branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>acarafat/SeqUtil<file_sep>/gene_search.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 10:50:36 2016
@author: arafat
"""
import urllib2
from Bio import Entrez
# This is an output of data mining using readTSVFile'gene list.tsv file')
info = {1667: ['NC_000008.11', '6977649', '6980122', 'minus'],
105881500: ['NW_012197698.1', '11850', '14308', 'minus']}
def fetchSource(gene_id):
''' This function can be used for obtaining nucleotide database accession,
from & to base positions and strand of a given gene id in gene database.
This function fetch source html of given id and find the fasta link information.
Only use when there is not enough information in the input file of
database record.
'''
url = 'http://www.ncbi.nlm.nih.gov/gene/?term=' + str(gene_id)
response = urllib2.urlopen(url)
html = response.read()
posInit = html.find("\"Nucleotide FASTA report\"")
posFinal = html.find("ref", posInit+31)
return html[posInit:posFinal]
def readSummaryFile(fileName):
'''
!!!Not developed!!!
'''
rawData = open(fileName).read().split('\n\n')
for data in rawData:
dataList = data.split('\n')
if '' in dataList == True:
dataList.remove('')
pass
def readTSVfile(fileName):
'''
Extract necessary information. Returns a dictionary.
{gene_id: [nt_accession, start_pos, end_pos, strand]}
if first two information not present about a field, need to use
fetchSource function to collect it from NCBI.
'''
rawData = open(fileName).read().split('\n')
info = {}
notFound = []
for record in rawData[1:]:
if record.split('\t')[-6] != '' or record.split('\t')[-5] != '':
info[int(record.split('\t')[2])] = [record.split('\t')[11], record.split('\t')[-6], record.split('\t')[-5], record.split('\t')[-4]]
else:
raw = fetchSource(int(record.split('\t')[2]))
try:
accession = raw.split('core/')[1].split('?')[0]
nt_start = raw[raw.find('from=')+5 : raw.find('&', raw.find('from='))]
if 'strand=true' in raw:
nt_end = raw[raw.find('to=')+3 : raw.find('&', raw.find('to='))]
nt_strand = 'minus'
else:
nt_end = raw[raw.find('to=')+3 : ]
nt_strand = 'plus'
info[int(record.split('\t')[2])] = [accession, nt_start, nt_end, nt_strand]
except:
notFound.append(int(record.split('\t')[2]))
continue
return info
# Fetch sequece using Entrez
def mineEntrez(paramInfo):
'''
Mine NCBI nucleotide database for defined sequence
'''
Entrez.email = '<EMAIL>'
seq = ''
for k in paramInfo.keys():
accID = paramInfo[k][0]
begin = paramInfo[k][1]
end = paramInfo[k][2]
if paramInfo[k][3] == 'plus':
s = 1
else:
s = 2
if '"' in end:
end = end[:end.find('"')]
handle = Entrez.efetch(db = 'nucleotide', id = str(accID),
rettype = 'fasta', retmode = 'text', strand = s,
seq_start = int(begin), seq_stop = int(end))
seq += handle.read()
return seq
if __name__ == '__main__':
readFile('alpha defensin gene database.txt')
<file_sep>/extract_cds_v0.2.py
# Extract CDS v 0.2
# Project: Alpha Defensin Evolutionary Analysis
# Date: 5 February 2015
# Author: ARF
# This script takes a nucleotide sequence as input along with 'join' information
# of CDS from genebank format of NCBI. Then it returns user a intron deleted CDS
# sequence.
import sys
print 'Please enter sequence here and press CONTROL+D to finish: \n'
s = sys.stdin.readlines()
join = raw_input('Please enter the "join" info and press ENTER: ')
seq = ''.join(s).replace('\n', '')
cdsN = ''
for i in join.split(','):
index = i.split('..')
cdsN += seq[int(index[0])-1: int(index[1])]
print cdsN
print len(cdsN)%3.0
<file_sep>/batch_SMART.py
# SMART Batch Analysis
import mechanize
from bs4 import BeautifulSoup
from time import sleep
br = mechanize.Browser()
def extract_domain(output):
### handle output of request
soup = BeautifulSoup(output)
viewer_wrap = soup.findAll('div', attrs = {'id':'viewerWrap'})[0]
domains = str(viewer_wrap).split('smart=')[1].split('+\"')[0].split(':')[1]
print domains
def handle_output(output):
try:
extract_domain(output)
except IndexError:
jobid = output.split('jobid=')[1].split('\"')[0]
url = 'http://smart.embl-heidelberg.de/smart/job_status.pl?jobid='+jobid
response = br.open(url)
output = response.read()
extract_domain(output)
#br.set_all_readonly(False) # allow everything to be written to
br.set_handle_robots(False) # ignore robots
br.set_handle_refresh(False) # can sometimes hang without this
br.addheaders = [('User-agent', 'Firefox')] # [('User-agent', 'Firefox')]
# Open a webpage and inspect its contents
response = br.open('http://smart.embl-heidelberg.de/smart/set_mode.cgi?NORMAL=1')
# Form for sequence analysis
br.select_form(nr=1)
#br.form = list(br.forms())[1]
br.form['SEQUENCE'] = 'MKTLVLLSALFLLAFQVQADPIQNTDEETNTEVQPQEEDQAVSVSFGNPEGSDLQEESLRDLGCYCRKRGCTRRERINGTCRKGHLMYTLCCL'
req = br.submit()
output = req.read()
#print output
#br.back()
if 'entered our processing' in output:
sleep(10)
jobid = output.split('jobid=')[1].split('\"')[0]
url = 'http://smart.embl-heidelberg.de/smart/job_status.pl?jobid='+jobid
response = br.open(url)
output = response.read()
extract_domain(output)
else:
extract_domain(output)
<file_sep>/find_na_acc.py
# NA Accession finder
# Alpha Defensin Project
# For Mining PSI BLAST Output
# <NAME>
# 25 April 2016
# What it does:
# Inspect gb entry.
# Go to xref for gene database if present.
# Extract NA accession number
# Extract NA sequence using join information in genbank file
# Import Modules
#from Bio import SeqIO
#from Bio import Entrez
import urllib2
from time import sleep
# Import Datasets
from find_na_acc_dump import geneID, links
# Remove duplicates in links
unique_links = list(set(links))
unique_links.remove('')
# Define e-mail for Entrez search using Biopython
#Entrez.email = '<EMAIL>'
def extract_geneID(handle):
'''
Objective: Extract db_xref qualifier from CDS feature of a GenBank entry
only if it contain GeneID key.
Input: A file containing GenBank sequences
Output: A list containing entry of db_xref that refers to NCBI Gene database
'''
db_xref = []
for record in SeqIO.parse(handle, 'genbank'):
for feature in record.features:
if feature.type == 'CDS':
try:
if 'GeneID' in ''.join(feature.qualifiers['db_xref']):
GeneID = [int(i.split(':')[1]) for i in feature.qualifiers['db_xref'] if 'GeneID' in i][0]
#db_xref.append(feature.qualifiers['db_xref'])
db_xref.append(GeneID)
except:
pass
return db_xref
def extract_NA_acc(GeneID):
'''
Objective: Extract accession number of nucleotide sequence
from a single gene id
Input: A GeneID
Output: A Nucleotide Accession Number
'''
url = 'http://www.ncbi.nlm.nih.gov/gene/?term=' + str(GeneID)
response = urllib2.urlopen(url)
html = response.read()
start = html.find('Go to nucleotide:</strong>')
end = html.find('GenBank</a>', start)
target = html[start:end].split('href=')[-1].split('ref')[0]
return target.strip().replace('"','')
def extract_NA_sequence(link):
'''
Objective: Extract CDS from genbank file using its join info.
Input: Link to genbank file
Output: CDS
'''
acc = link.split('/')[2].split('?')[0]
start_pos = int(link.split('=')[-2].split('&')[0])
try:
stop_pos = int(link.split('=')[-1])
except:
stop_pos = int(links[1].split(';')[-2].split('=')[-1].split('&')[0])
try:
handle = Entrez.efetch(db='nucleotide', rettype = 'gb', retmode = 'text',
seq_start = start_pos, seq_stop = stop_pos, id = acc)
record = SeqIO.read(handle, 'genbank')
for feature in record.features:
if feature.type =='CDS':
join = feature.location
cds = join.extract(record.seq)
return record.id, record.description, cds
except:
print acc, 'not found!'
if __name__ == '__main__':
#handle = '../Dataset/psi_blast_NP_001289194.1.gb'
#db_xref = extract_geneID(handle)
#url_target = []
#count = 1
#for i in geneID:
# print 'Progress: ', count, '/', len(geneID)
# count += 1
# url_target.append(extract_NA_acc(i))
#print ''
#print url_target
#cds_sequences = []
#count = 1
#for entry in unique_links:
# print 'Progress: ', count, '/', len(links)
# output = extract_NA_sequence(entry)
# cds_sequences.append(output)
# count += 1
# if count%3 == 0:
# sleep(3)
pass
<file_sep>/seqspliter_v0.3.py
# Split Sequence
# Project: Alpha Defensin
# Task: Split def domain encoding region from propeptide.
# Arafat
# 27 February 2016
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
def file_input(filename, header= False):
'''
csv file in and pre processing
Input: a csv which do not have table-header. If header present,
header = True should be used.
Output: a list containing sequence id and index for splitting
'''
readcsv = open(filename, 'r').read()
if header == True:
csv_data = readcsv.split('\n')[1:]
else:
csv_data = readcsv.split('\n')
if '' in csv_data:
csv_data.remove('')
return csv_data
def get_index(csv_data):
'''
Split csv_data entry on ',' and then store given index position
Input: start and stop position
Output: a dictionary whose key is sequence id/description and value is
start and stop position
'''
# indices info from csv file
indices = [[i.split(',')[0],i.split(',')[1], i.split(',')[2],
i.split(',')[3], i.split(',')[4]] for i in csv_data]
return indices
def original_sequences(seq_file):
'''
Load sequence in a dictionary for splitting
'''
seq_record = [[i.description, i.seq] for i in SeqIO.parse(seq_file, 'fasta')]
return seq_record
def split_sequences(indices, seq, start, end):
# splitting sequence
# The problem is here
splitted_seq = []
count = 0
for i in indices.keys():
seq_id = '_'.join(i.split('_')[0:2])[1:]
for d in seq.keys():
if seq_id in d:
count += 1
try:
sub_seq = SeqRecord(seq[d][int(indices[i][start])*3:int(indices[i][end])*3+4], id = seq_id, description = d)
splitted_seq.append(sub_seq)
except:
pass
break
return splitted_seq
if __name__ == '__main__':
csv_data = file_input('../Dataset/SMART-Analysis-Information-All.csv', True)
indices = get_index(csv_data)
seq = original_sequences('../Dataset/def_seqs_CDS.fas')
#splitted_seq = split_sequences(indices, seq, 0, 3)
#SeqIO.write(splitted_seq, '../Dataset/propeptides.fas', 'fasta')
<file_sep>/change_fasta_description.py
# Update Fasta Description
# Arafat
# 20 April 2016
from Bio import SeqIO
#target fasta file to change description
target_file = '../Dataset/new_genomes/zika-genomeapril-june_no-5-utr.fas'
#preporcess csv file containing sequence meta-information
raw = open('../Dataset/new_genomes/zika_genome_new-25.csv').read().split('\n')
raw.remove('')
meta_info = {i.split(',')[0].strip():i.split(',') for i in raw}
# Initiate list to store updated sequence record
store = []
# Update sequence record
for seq_record in SeqIO.parse(target_file, 'fasta'):
gb_acc = seq_record.id.split('|')[-2].strip()
if gb_acc in meta_info.keys():
seq_record.id = ''
seq_record.description = gb_acc+'_'+'_'.join(meta_info[gb_acc]).strip()
store.append(seq_record)
# Write updated sequence records in a file
SeqIO.write(store, '../Dataset/new_genomes/25genome_updated.fasta', 'fasta')
|
03f2e2e9a9b1d2e8f1e769f18e10cef2db21c303
|
[
"Python"
] | 6 |
Python
|
acarafat/SeqUtil
|
d5507fac02cd5b0c7ed2cfdc0fa1611ef30cdb12
|
780832739f9714210079fac029accc0aa4bd2586
|
refs/heads/master
|
<file_sep>package com.ag_automation_demo.page_objects;
import android.support.annotation.IdRes;
import com.ag_automation_demo.Assert;
import com.ag_automation_demo.R;
import static android.support.test.espresso.Espresso.closeSoftKeyboard;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* Calculator page object
*/
public class CalculatorPage implements IPageObject
{
public enum CalcField { MSRP, DOWN_PAYMENT, LOAN_TERM, APR }
public CalculatorPage()
{
}
@Override
public CalculatorPage isLoadSuccessful()
{
Assert.viewDisplayedWithId(R.id.tv_current_vehicle);
return this;
}
public CalculatorPage clickEditVehicleName()
{
onView(withId(R.id.btn_edit_name))
.perform(click());
return this;
}
public CalculatorPage modifyVehicleName(String value)
{
onView(withId(R.id.et_current_vehicle))
.perform(click(), clearText(), typeText(value));
return this;
}
public CalculatorPage clickSaveVehicleName()
{
onView(withId(R.id.btn_save_name))
.perform(click());
return this;
}
public CalculatorPage modifyCalculation(CalcField field, String value)
{
@IdRes int resourceId;
switch (field)
{
case MSRP:
resourceId = R.id.et_msrp;
break;
case DOWN_PAYMENT:
resourceId = R.id.et_down_payment;
break;
case LOAN_TERM:
resourceId = R.id.et_loan_term;
break;
case APR:
resourceId = R.id.et_apr;
break;
default:
resourceId = -1;
break;
}
onView(withId(resourceId))
.perform(click(), clearText(), typeText(value));
closeSoftKeyboard();
return this;
}
public CalculatorPage clickSaveEntry()
{
onView(withId(R.id.btn_save_entry))
.perform(click());
return this;
}
}
<file_sep>package com.ag_automation_demo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.ag_automation_demo.utility.Extra;
import com.ag_automation_demo.utility.Utility;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
private final Context _context = this;
private ArrayList<LoanItem> _loanItems;
private LoanListAdapter _loanListAdapter;
// Request codes
public final int NEW_ENTRY_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
// Inflate alert dialog xml
LayoutInflater li = LayoutInflater.from(_context);
View dialogView = li.inflate(R.layout.custom_dialog, null);
final AlertDialog dialog = new AlertDialog.Builder(_context)
.setTitle(R.string.new_entry)
.setIcon(R.mipmap.ic_launcher)
.setView(dialogView)
.setCancelable(false)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create();
final TextInputEditText userInput = (TextInputEditText) dialogView
.findViewById(R.id.et_input);
dialog.setOnShowListener(new DialogInterface.OnShowListener()
{
@Override
public void onShow(DialogInterface dialogInterface)
{
Button buttonPositive = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
buttonPositive.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String userInputText = userInput.getText().toString();
if (Utility.isNullOrEmpty(userInputText))
{
userInput.setError(getString(R.string.value_required));
return;
}
Intent intent = new Intent(_context, CalculatorActivity.class);
intent.putExtra(Extra.VEHICLE_NAME, userInputText);
startActivityForResult(intent, NEW_ENTRY_REQUEST);
dialog.dismiss();
}
});
Button buttonNegative = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
buttonNegative.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
dialog.cancel();
}
});
}
});
// Show dialog
dialog.show();
}
});
// Setup list view
_loanItems = new ArrayList<>();
ListView lvLoans = (ListView) findViewById(R.id.lv_loans);
_loanListAdapter = new LoanListAdapter(this, _loanItems);
lvLoans.setAdapter(_loanListAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case NEW_ENTRY_REQUEST:
Bundle bundle = data.getExtras();
if (bundle != null)
{
String vehicleName = bundle.getString(Extra.VEHICLE_NAME);
String monthlyPayment = bundle.getString(Extra.MONTHLY_PAYMENT);
String downPayment = bundle.getString(Extra.DOWN_PAYMENT);
String loanInfo = String.format(getString(R.string.loan_info), monthlyPayment, downPayment);
_loanItems.add(new LoanItem(vehicleName, loanInfo));
}
_loanListAdapter.notifyDataSetChanged();
break;
}
}
}
}
<file_sep>package com.ag_automation_demo.utility;
/**
* Extras to pass via intent
*/
public class Extra
{
public static final String VEHICLE_NAME = "VEHICLE_NAME";
public static final String MONTHLY_PAYMENT = "MSRP";
public static final String DOWN_PAYMENT = "DOWN_PAYMENT";
}
<file_sep>package com.ag_automation_demo;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Custom adapter for loan item list view
*/
public class LoanListAdapter extends ArrayAdapter<LoanItem>
{
public LoanListAdapter(Context context, ArrayList<LoanItem> data)
{
super(context, 0, data);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
// Get the data item for this position
LoanItem loanItem = getItem(position);
ViewHolder viewHolder;
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.loan_list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvVehicleName = (TextView) convertView.findViewById(R.id.tv_vehicle_name);
viewHolder.tvLoanInfo = (TextView) convertView.findViewById(R.id.tv_loan_info);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
if (loanItem != null)
{
// Populate the data into the template view using the data object
viewHolder.tvVehicleName.setText(loanItem.vehicleName);
viewHolder.tvLoanInfo.setText(loanItem.loanInfo);
}
return convertView;
}
private static class ViewHolder
{
TextView tvVehicleName;
TextView tvLoanInfo;
}
}
<file_sep>package com.ag_automation_demo.page_objects;
/**
* Define common page object functionality
*/
interface IPageObject
{
// This is the only function that should have an assertion within a page object
// as a quick way to check that a page is loaded after a set of actions
IPageObject isLoadSuccessful();
}
|
55511dc0d101c746e8ce807daecf885eeab4cd0d
|
[
"Java"
] | 5 |
Java
|
artificialnerd/AG_Automation_Demo
|
5daa320cc7bbdc3858082405b258b689e56f21fe
|
9f25df8660565d08027e82afff0a15b8579a5c54
|
refs/heads/master
|
<file_sep>#
# Parser data of partners from hansemerkur.de and export to csv-file
#
# Created by <NAME>
# email: d.vandyshev (doggy) ya.ru
# skype: d.vandyshev,
# freelancer.com: https://www.freelancer.com/u/vandyshev.html
# odesk/upwork.com: https://www.upwork.com/users/~0171345aa6fedb4083
#
class ParserHansemerkurPartners
require 'sequel'
require 'mechanize'
require 'logger'
require 'singleton'
require 'csv'
require 'rubygems'
exit if Object.const_defined?(:Ocra)
BASE_URL = 'http://www.hansemerkur.de'
CSV_OUT_FILE = 'hansemerkur_partners.csv'
POSTCODES_FILE = 'PLZ.txt'
class ::String
def clean
self.gsub(/\u00a0/, ' ').strip # remove symbol
end
end
Partner = Struct.new(
:email_prefix,
:p_name,
:p_job,
:p_street,
:p_zip,
:p_city,
:p_tel,
:p_fax,
:p_mob,
:agency,
:image,
:www,
:email,
:postcode
)
def initialize
# Logging
@log = Log.instance
@log.info 'Start parser partners from hansemerkur.de'
# Database
@log.info 'Create DB if not exist'
db = Sequel.connect('sqlite://partners.sqlite')
db.create_table? :partners do
primary_key :id
String :email_prefix
String :p_name
String :p_job
String :p_street
String :p_zip
String :p_city
String :p_tel
String :p_fax
String :p_mob
String :agency
String :image
String :www
String :email
String :postcode
end
@table_partners = db[:partners]
db.create_table? :postcodes do
primary_key :id
String :postcode
end
@table_postcodes = db[:postcodes]
@log.info 'Set mechanize for HTTP'
# HTTP client
@mech = Mechanize.new { |agent|
agent.user_agent_alias = 'Windows Chrome'
agent.follow_meta_refresh = true
}
end
def start
@log.info 'Read postcodes'
postcodes = read_postcodes
@log.info 'Get pages with partners'
postcodes.each do |pc|
next unless @table_postcodes.where(postcode: pc).empty?
url = partners_url(pc)
# Get all partners from this postcode
partners = []
loop do
@log.info "Postcode #{pc}. Parse page #{url}\n\t"
page = @mech.get url
page.parser.css('div#aktionsbereich-kontact-agent-search-result-container').each do |container|
p = Partner.new
p.agency = 'Hanse Merkur'
p.postcode = pc
# Name
node_p_name = container.at('div.aktionsbereich-kontact-agent-search-result-heading')
p.p_name = node_p_name.text.clean
# Job
p.p_job = node_p_name.next_element.text.clean
# Image
p.image = BASE_URL + container.at('img').attribute('src').text.sub(/\s+/, '') unless container.at('img').nil?
count = 1
container.css('div#aktionsbereich-kontact-agent-search-result-container-right tr').each do |tr|
p.p_street = tr.text.clean if count == 1
if count == 2
p.p_zip, p.p_city = tr.css('span').text.split
end
p.p_tel = tr.text.sub('Telefon:', '').clean if tr.text.include? 'Telefon'
p.p_fax = tr.text.sub('Telefax:', '').clean if tr.text.include? 'Telefax'
p.p_mob = tr.text.sub('Mobil:', '').clean if tr.text.include? 'Mobil'
p.email = tr.text.sub('E-Mail:', '').clean if tr.text.include? 'E-Mail'
p.www = tr.text.sub('Homepage:', '').clean if tr.text.include? 'Homepage'
count += 1
end
p.email_prefix = p.email[/^(.+)@/, 1]
@log.info "\t#{p}"
partners << p.to_h
end
# Exist next page?
next_page_node = page.at('div.agent-search-page-links > a')
unless next_page_node.nil?
url = next_page_node.attribute('href').text
next
end
break
end
@table_partners.multi_insert partners
@table_postcodes.insert(postcode: pc)
end
@log.info 'Export to csv ' + CSV_OUT_FILE
export_to_csv
end
private
def export_to_csv
CSV.open(CSV_OUT_FILE, 'wb') do |csv|
csv << %w[email_prefix id p_name p_firstname p_lastname zusatz p_job p_street p_zip p_city p_tel p_fax p_mob
agency image title www email]
added = []
local_id = 1
@table_partners.each do |p|
# Skip duplicates
this_partner = {name: p[:p_name], phone: p[:p_tel], mail: p[:email]}
next if added.include? this_partner
added << this_partner
# Extract firstname, lastname, zusatz as separate fields
p[:p_firstname], p[:p_lastname] = p[:email_prefix].split('.').map(&:capitalize)
p[:zusatz] = p[:p_name].sub(/#{p[:p_firstname]}/i, '').sub(/#{p[:p_lastname]}/i, '').strip
csv << [p[:email_prefix], local_id, p[:p_name], p[:p_firstname], p[:p_lastname], p[:zusatz], p[:p_job],
p[:p_street], p[:p_zip], p[:p_city], p[:p_tel], p[:p_fax],
p[:p_mob], p[:agency], p[:image], p[:title], p[:www], p[:email]]
local_id += 1
end
end
end
# Read file with postcodes in Germany
def read_postcodes
pc = IO.readlines(POSTCODES_FILE)
pc.map { |s| s.strip! }
pc.delete_if { |s| s.length != 5 || s.to_i == 0 }
end
# Form url for given postcode
def partners_url(pc)
u = ''
u << 'http://www.hansemerkur.de/agentsearch?p_p_id=Agent_Search&p_p_lifecycle=0'
u << '&p_p_state=normal&p_p_mode=view&p_p_col_id=column-2&p_p_col_count=2'
u << '&_Agent_Search_struts_action=%2Fext%2Fagent_search%2Fsearch_agent&_Agent_Search_delta=20'
u << '&_Agent_Search_keywords=&_Agent_Search_advancedSearch=false&_Agent_Search_andOperator=true'
u << '&_Agent_Search_city=&_Agent_Search_mile=20km&_Agent_Search_name='
u << '&_Agent_Search_zip=' + pc + '&_Agent_Search_searchBy=zip'
u << '&cur=1'
end
# MultiIO fo logging
class MultiIO
def initialize(*targets)
@targets = targets
end
def write(*args)
@targets.each { |t| t.write(*args) }
end
def close
@targets.each(&:close)
end
end
# Singleton logger
class Log < Logger
include Singleton
# ParserHansemerkurPartners::LOG::
@@old_initialize = Logger.instance_method :initialize
def initialize
log_file = File.open(File.basename(__FILE__, '.*') + '.log', 'a')
@@old_initialize.bind(self).call(MultiIO.new(STDOUT, log_file), 0, 1024 * 1024)
end
end
end
ParserHansemerkurPartners.new.start
puts 'Successfully! Press Enter to exit'
gets
<file_sep># Parser partners from hansemerkur.de
## Units of parser
1. ~~Read file 'PLZ.txt' with postcodes in array~~
2. ~~Create sqlite3 DB if not exist - structure~~
```
id int
email_prefix string
p_name
p_job
p_street
p_zip
p_tel
p_fax
p_mob
agency
image
title
www
email
```
3. ~~Loop for postcodes and request page with partners from area. http://www.hansemerkur.de/~~
```
GET page 3: 11-15
http://www.hansemerkur.de/agentsearch?
p_p_id=Agent_Search
&p_p_lifecycle=0
&p_p_state=normal
&p_p_mode=view
&p_p_col_id=column-2
&p_p_col_count=2
&_Agent_Search_struts_action=%2Fext%2Fagent_search%2Fsearch_agent
&_Agent_Search_delta=20
&_Agent_Search_keywords=
&_Agent_Search_advancedSearch=false
&_Agent_Search_andOperator=true
&_Agent_Search_city=
&_Agent_Search_mile=20km
&_Agent_Search_name=
&_Agent_Search_zip=10783
&_Agent_Search_searchBy=zip
&cur=3
```
4. ~~Get all pages with partners (if numbers of pages > 1).~~
5. ~~Parse partners data to struct~~
6. ~~Export all partners to DB and mark this postcode as completed~~
7. ~~At the end get data from DB and export to csv-file~~
8. ~~Remove duplicates~~
9. Added new fields: firstname, lastname, zusatz
|
10399f6c9a937d4c104592737a0caf6d08db61ae
|
[
"Markdown",
"Ruby"
] | 2 |
Ruby
|
d-vandyshev/parser_hansemerkur.de_partners
|
a9d75c4a1efb3d66bb7fa1f64e1ee2d040ed6678
|
a03b2ee817138d1d4335c3671b69d705c76880b6
|
refs/heads/main
|
<repo_name>RoselineMnguni/MyOnlineCv<file_sep>/main.js
/*----- SCROLL REVEAL ANIMATION -----*/
const sr = ScrollReveal({
origin: 'top',
distance: '80px',
duration: 2000,
reset: true
});
/*------ SCROLL HOME -------*/
sr.reveal('.home' ,{});
sr.reveal('.socialmedia-handles',{ interval: 200});
/*------ SCROLL ABOUT --------*/
sr.reveal('.profile-img',{});
sr.reveal('.section-title',{delay:200});
sr.reveal('.About-subtitle',{delay: 200});
sr.reveal('.About-text',{delay: 400});
/*------ SCROLL Profile--------*/
sr.reveal('.profile-title',{});
sr.reveal('.academic-timeline',{ interval: 200});
/*------ SCROLL Services--------*/
sr.reveal('.service-title',{});
sr.reveal('.service-item',{ interval: 200});
/*------- SCROLL Interents---------*/
sr.reveal('.interest-title',{});
sr.reveal('.interest-img',{interval: 200});
/*SCROLL CONTACT*/
sr.reveal('.contact-input',{interval: 200});
<file_sep>/README.md
# MyOnlineCv
|
07803d6aba5ae0716122b05a402b3af60e1bb970
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
RoselineMnguni/MyOnlineCv
|
384ad77b4b2d4534b35a08c8759dc040ba6f88b3
|
b494e955d3df6f8c64bf8aee05c2d9a954bb79ef
|
refs/heads/master
|
<repo_name>Ankioro/adalidremoto<file_sep>/adalidJavaSencillo/src/adalidJavaSencillo/HectorFetch.java
package adalidJavaSencillo;
public class HectorFetch {
}
|
aa1699c7d018d3d6aeecc125da805d5f90ad21be
|
[
"Java"
] | 1 |
Java
|
Ankioro/adalidremoto
|
1ae0022dea405e0e65c4eb679c39726404a6e571
|
a949f2ba4b8a550092c0aaca252cd83883928578
|
refs/heads/master
|
<file_sep># currency-exchange-rate
Получение актуальных обменных курсов валют.
Класс CurrencyExchangeRate позволяет получить актуальные обменные курсы 168 валют с помощью web-сервиса https://currencylayer.com.
Для использования этого web-сервиса необходимо создать бесплатный аккаунт на сайте https://currencylayer.com и получить там ключ доступа (ACCESS_KEY).
Получить курсы всех 168 валют можно с помощью метода getExchangeRates(), данные записываются (кэшируются) в файл. Полный путь к кэш-файлу нужно указать в конструкторе класса CurrencyExchangeRate. Кэш-файл нужен для минимизации обращений к HTTP API, поскольку количество запросов для бесплатных аккаунтов ограничено.
Чтобы получить обменный курс заданной валюты относительно другой, нужно вызвать метод getExchangeRate, передав в аргументы коды этих валют.
Инструмент предназначен для использовния с PHP-фреймворком Laravel, но может быть легко переделан для других фреймворков.
Пример использования для получения курса евро относительно доллара и конвертации 100 евро в доллары:
// access key for free account form HTTP API https://currencylayer.com
$accessKey = 'your-access-key';
// full path to cache file to save currency exchange rates
$pathToCacheFile = 'full-path-to-cache-file';
try {
// create CurrencyExchangeRate instance
$currencyTool = new CurrencyExchangeRate($accessKey, $pathToCacheFile);
// get currency exchange rates from HTTP API https://currencylayer.com
// and save it in a cache file
$rates = $currencyTool->getExchangeRates();
// returns array [
// "USDAED" => 3.673102
// "USDAFN" => 75.838566
// "USDAMD" => 479.809805
// ...
// get exchange rate EUR/USD
$rate = $currencyTool->getExchangeRate('EUR', 'USD');// 1.08172
// convert 100 EUR to USD
$price = $currencyTool->convert(100, 'EUR', 'USD');// 108.172
} catch (\Exception $e) {
echo "\n" . 'Error: ' . $e->getMessage() . "\n";
}
<file_sep><?php
namespace App\Services\CurrencyExchangeRate;
use GuzzleHttp;
use Storage;
use App\Services\CurrencyExchangeRate\Cache;
/**
* Class CurrencyExchangeRate.
* Tool for obtaining currency exchange rates.
*/
class CurrencyExchangeRate
{
/**
* HTTP API URL
*/
const API_URL = 'http://api.currencylayer.com/live';
/**
* @var string Access Key for HTTP API https://currencylayer.com
*/
public $api_access_key;
/**
* @var string The path to the cache file where currency exchange
* rates are stored.
*/
public $path_to_cache_file;
/**
* @var Cache The class for caching currency exchange rates to a file.
*/
protected $cache;
/**
* @var integer Number of digits after the decimal point for
* currency exchange rates.
*/
protected $precision;
/**
* Create a new CurrencyExchangeRate class instance.
*
* @param string $api_access_key Access Key for HTTP API https://currencylayer.com
* @param string $path_to_cache_file The path to the cache file where
currency exchange rates are stored.
*/
public function __construct($api_access_key, $path_to_cache_file)
{
if (empty($api_access_key)){
throw new \Exception('API access key not specified.');
}
if (empty($path_to_cache_file)){
throw new \Exception('Path to cache file not specified.');
}
$this->api_access_key = $api_access_key;
$this->path_to_cache_file = $path_to_cache_file;
$this->cache = new Cache($this->path_to_cache_file);
$this->precision = 6;
}
/**
* Get currency exchange rates for 168 currencies from HTTP API
* https://currencylayer.com and save it in a cache file.
*
* @return array Currency exchange rates
*/
public function getExchangeRates()
{
$rates = $this->getExchangeRatesFromHttpApi();
$this->cache->save($rates);
return $rates;
}
/**
* Get currency exchange rate.
*
* For example, exchange rate 'EUR'/'USD' can be obtained
* by calling this method with such arguments: getExchangeRate('EUR', 'USD').
*
* @param string $currencyFrom Currency code, the value of which must
* be obtained in another currency ($currencyTo).
* @param string $currencyTo Currency code in which you want to get the value
* of the currency with the code $currencyFrom.
* @param integer|null $precision Number of digits after the decimal
* point for exchange rate.
* @return float Currency exchange rate.
*/
public function getExchangeRate($currencyFrom, $currencyTo, $precision = null)
{
if (!($rates = $this->getExchangeRatesFromCache())) {
throw new \Exception('Data retrieving error.');
}
$precision = $precision ?? $this->precision;
if ($currencyFrom == 'USD') {
if (!isset($rates['USD' . $currencyTo])) {
throw new \Exception('Data format error.');
}
return round(
(float)($rates['USD' . $currencyTo]),
$precision
) ?? false;
}
if ($currencyTo == 'USD') {
if (!isset($rates['USD' . $currencyFrom])) {
throw new \Exception('Data format error.');
}
return isset($rates['USD' . $currencyFrom]) ? round(
(float)(1/$rates['USD' . $currencyFrom]),
$precision
) : false;
}
if (!isset($rates['USD' . $currencyFrom]) ||
!isset($rates['USD' . $currencyTo])
) {
throw new \Exception('Data format error.');
}
return round(
(float)($rates['USD' . $currencyTo] / $rates['USD' . $currencyFrom]),
$precision
);
}
/**
* Convert money.
*
* For example, to convert 100 EUR to USD, you must call this method with
* such arguments: convert(100, 'EUR', 'USD').
*
* @param float|integer $amount Money amount.
* @param string $currencyFrom Currency code, the value of which must
* be obtained in another currency ($currencyTo).
* @param string $currencyTo Currency code in which you want to get the value
* of the currency with the code $currencyFrom.
* @param integer|null $precision Number of digits after the decimal
* point for convertion result.
* @return float
*/
public function convert($amount, $currencyFrom, $currencyTo, $precision = null)
{
if (!($rate = $this->getExchangeRate($currencyFrom, $currencyTo))) {
return null;
}
return round((float)$amount * $rate , $precision ?? $this->precision);
}
/**
* Set number of digits after the decimal point for currency exchange rates.
*
* @param integer $precision Number of digits after the decimal point for
* currency exchange rates.
*/
public function setPrecision($precision)
{
if (!is_int($precision)) {
throw new \Exception('Precision must be an integer.');
}
$this->precision = $precision;
}
/**
* Get number of digits after the decimal point for currency exchange rates.
*
* @return integer
*/
public function getPrecision()
{
return $this->precision;
}
public function getExchangeRatesFromHttpApi()
{
$url = self::API_URL . '?access_key=' . $this->api_access_key;
$client = new GuzzleHttp\Client();
try {
$response = $client->request('GET', $url, ['timeout' => 10]);
} catch (\Throwable $e) {
throw new \Exception('API connection error: Guzzle exception.');
}
if (empty($response) ||
$response->getStatusCode() != 200 ||
empty($response->getBody())
) {
throw new \Exception('API response error.');
}
$data = \json_decode($response->getBody(), true);
if (!$data || empty($data['success']) || empty($data['quotes'])) {
throw new \Exception('Response data format error.');
}
return $data['quotes'];
}
public function getExchangeRatesFromCache()
{
return $this->cache->get();
}
}
<file_sep><?php
namespace App\Services\CurrencyExchangeRate;
use Illuminate\Filesystem\Filesystem;
/**
* Class Cache.
* The class is designed to cache currency exchange rates to a file.
*/
class Cache
{
/**
* @var string The path to the cache file where currency exchange rates are stored.
*/
public $path_to_cache_file;
/**
* Create a new Cache class instance.
*
* @param string $path_to_cache_file The path to the cache file where currency
* exchange rates are stored.
*/
public function __construct($path_to_cache_file)
{
if (empty($path_to_cache_file)) {
throw new \Exception('Path to cache file not specified.');
}
$this->path_to_cache_file = $path_to_cache_file;
}
/**
* Get currency exchange rates from cache file.
*
* @return array Currency exchange rates.
*/
public function get()
{
$filesystem = new Filesystem;
if (!$filesystem->exists($this->path_to_cache_file)) {
throw new \Exception('Cache file not exists.');
}
return \json_decode($filesystem->get($this->path_to_cache_file), true);
}
/**
* Save currency exchange rates to cache file.
*
* @param array $rates Currency exchange rates.
*/
public function save($rates)
{
(new Filesystem)->put(
$this->path_to_cache_file,
\json_encode($rates, JSON_PRETTY_PRINT)
);
}
public function clear()
{
(new Filesystem)->delete($this->path_to_cache_file);
}
}
|
a2506c78d0eef284d3aeebc85561b342eb7fa638
|
[
"Markdown",
"PHP"
] | 3 |
Markdown
|
yakov-lazorenko/currency-exchange-rate
|
e5628786ddf78676fe9a9210f4fce0559c7f15a9
|
8eefdb27b7c71196a8ffa9bc661380eea793ae33
|
refs/heads/master
|
<file_sep>fout = open("Imageout.txt","w")
fin = open("Image.txt","r")
count=0
for line in fin:
line = line[:-1]
fout.write("\t")
fout.write(str(count))
fout.write("\t")
fout.write(":")
fout.write("\t")
fout.write(line)
fout.write(";")
fout.write("\n")
count += 1<file_sep># Custom-processor-for-image-down-sampling
This repository contains a custom processor and an UART transceiver build using Verilog for the task of image downsampling
>>Refer the report for more information
Required Software
>MATLAB
>Quartus
Hardware
>Altera DE2-115 development board

How to use
> Write the code using the instructions in the ISA
>Convert it to the machine instructions using the given compiler
>Save it to the instruction memory using Quartus software
>Send the image using the matlab code and wait till the recieving is complete
Performance
>It takes around 2 minuts for the transmission
>less than 1 second for the downsampling
>ability to downsample maximum of 256x256x3 image
following diagrams shows the architecture, state diagram and datapath of the processor



|
17f2ec86b0bca0007a15c4150c5e2d314c3e6853
|
[
"Markdown",
"Python"
] | 2 |
Python
|
sahanHe/Custom-processor-for-image-down-sampling
|
501aafd7f6838e778065af79ce385ad5552ba73d
|
7ba03f516df7ad662662e1380510a03598c2da07
|
refs/heads/master
|
<file_sep>package com.wbrawner.budgetserver.transaction;
import com.wbrawner.budgetserver.budget.Budget;
import com.wbrawner.budgetserver.category.Category;
import com.wbrawner.budgetserver.user.User;
import javax.persistence.*;
import java.time.Instant;
@Entity
public class Transaction implements Comparable<Transaction> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private final Long id = null;
@ManyToOne
@JoinColumn(nullable = false)
private final User createdBy;
private String title;
private String description;
private Instant date;
private Long amount;
@ManyToOne
private Category category;
private Boolean expense;
@ManyToOne
@JoinColumn(nullable = false)
private Budget budget;
public Transaction() {
this(null, null, null, null, null, null, null, null);
}
public Transaction(String title,
String description,
Instant date,
Long amount,
Category category,
Boolean expense,
User createdBy,
Budget budget) {
this.title = title;
this.description = description;
this.date = date;
this.amount = amount;
this.category = category;
this.expense = expense;
this.createdBy = createdBy;
this.budget = budget;
}
public Long getId() {
// This should only be set from Hibernate so it shouldn't actually be null ever
//noinspection ConstantConditions
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Instant getDate() {
return date;
}
public void setDate(Instant date) {
this.date = date;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Boolean getExpense() {
return expense;
}
public void setExpense(Boolean expense) {
this.expense = expense;
}
public User getCreatedBy() {
return createdBy;
}
public Budget getBudget() {
return budget;
}
public void setBudget(Budget budget) {
this.budget = budget;
}
@Override
public int compareTo(Transaction other) {
return this.date.compareTo(other.date);
}
}<file_sep>package com.wbrawner.budgetserver.budget;
import com.wbrawner.budgetserver.category.Category;
import com.wbrawner.budgetserver.transaction.Transaction;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
@Entity
public class Budget {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String description;
private String currencyCode;
@OneToMany(mappedBy = "budget")
private final Set<Transaction> transactions = new TreeSet<>();
@OneToMany(mappedBy = "budget")
private final Set<Category> categories = new TreeSet<>();
@OneToMany(mappedBy = "budget")
private final Set<Transaction> users = new HashSet<>();
public Budget() {}
public Budget(String name, String description) {
this(name, description, "USD");
}
public Budget(String name, String description, String currencyCode) {
this.name = name;
this.description = description;
this.currencyCode = currencyCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public Set<Transaction> getTransactions() {
return transactions;
}
public Set<Category> getCategories() {
return categories;
}
public Set<Transaction> getUsers() {
return users;
}
}
<file_sep>package com.wbrawner.budgetserver.permission;
public enum Permission {
/**
* The user can read the content but cannot make any modifications.
*/
READ,
/**
* The user can read and write the content but cannot make any modifications to the container of the content.
*/
WRITE,
/**
* The user can read and write the content, and make modifications to the container of the content including things like name, description, and other users' permissions (with the exception of the owner user, whose role can never be removed by a user with only MANAGE permissions).
*/
MANAGE,
/**
* The user has complete control over the resource. There can only be a single owner user at any given time.
*/
OWNER;
public boolean isNotAtLeast(Permission wanted) {
return ordinal() < wanted.ordinal();
}
}
<file_sep>spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/budget
spring.datasource.username=budget
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.profiles.active=prod
spring.session.jdbc.initialize-schema=always
spring.datasource.testWhileIdle=true
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.validationQuery=SELECT 1
twigs.cors.domains=*
<file_sep>FROM openjdk:14-jdk as builder
MAINTAINER <NAME> <<EMAIL>>
RUN groupadd --system --gid 1000 gradle \
&& useradd --system --gid gradle --uid 1000 --shell /bin/bash --create-home gradle
COPY --chown=gradle:gradle . /home/gradle/src
WORKDIR /home/gradle/src
RUN /home/gradle/src/gradlew --console=plain --no-daemon bootJar
FROM openjdk:14-jdk-slim
EXPOSE 8080
COPY --from=builder /home/gradle/src/api/build/libs/api.jar twigs-api.jar
CMD /usr/java/openjdk-14/bin/java $JVM_ARGS -jar /twigs-api.jar
<file_sep>package com.wbrawner.budgetserver.category;
public class UpdateCategoryRequest {
private final String title;
private final String description;
private final Long amount;
private final Boolean expense;
private final Boolean archived;
public UpdateCategoryRequest() {
this(null, null, null, null, null);
}
public UpdateCategoryRequest(String title, String description, Long amount, Boolean expense, Boolean archived) {
this.title = title;
this.description = description;
this.amount = amount;
this.expense = expense;
this.archived = archived;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public Long getAmount() {
return amount;
}
public Boolean getExpense() {
return expense;
}
public Boolean getArchived() {
return archived;
}
}
<file_sep>package com.wbrawner.budgetserver.passwordresetrequest;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PasswordResetRequestRepository extends PagingAndSortingRepository<PasswordResetRequest, Long> {
}<file_sep>apply plugin: 'java'
apply plugin: 'application'
apply plugin: "io.spring.dependency-management"
apply plugin: "org.springframework.boot"
repositories {
mavenLocal()
mavenCentral()
maven {
url = "http://repo.maven.apache.org/maven2"
}
}
dependencies {
implementation "org.springframework.boot:spring-boot-starter-data-jpa"
implementation "org.springframework.boot:spring-boot-starter-security"
implementation "org.springframework.session:spring-session-jdbc"
implementation "org.springframework.boot:spring-boot-starter-web"
implementation "io.springfox:springfox-swagger2:2.8.0"
implementation "io.springfox:springfox-swagger-ui:2.8.0"
runtimeOnly "mysql:mysql-connector-java:8.0.15"
testImplementation "org.springframework.boot:spring-boot-starter-test"
testImplementation "org.springframework.security:spring-security-test:5.1.5.RELEASE"
}
jar {
description = "twigs-server"
}
mainClassName = "com.wbrawner.budgetserver.BudgetServerApplication"
sourceCompatibility = 14
targetCompatibility = 14
<file_sep>buildscript {
repositories {
mavenLocal()
mavenCentral()
maven { url "http://repo.spring.io/snapshot" }
maven { url "http://repo.spring.io/milestone" }
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:2.2.2.RELEASE"
}
}
apply plugin: 'java'
allprojects {
repositories {
mavenLocal()
mavenCentral()
maven { url "http://repo.spring.io/snapshot" }
maven { url "http://repo.spring.io/milestone" }
maven { url "http://repo.maven.apache.org/maven2" }
}
jar {
group = "com.wbrawner"
archiveVersion.set("0.0.1-SNAPSHOT")
}
}
<file_sep>package com.wbrawner.budgetserver.user;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Optional;
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
Optional<User> findByUsername(String username);
Optional<User> findByUsernameAndPassword(String username, String password);
List<User> findByUsernameContains(String username);
Optional<User> findByEmail(String email);
}<file_sep>package com.wbrawner.budgetserver.transaction;
import com.wbrawner.budgetserver.budget.Budget;
import com.wbrawner.budgetserver.category.Category;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Optional;
public interface TransactionRepository extends PagingAndSortingRepository<Transaction, Long> {
Optional<Transaction> findByIdAndBudgetIn(Long id, List<Budget> budgets);
List<Transaction> findAllByBudgetInAndCategoryInAndDateGreaterThanAndDateLessThan(
List<Budget> budgets,
List<Category> categories,
Instant start,
Instant end,
Pageable pageable
);
List<Transaction> findAllByBudgetAndCategory(Budget budget, Category category);
@Query(
nativeQuery = true,
value = "SELECT (COALESCE((SELECT SUM(amount) from transaction WHERE Budget_id = :BudgetId AND expense = 0 AND date > :start), 0)) - (COALESCE((SELECT SUM(amount) from transaction WHERE Budget_id = :BudgetId AND expense = 1 AND date > :date), 0));"
)
Long sumBalanceByBudgetId(Long BudgetId, Date start);
@Query(
nativeQuery = true,
value = "SELECT (COALESCE((SELECT SUM(amount) from transaction WHERE category_id = :categoryId AND expense = 0 AND date > :start), 0)) - (COALESCE((SELECT SUM(amount) from transaction WHERE category_id = :categoryId AND expense = 1 AND date > :start), 0));"
)
Long sumBalanceByCategoryId(Long categoryId, Date start);
}<file_sep>package com.wbrawner.budgetserver.config;
import com.wbrawner.budgetserver.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class JdbcUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public JdbcUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails userDetails;
userDetails = userRepository.findByUsername(username).orElse(null);
if (userDetails != null) {
return userDetails;
}
userDetails = userRepository.findByEmail(username).orElse(null);
if (userDetails != null) {
return userDetails;
}
throw new UsernameNotFoundException("Unable to find user with username $username");
}
}<file_sep>package com.wbrawner.budgetserver.user;
public class UpdateUserRequest {
private final String username;
private final String password;
private final String email;
public UpdateUserRequest() {
this(null, null, null);
}
public UpdateUserRequest(String username, String password, String email) {
this.username = username;
this.password = <PASSWORD>;
this.email = email;
}
public String getUsername() {
return username;
}
public String getPassword() {
return <PASSWORD>;
}
public String getEmail() {
return email;
}
}<file_sep>package com.wbrawner.budgetserver.config;
import com.wbrawner.budgetserver.passwordresetrequest.PasswordResetRequestRepository;
import com.wbrawner.budgetserver.user.UserRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.web.cors.CorsConfiguration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final Environment env;
private final DataSource datasource;
private final UserRepository userRepository;
private final PasswordResetRequestRepository passwordResetRequestRepository;
private final JdbcUserDetailsService userDetailsService;
private final Environment environment;
public SecurityConfig(Environment env,
DataSource datasource,
UserRepository userRepository,
PasswordResetRequestRepository passwordResetRequestRepository,
JdbcUserDetailsService userDetailsService,
Environment environment) {
this.env = env;
this.datasource = datasource;
this.userRepository = userRepository;
this.passwordResetRequestRepository = passwordResetRequestRepository;
this.userDetailsService = userDetailsService;
this.environment = environment;
}
@Bean
public JdbcUserDetailsManager getUserDetailsManager() {
var userDetailsManager = new JdbcUserDetailsManager();
userDetailsManager.setDataSource(datasource);
return userDetailsManager;
}
@Bean
public DaoAuthenticationProvider getAuthenticationProvider() {
var authProvider = new DaoAuthenticationProvider();
authProvider.setPasswordEncoder(getPasswordEncoder());
authProvider.setUserDetailsService(userDetailsService);
return authProvider;
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(getAuthenticationProvider());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users/new", "/users/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.and()
.cors()
.configurationSource(request -> {
var corsConfig = new CorsConfiguration();
corsConfig.applyPermitDefaultValues();
var corsDomains = environment.getProperty("twigs.cors.domains", "*");
corsConfig.setAllowedOrigins(Arrays.asList(corsDomains.split(",")));
corsConfig.setAllowedMethods(
Stream.of(
HttpMethod.GET,
HttpMethod.POST,
HttpMethod.PUT,
HttpMethod.DELETE,
HttpMethod.OPTIONS
)
.map(Enum::name)
.collect(Collectors.toList())
);
corsConfig.setAllowCredentials(true);
return corsConfig;
})
.and()
.csrf()
.disable();
}
}
|
f0950ef26869a7322e1394d4f1617a1a3bfcb286
|
[
"Java",
"Dockerfile",
"INI",
"Gradle"
] | 14 |
Java
|
wbrawner/budget-spring
|
05f203a56f927d765a3385aadc87aa0f3195a20a
|
050fc85f6aac41923e19325014eff85c2ae1058c
|
refs/heads/master
|
<repo_name>EropForWork/Game01<file_sep>/js/launch.js
var MainCanvasHTML5;
var MainCanvas;
var FaryCanvasHTML5;
var FaryCanvas;
const WIN_W = window.visualViewport.width;
const WIN_H = window.visualViewport.height;
const MEAL_SCALE = 0.2;
var MealGoodsArr = [];
var GameName = [
['ru', 'Привет! Давай готовить с Тоби и Фари!'],
['en', "Hello! Let's cook with Toby and Fary!"]
];
var language = window.navigator ? (window.navigator.language ||
window.navigator.systemLanguage ||
window.navigator.userLsanguage) : "ru";
language = language.substr(0, 2).toLowerCase();
function initLogin() {
MainCanvasHTML5 = document.getElementById('mainCanvas'); // Для HTML5
MainCanvasHTML5.width = WIN_W;
MainCanvasHTML5.height = WIN_H;
MainCanvas = new createjs.Stage(MainCanvasHTML5);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", MainCanvas);
MainCanvas.enableMouseOver(60);
createjs.Touch.enable(MainCanvas);
addFaceFary();
makeHelloText();
loadImage();
makeCloud(100, 100, 200, 100);
}
function makeHelloText() {
let text = 'А что за язык у тебя?';
for (let i = 0; i < GameName.length; i++) {
if (GameName[i][0] == language) {
text = GameName[i][1];
break;
}
}
let TopText = new createjs.Text(text);
TopText.font = "50px Consolas";
TopText.textAlign = "center";
TopText.lineWidth = WIN_W - 50;
TopText.lineHeight = 50;
TopText.x = WIN_W / 2;
TopText.y = 20;
let NewCon = new createjs.Container();
NewCon.name = 'LoginText';
NewCon.addChild(makeCloud(TopText.x - TopText.getMetrics().width / 2 - 5, TopText.y, TopText.getMetrics().width + 10, TopText.getMetrics().height + 10), TopText);
MainCanvas.addChild(NewCon);
MainCanvas.update();
}
function textLoginDis() {
new createjs.Tween.get(MainCanvas.getChildByName('LoginText')).to({
alpha: 0
}, 1500).call(initFisrtDish);
}
function makeCloud(x1 = 0, y1 = 0, w = 50, h = 50, a = 1) {
x1 = Math.floor(x1);
y1 = Math.floor(y1);
w = Math.floor(w);
h = Math.floor(h);
let NewR = new createjs.Shape();
NewR.graphics.beginFill('#dddddd').drawRect(-0.5, -0.5, w + 1, h + 1);
let CurveCount = (w * 2 + h * 2) / 5;
let NewCloud = new createjs.Shape();
NewCloud.graphics.setStrokeStyle(2).beginStroke('#5ab2ec').beginFill('#dddddd');
for (let i = 0; i < CurveCount; i++) {
let Coor = {
'StartX': Math.floor(-10 + Math.random() * (10 + 1 - (-10))),
'StartY': Math.floor(-10 + Math.random() * (10 + 1 - (-10))),
'CpX': Math.floor(10 + Math.random() * (20 + 1 - 10)),
'CpY': Math.floor(10 + Math.random() * (20 + 1 - 10)),
'LastX': Math.floor(10 + Math.random() * (20 + 1 - 10)),
'LastY': Math.floor(10 + Math.random() * (20 + 1 - 10))
};
let LastGraph = NewCloud.graphics._activeInstructions[NewCloud.graphics._activeInstructions.length - 1];
if (LastGraph == undefined) {
Coor.StartX = 0;
Coor.CpX = 0 + Math.abs(Coor.LastX) / 2;
Coor.LastX = Math.abs(Coor.LastX) + 0;
Coor.StartY = 0;
Coor.LastY = 0;
Coor.CpY = 0 - Coor.CpY;
} else {
// 1
if (LastGraph.x < 0 + w && LastGraph.y == 0) {
Coor.StartX = LastGraph.x;
Coor.CpX = LastGraph.x + Coor.LastX / 2;
if (Coor.LastX + LastGraph.x >= 0 + w)
Coor.LastX = 0 + w;
else
Coor.LastX = Coor.LastX + LastGraph.x;
Coor.StartY = 0;
Coor.LastY = 0;
Coor.CpY = 0 - Coor.CpY;
if (Coor.LastX > 0 + w - 10)
Coor.LastX = 0 + w;
// 2
} else if (LastGraph.x >= 0 + w && LastGraph.y < 0 + h) {
if (LastGraph.x > 0 + w)
Coor.StartX = LastGraph.x;
else
Coor.StartX = 0 + w;
Coor.LastX = 0 + w;
Coor.CpX += 0 + w;
Coor.StartY = LastGraph.y;
Coor.CpY = LastGraph.y + Coor.LastY / 2;
if (Coor.LastY + LastGraph.y >= 0 + h)
Coor.LastY = 0 + h;
else
Coor.LastY = Coor.LastY + LastGraph.y;
if (Coor.LastY > 0 + h - 10)
Coor.LastY = 0 + h;
// 3
} else if (LastGraph.x >= 0 && LastGraph.y >= 0 + h) {
if (LastGraph.y > 0 + h)
Coor.StartY = LastGraph.y;
else
Coor.StartY = 0 + h;
Coor.LastY = 0 + h;
Coor.CpY += 0 + h;
Coor.StartX = LastGraph.x;
Coor.CpX = LastGraph.x - Coor.LastX / 2;
if (LastGraph.x - Coor.LastX <= 0)
Coor.LastX = 0 - 0.01;
else
Coor.LastX = LastGraph.x - Coor.LastX;
if (Coor.LastX < 0 + 10)
Coor.LastX = 0 - 0.01;
// 4
} else {
if (LastGraph.x < 0)
Coor.StartX = LastGraph.x;
else
Coor.StartX = 0;
if (LastGraph.y <= 0 + 20) {
Coor.CpX = 0 - Coor.CpX;
Coor.LastX = 0;
Coor.StartY = LastGraph.y;
Coor.LastY = 0;
Coor.CpY = 0 + Coor.CpY / 2;
NewCloud.graphics.moveTo(Coor.StartX, Coor.StartY).quadraticCurveTo(Coor.CpX, Coor.CpY, Coor.LastX, Coor.LastY);
break;
}
Coor.CpX = LastGraph.x - Coor.CpX;
Coor.LastX = 0;
Coor.StartY = LastGraph.y;
Coor.CpY = LastGraph.y - Math.abs(Coor.LastY) / 2;
Coor.LastY = LastGraph.y - Math.abs(Coor.LastY);
}
}
NewCloud.graphics.moveTo(Coor.StartX, Coor.StartY).quadraticCurveTo(Coor.CpX, Coor.CpY, Coor.LastX, Coor.LastY);
}
let CloudCon = new createjs.Container();
CloudCon.name = 'Cloud';
CloudCon.addChild(NewR, NewCloud);
CloudCon.alpha = a;
CloudCon.setTransform(x1, y1);
return CloudCon;
}
<file_sep>/js/page1.js
let stage1 = new createjs.Stage("page1Canvas");
// function init() {
// let circle = new createjs.Shape();
// circle.graphics.beginFill("DeepSkyBlue").drawCircle(0, 0, 30);
// circle.x = 100;
// circle.y = 100;
// stage.addChild(circle);
// stage.update();
//
// // say_hello();
// }
//
// function say_hello() {
// alert('AAAAAAAAAAAA');
// }
<file_sep>/js/ImgArr.js
/*let ImgArr = JSON.stringify([
]);*/
let ImgArr = [{
'place': 'Tableware',
'img': 'Plate.png'
}, {
'place': 'Meal/Omelette',
'img': 'Pig.png'
}, {
'place': 'Meal/Omelette',
'img': 'Egg.png'
}, {
'place': 'Meal/Omelette',
'img': 'Green1.png'
}, {
'place': 'Meal/Omelette',
'img': 'Tomato.png'
}, {
'place': 'Meal/Pasta1',
'img': 'Pasta1.png'
}, {
'place': 'Meal/Pasta1',
'img': 'Tomato.png'
}, {
'place': 'Meal/Pasta1',
'img': 'Green2.png'
}, {
'place': 'Meal/Pasta1',
'img': 'Chees.png'
}, {
'place': 'Shop',
'img': 'Apple1.png',
'scale': 2
},
// {
// 'place': 'Shop',
// 'img': 'Apple2.png',
// 'scale': 2
// },
{
'place': 'Shop',
'img': 'Broccoli.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Cabbage.png',
'scale': 1.5
}, {
'place': 'Shop',
'img': 'Carrot.png',
'scale': 0.8
}, {
'place': 'Shop',
'img': 'Chiken.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Corn.png',
'scale': 2
}, {
'place': 'Shop',
'img': 'Cucumber.png',
'scale': 1.4
}, {
'place': 'Shop',
'img': 'Egg1.png',
'scale': 1
},
// {
// 'place': 'Shop',
// 'img': 'Egg2.png',
// 'scale': 1
// },
{
'place': 'Shop',
'img': 'Eggplant.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Limon.png',
'scale': 1.5
}, {
'place': 'Shop',
'img': 'Mushroom.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Onion.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Orange.png',
'scale': 2
}, {
'place': 'Shop',
'img': 'Pasta.png',
'scale': 0.8
}, {
'place': 'Shop',
'img': 'Pear.png',
'scale': 1.5
}, {
'place': 'Shop',
'img': 'Pepper.png',
'scale': 1
},
// {
// 'place': 'Shop',
// 'img': 'Pepper2.png',
// 'scale': 2.4
// },
{
'place': 'Shop',
'img': 'Pig.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Potato.png',
'scale': 0.8
}, {
'place': 'Shop',
'img': 'Radish.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Green.png',
'scale': 1.6
}, {
'place': 'Shop',
'img': 'Strawberry.png',
'scale': 3
}, {
'place': 'Shop',
'img': 'Tomato.png',
'scale': 0.8
}, {
'place': 'Shop',
'img': 'Watermelon.png',
'scale': 2
}, {
'place': 'Shop',
'img': 'Chees.png',
'scale': 1
}, {
'place': 'Shop',
'img': 'Basket.png'
}, {
'place': 'Shop',
'img': 'Shop_main.png'
}, {
'place': 'Shop',
'img': 'Plane1.png'
}, {
'place': 'Shop',
'img': 'Plane2.png'
}, {
'place': 'Shop',
'img': 'Дно_Ящик_1.png'
}, {
'place': 'Shop',
'img': 'Перед_Ящик_1.png'
}, {
'place': 'Shop',
'img': 'Рамка_Ящик_1.png'
}, {
'place': 'Shop',
'img': 'Дно_Ящик_2.png'
}, {
'place': 'Shop',
'img': 'Перед_Ящик_2.png'
}, {
'place': 'Shop',
'img': 'Рамка_Ящик_2.png'
}, {
'place': 'Kitchen',
'img': 'Apron.png'
}, {
'place': 'Kitchen',
'img': 'Board1.png'
}, {
'place': 'Kitchen',
'img': 'Board2.png'
}, {
'place': 'Kitchen',
'img': 'Hat.png'
}, {
'place': 'Kitchen',
'img': 'KitchenMain.png'
}, {
'place': 'Kitchen',
'img': 'Knife1.png'
}, {
'place': 'Kitchen',
'img': 'Pan1.png'
}, {
'place': 'Kitchen',
'img': 'Pan2.png'
}, {
'place': 'Kitchen',
'img': 'Pan3.png'
}, {
'place': 'Kitchen',
'img': 'Pan4.png'
}, {
'place': 'Kitchen',
'img': 'Plate1.png'
}, {
'place': 'Kitchen',
'img': 'Plate2.png'
}, {
'place': 'Kitchen',
'img': 'Plate3.png'
}, {
'place': 'Kitchen',
'img': 'Sault.png'
}, {
'place': 'Kitchen',
'img': 'Stove.png'
}
];
<file_sep>/js/loadImg.js
let TempImgCon = new createjs.Container();
function loadImage() {
for (let i = 0; i < ImgArr.length; i++) {
let Img = new createjs.Bitmap('images/' + ImgArr[i].place + '/' + ImgArr[i].img);
Img.name = ImgArr[i].img.substring(0, ImgArr[i].img.indexOf('.'));
TempImgCon.addChild(Img);
Img.alpha = 0;
Img.crossOrigin="Anonymous";
if (ImgArr[i].place == 'Shop' && ImgArr[i].img.indexOf('Shop') == -1) {
Img.scaleX = Img.scaleY = ImgArr[i].scale;
}
}
textLoginDis();
MainCanvas.addChild(TempImgCon);
}
// настоящий код
/*let TempImgCon = new createjs.Container();
function loadImage() {
let ImgLinkArr = [];
for (let i = 0; i < JSON.parse(ImgArr).length; i++) {
ImgLinkArr.push(JSON.parse(ImgArr)[i].img.substring(0, JSON.parse(ImgArr)[i].img.indexOf('.')), 'images/' + JSON.parse(ImgArr)[i].place + '/' + JSON.parse(ImgArr)[i].img);
}
var queue = new createjs.LoadQueue(true);
for (let i = 0; i < ImgLinkArr.length / 2; i++) {
queue.loadManifest({
id: ImgLinkArr[i * 2],
src: ImgLinkArr[i * 2 + 1]
});
}
queue.on("complete", loadComplete);
queue.on("fileload", imgLoad);
// queue.on("progress", loadProgress);
queue.load();
}
function loadComplete(e) {
console.log('Загрузился полностью.');
// textLoginDis();
MainCanvas.addChild(TempImgCon);
console.log(TempImgCon);
}
function imgLoad(e) {
// console.log('Файл', e.item, 'загрузился.');
let Img = new createjs.Bitmap(e.item.src);
Img.name = e.item.id;
Img.alpha = 0;
TempImgCon.addChild(Img);
}
function loadProgress(e) {
console.log("Загрузка файлов:", Math.floor(e.progress * 100) + '%');
}
*/
<file_sep>/js/Take_Dish_old.js
var DishHello = [
['ru', 'Выбирай блюдо, которое будем готовить!'],
['en', "Choose the dish that we will cook!"]
];
var DISH_COLOR = {
plate_white: '#F6F3EC',
plate_grey: '#CAC0B6',
plate_bottom: '#E9E6E0',
kotletka: '#78130A',
puresha_w: '#F6EF90',
puresha_b: '#E7AD00'
}
function Init_Fisrt_Dish() {
LaunchCanvas.addChild(Text_Hello_Dish(), Make_Dish_Carousel())
LaunchCanvas.update();
new createjs.Tween.get(LaunchCanvas.getChildByName('DISH_CHOICE')).to({
alpha: 1
}, 500);
}
function Text_Hello_Dish() {
let text = 'А что за язык у тебя?';
for (let i = 0; i < DishHello.length; i++) {
if (DishHello[i][0] == language) {
text = DishHello[i][1];
break;
}
}
let TopText = new createjs.Text(text);
TopText.font = "50px Consolas";
TopText.textAlign = "center";
TopText.lineWidth = WIN_W - 50;
TopText.lineHeight = 50;
TopText.x = WIN_W / 2;
TopText.y = 20;
TopText.alpha = 0;
TopText.name = 'DISH_CHOICE';
return TopText;
}
function Make_Dish_Carousel() {
let DishCarousel = new createjs.Container();
DishCarousel.name = 'DISH_CAROUSEL';
// DishCarousel.addChild(Make_Dish_Kartoshka_Kotletka());
DishCarousel.addChild(Make_Finish_Omlette(), Make_Finish_Pasta1());
for (var i = 0; i < DishCarousel.children.length; i++) {
DishCarousel.children[i].on('click', Click_Dish)
}
return DishCarousel;
}
function Make_Plate() {
let Plate = new createjs.Container();
let Plate1 = new createjs.Shape();
Plate1.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey).beginFill(DISH_COLOR.plate_white)
.drawEllipse(0, 0, 630, 285).closePath();
Plate1.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey)
.moveTo(2, 160).quadraticCurveTo(100, 270, 315, 270).quadraticCurveTo(528, 270, 628, 160);
let Plate2 = new createjs.Shape();
Plate2.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey).beginFill(DISH_COLOR.plate_bottom)
.drawEllipse(55, 15, 520, 235).closePath();
Plate.addChild(Plate1, Plate2);
Plate.setTransform(280, 180);
return Plate;
}
function Make_Dish_Kartoshka_Kotletka() {
let Dish = new createjs.Container();
let Kotletka1 = new createjs.Shape();
Kotletka1.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey).beginFill(DISH_COLOR.kotletka)
.moveTo(21.75, 98.25)
.quadraticCurveTo(82.8, 34.55, 126.85, 54.8)
.quadraticCurveTo(207, 89, 205.25, 145)
.lineTo(87.8, 212.9)
.quadraticCurveTo(0, 150, 21.75, 98.25);
Kotletka1.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey)
.moveTo(21.75, 98.25)
.quadraticCurveTo(65, 230, 205.25, 145);
let Kotletka2 = new createjs.Shape();
Kotletka2.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey).beginFill(DISH_COLOR.kotletka)
.moveTo(85.6, 185.95)
.quadraticCurveTo(195, 105, 298.2, 165.85)
.quadraticCurveTo(311, 184, 314.25, 204.1)
.quadraticCurveTo(270, 300, 90.6, 243.4)
.quadraticCurveTo(75.4, 214.8, 85.6, 185.95);
Kotletka2.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.plate_grey)
.moveTo(85.6, 185.95)
.quadraticCurveTo(270, 245, 298.2, 165.85);
Kotletka1.setTransform(291.85, 167.75);
Kotletka2.setTransform(291.85, 167.75);
Dish.addChild(Make_Plate(), Make_Pureshka(), Kotletka1, Kotletka2);
return Dish;
}
function Make_Pureshka() {
let Pureshka = new createjs.Shape();
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(195.8, 109.75)
.quadraticCurveTo(200, 107, 206.85, 102.4)
.quadraticCurveTo(223.35, 70, 260.1, 63.45)
.quadraticCurveTo(291.2, 49, 321.95, 55.3)
.quadraticCurveTo(319.45, 35.25, 356.35, 35.25)
.quadraticCurveTo(370.35, 22.1, 394.05, 24.6)
.quadraticCurveTo(405.9, 26.4, 405.9, 54.05)
.quadraticCurveTo(436.95, 51.55, 428.05, 65.05)
.quadraticCurveTo(489.45, 83.5, 492.7, 104.75)
.quadraticCurveTo(536.15, 109.75, 527, 126.15)
.quadraticCurveTo(519.6, 152.25, 494.45, 167.55)
.quadraticCurveTo(478.2, 208.55, 441.95, 203.55)
.quadraticCurveTo(415.25, 230.25, 342.45, 227.75)
.quadraticCurveTo(313.8, 242.55, 301.4, 237.55)
.quadraticCurveTo(282.2, 232.75, 260.1, 197.45)
.quadraticCurveTo(233.55, 187.45, 231.05, 173.85)
.quadraticCurveTo(203.45, 162.55, 201.85, 152.25)
.quadraticCurveTo(189.15, 117.5, 195.8, 109.75);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(260.1, 63.45)
.quadraticCurveTo(252.2, 70.4, 253.3, 77.7)
.quadraticCurveTo(228.55, 101.3, 231.05, 173.85);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(253.3, 77.7)
.lineTo(252.3, 83.5)
.quadraticCurveTo(233.55, 101.3, 270.6, 140.4)
.quadraticCurveTo(258, 139.2, 260.1, 149.75)
.quadraticCurveTo(242.2, 173.85, 231.05, 173.85);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(252.3, 83.5)
.quadraticCurveTo(249.8, 96.3, 273.1, 117.5)
.quadraticCurveTo(288.7, 139.2, 367.85, 172.2)
.quadraticCurveTo(410.9, 173.85, 423.05, 162.55)
.quadraticCurveTo(454.55, 173.85, 494.45, 167.55);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(260.1, 149.75)
.quadraticCurveTo(296.4, 152.25, 347.45, 192.45)
.quadraticCurveTo(356.35, 206.3, 441.95, 203.55);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(260.1, 197.45)
.quadraticCurveTo(298.9, 222.75, 342.45, 227.75);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(303.9, 55.3)
.quadraticCurveTo(291.2, 56.55, 286.2, 65.05)
.quadraticCurveTo(278.1, 68.45, 277.2, 79.8)
.quadraticCurveTo(283.7, 92, 303.9, 101.3)
.quadraticCurveTo(339.95, 139.2, 421.7, 139.2)
.quadraticCurveTo(459.7, 149.75, 487.7, 134.2)
.quadraticCurveTo(504.35, 119.75, 492.7, 104.75);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(303.9, 101.3)
.quadraticCurveTo(314.45, 110.75, 332.6, 111.35)
.quadraticCurveTo(361.35, 124, 396.15, 122.5)
.quadraticCurveTo(412.75, 119.75, 415.25, 107.4)
.quadraticCurveTo(433.05, 101.3, 463.3, 114.75)
.quadraticCurveTo(474.1, 121.15, 492.7, 104.75);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(415.25, 107.4)
.quadraticCurveTo(431.5, 89.6, 428.05, 65.05);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(286.2, 65.05)
.quadraticCurveTo(331.95, 102.15, 351.35, 93.55)
.quadraticCurveTo(384.85, 89.6, 405.9, 54.05);
Pureshka.graphics.setStrokeStyle(1).beginStroke(DISH_COLOR.puresha_b).beginFill(DISH_COLOR.puresha_w)
.moveTo(321.95, 55.3)
.quadraticCurveTo(344.95, 65.05, 365.35, 55.3)
.quadraticCurveTo(367.85, 44.3, 356.35, 35.25);
Pureshka.setTransform(291.85, 167.75);
return Pureshka;
}
function Click_Dish(e) {
Jump(LaunchCanvas.getChildByName('FARY_FACE'));
new createjs.Tween.get(LaunchCanvas.getChildByName('DISH_CAROUSEL')).to({
alpha: 0
}, 350);
new createjs.Tween.get(LaunchCanvas.getChildByName('DISH_CHOICE')).to({
alpha: 0
}, 350);
new createjs.Tween.get(LaunchCanvas.getChildByName('FARY_FACE')).to({
x: WIN_W / 2 - 100
}, 350);
Go_To_Shop();
}
function Make_Finish_Omlette() {
let Plate = new createjs.Bitmap("images/Tableware/Plate.png");
let Becon = new createjs.Bitmap("images/Meal/Omelette/Becon.png");
let Eggs = new createjs.Bitmap("images/Meal/Omelette/Eggs.png");
let Green1 = new createjs.Bitmap("images/Meal/Omelette/Green1.png");
let Tomato = new createjs.Bitmap("images/Meal/Omelette/Tomato.png");
new createjs.Tween.get().to({}, 0).call(Load_Meal_Pics, [
[Plate, Becon, Eggs, Green1, Tomato], 'Omlette'
]);
}
function Make_Finish_Pasta1() {
let Plate = new createjs.Bitmap("images/Tableware/Plate.png");
let Green2 = new createjs.Bitmap("images/Meal/Pasta1/Green2.png");
let Pasta1 = new createjs.Bitmap("images/Meal/Pasta1/Pasta1.png");
let Sous1 = new createjs.Bitmap("images/Meal/Pasta1/Sous1.png");
let Spices1 = new createjs.Bitmap("images/Meal/Pasta1/Spices1.png");
new createjs.Tween.get().to({}, 0).call(Load_Meal_Pics, [
[Plate, Pasta1, Sous1, Green2, Spices1], 'Pasta1'
]);
}
function Load_Meal_Pics(newA, Dish) {
let NewMeal = new createjs.Container();
for (var i = 0; i < newA.length; i++) {
NewMeal.addChild(newA[i]);
if (Dish == 'Omlette') {
let newY = 100;
if (i == 0) newA[i].setTransform(-150, 0, 1.4, 1.4);
if (i == 1) newA[i].setTransform(210, -130 + newY);
if (i == 2) newA[i].setTransform(0, 0 + newY);
if (i == 3) newA[i].setTransform(0, 70 + newY);
if (i == 4) newA[i].setTransform(30, 140 + newY);
}
if (Dish == 'Pasta1') {
let newX = 150;
let newY = 40;
if (i == 0) newA[i].setTransform(-150, 0, 1.4, 1.4);
if (i == 1) newA[i].setTransform(0 + newX, 0 + newY, 2, 2);
if (i == 2) newA[i].setTransform(60 + newX, -30 + newY, 2, 2);
if (i == 3) newA[i].setTransform(130 + newX, -30 + newY, 2, 2);
if (i == 4) newA[i].setTransform(40 + newX, -10 + newY, 2, 2);
}
}
NewMeal.name = Dish;
LaunchCanvas.addChild(NewMeal);
Find_Max_Scale_Pic(NewMeal);
}
function Find_Max_Scale_Pic(e) {
let x1 = 0;
let y1 = 0;
let x2 = 0;
let y2 = 0;
for (var i = 0; i < e.children.length; i++) {
let maxW = e.children[i].image.naturalWidth;
let maxH = e.children[i].image.naturalHeight;
let oldX = e.children[i].x + e.children[i].regX;
let oldY = e.children[i].y + e.children[i].regY;
oldX > x1 ? x1 : x1 = oldX;
oldY > y1 ? y1 : y1 = oldY;
oldX + maxW < x2 ? x2 : x2 = oldX + maxW;
oldY + maxH < y2 ? y2 : y2 = oldY + maxH;
}
let newW = (WIN_W / 100) * (MEAL_SCALE - 0.03) * 100;
let newH = (WIN_H / 100) * (MEAL_SCALE - 0.03) * 100;
let newS = 1;
let maxW = x2 - x1;
let maxH = y2 - y1;
if (maxW > newW) {
newS = (newW / (maxW / 100)) / 100;
}
if (maxH > newH) {
let temp = (newW / (maxW / 100)) / 100;
temp < newS ? newS = temp : newS;
}
e.setTransform(0, 0, newS, newS)
}
<file_sep>/js/Take_Dish.js
var DishHello = [
['ru', 'Выбирай блюдо, которое будем готовить!'],
['en', "Choose the dish that we will cook!"]
];
var DishesArr = ['Pasta1', 'Omelette'];
let Carousel_Diff_X = 0;
function initFisrtDish() {
MainCanvas.addChild(textHelloDish(), makeDishCarousel())
MainCanvas.update();
new createjs.Tween.get(MainCanvas.getChildByName('DISH_CHOICE')).to({
alpha: 1
}, 500);
}
function textHelloDish() {
let text = 'А что за язык у тебя?';
for (let i = 0; i < DishHello.length; i++) {
if (DishHello[i][0] == language) {
text = DishHello[i][1];
break;
}
}
let TopText = new createjs.Text(text);
TopText.font = "50px Consolas";
TopText.textAlign = "center";
TopText.lineWidth = WIN_W - 50;
TopText.lineHeight = 50;
TopText.x = WIN_W / 2;
TopText.y = 20;
// TopText.name = 'DISH_CHOICE';
let NewCon = new createjs.Container();
NewCon.name = 'DISH_CHOICE';
NewCon.alpha = 0;
NewCon.addChild(makeCloud(TopText.x - TopText.getMetrics().width / 2 - 5, TopText.y, TopText.getMetrics().width + 10, TopText.getMetrics().height + 10), TopText);
return NewCon;
}
function makeDishCarousel() {
let DishCarousel = new createjs.Container();
DishCarousel.name = 'DISH_CAROUSEL';
makeDishes(DishCarousel);
makeDishCarouselCoor(DishCarousel);
return DishCarousel;
}
function makeDishes(e) {
for (let i = 0; i < DishesArr.length; i++) {
let Dish = new createjs.Container();
Dish.name = DishesArr[i];
let NewImg = TempImgCon.getChildByName('Plate').clone();
NewImg.alpha = 1;
Dish.addChild(NewImg);
for (let ii = 0; ii < TempImgCon.children.length; ii++) {
if (TempImgCon.children[ii].image.src.indexOf(Dish.name) != -1) {
let NewImg = TempImgCon.children[ii].clone();
Dish.addChild(NewImg);
NewImg.alpha = 1;
}
}
loadMealPics(Dish);
e.addChild(Dish);
}
}
function makeDishCarouselCoor(e) {
let diff = 50;
let diffX = (Carousel_Diff_X / e.children.length) * 1.4 + diff;
for (var i = 0; i < e.children.length; i++) {
e.children[i].x = i * diffX;
e.children[i].y = 200;
e.children[i].children[e.children[i].children.length - 1].on('click', clickDish, null, true);
}
e.setTransform((WIN_W / 2 - (Carousel_Diff_X * 1.4) / 2) + (diff * (e.children.length - 1)) / 2);
}
function clickDish(e) {
new createjs.Tween.get(MainCanvas.getChildByName('DISH_CAROUSEL')).to({
alpha: 0
}, 350);
new createjs.Tween.get(MainCanvas.getChildByName('DISH_CHOICE')).to({
alpha: 0
}, 350);
let FaryFace = MainCanvas.getChildByName('FARY_FACE');
FaryFace.removeAllEventListeners('click');
goToShop(e.currentTarget.parent.name);
}
function loadMealPics(e) {
let newA = e.children;
let Dish = e.name;
for (var i = 0; i < newA.length; i++) {
if (Dish == 'Omelette') {
let newY = 100;
if (i == 0) newA[i].setTransform(-150, 0, 1.4, 1.4);
if (i == 1) newA[i].setTransform(210, -130 + newY);
if (i == 2) newA[i].setTransform(0, 0 + newY);
if (i == 3) newA[i].setTransform(0, 70 + newY);
if (i == 4) newA[i].setTransform(30, 140 + newY);
}
if (Dish == 'Pasta1') {
let newX = 150;
let newY = 40;
if (i == 0) newA[i].setTransform(-150, 0, 1.4, 1.4);
if (i == 1) newA[i].setTransform(0 + newX, 0 + newY, 2, 2);
if (i == 2) newA[i].setTransform(60 + newX, -30 + newY, 2, 2);
if (i == 3) newA[i].setTransform(130 + newX, -30 + newY, 2, 2);
if (i == 4) newA[i].setTransform(40 + newX, -10 + newY, 2, 2);
}
}
findMaxScalePic(e);
}
function findMaxScalePic(e) {
let x1 = 0;
let y1 = 0;
let x2 = 0;
let y2 = 0;
for (var i = 0; i < 1; i++) {
let maxW = e.children[i].image.naturalWidth;
let maxH = e.children[i].image.naturalHeight;
let oldX = e.children[i].x + e.children[i].regX;
let oldY = e.children[i].y + e.children[i].regY;
oldX > x1 ? x1 : x1 = oldX;
oldY > y1 ? y1 : y1 = oldY;
oldX + maxW < x2 ? x2 : x2 = oldX + maxW;
oldY + maxH < y2 ? y2 : y2 = oldY + maxH;
}
let newW = (WIN_W / 100) * (MEAL_SCALE - 0.03) * 100;
let newH = (WIN_H / 100) * (MEAL_SCALE - 0.03) * 100;
let newS = 1;
let maxW = x2 - x1;
let maxH = y2 - y1;
if (maxW > newW) {
newS = (newW / (maxW / 100)) / 100;
}
if (maxH > newH) {
var temp = (newH / (maxH / 100)) / 100;
temp < newS ? newS = temp : newS;
}
e.addChild(makeDishRect(x1, y1, maxW*1.4, maxH*1.4));
e.setTransform(0, 0, newS, newS);
Carousel_Diff_X += maxW * newS;
}
function makeDishRect(x1, y1, maxW, maxH) {
let Rect = new createjs.Shape();
Rect.graphics.beginFill('white').drawRect(0, 0, maxW, maxH);
Rect.setTransform(x1, y1);
Rect.alpha = 0.01;
return Rect;
}
<file_sep>/js/Shop.js
function goToShop(e) {
MainCanvas.addChild(makeShop(e));
}
function makeShop(e) {
let NewShop = new createjs.Container();
NewShop.alpha = 0;
NewShop.name = 'NewShop';
MealGoodsArr.length = 0;
for (let i = 0; i < TempImgCon.children.length; i++) {
if (TempImgCon.children[i].image.src.indexOf(e) != -1) {
let MaxDishGoodname = TempImgCon.children[i].name;
let DishGoodname = MaxDishGoodname.replace(/[0-9]/g, '');
if (TempImgCon.getChildByName(DishGoodname)) {
MealGoodsArr.push(DishGoodname);
} else {
console.log('Продукта', DishGoodname, 'нет в магазине!');
}
}
}
let Shop = TempImgCon.getChildByName('Shop_main').clone();
let Basket = TempImgCon.getChildByName('Basket').clone();
let NewBasCon = new createjs.Container();
NewBasCon.addChild(Basket);
NewBasCon.name = 'Basket';
let Plane1 = TempImgCon.getChildByName('Plane1').clone();
let Plane2 = TempImgCon.getChildByName('Plane2').clone();
Shop.alpha = Basket.alpha = Plane1.alpha = 1;
NewShop.addChild(Shop, NewBasCon, Plane1, Plane2);
Basket.setTransform(1950, 915, 0.68, 0.68);
Plane1.setTransform(1838, 1515);
Plane2.setTransform(1838, 1015);
for (var i = 0; i < 2; i++) {
let RectH = 200 - 100 * i
let ShadowRect = new createjs.Shape();
ShadowRect.graphics.beginFill('black')
.drawRect(10, -10, 1060, RectH);
ShadowRect.name = 'ShadowRect' + i;
ShadowRect.alpha = 0.4;
if (i == 0) {
ShadowRect.setTransform(Plane1.x, Plane1.y + Plane1.image.naturalHeight)
} else {
ShadowRect.alpha = 0;
ShadowRect.setTransform(Plane2.x, Plane2.y + Plane2.image.naturalHeight)
}
NewShop.addChild(ShadowRect);
}
let AllGoods = [];
for (let i = 0; i < ImgArr.length; i++) {
if (ImgArr[i].place.indexOf('Shop') != -1 && ImgArr[i].img.indexOf('Shop') == -1) {
if (ImgArr[i].img != 'Рамка_Ящик_2.png' &&
ImgArr[i].img != 'Перед_Ящик_2.png' &&
ImgArr[i].img != 'Дно_Ящик_2.png' &&
ImgArr[i].img != 'Рамка_Ящик_1.png' &&
ImgArr[i].img != 'Перед_Ящик_1.png' &&
ImgArr[i].img != 'Дно_Ящик_1.png' &&
ImgArr[i].img != 'Plane2.png' &&
ImgArr[i].img != 'Plane1.png' &&
ImgArr[i].img != 'Shop_main.png' &&
ImgArr[i].img != 'Basket.png') {
let DishGoodname = ImgArr[i].img.substring(0, ImgArr[i].img.indexOf('.')).replace(/[0-9]/g, '');
if (MealGoodsArr.indexOf(DishGoodname) == -1) {
AllGoods.push(DishGoodname);
}
}
}
}
let ShopGoods = MealGoodsArr.slice();
while (ShopGoods.length < 7) {
let RandomNum = Math.floor(Math.random() * AllGoods.length);
let FalseGood = AllGoods[RandomNum];
if (ShopGoods.indexOf(FalseGood) == -1) {
AllGoods.splice(RandomNum, 1);
ShopGoods.push(FalseGood);
}
}
let Q;
let Temp;
for (let i = 0; i < ShopGoods.length; i++) {
Q = Math.floor(Math.random() * (i + 1));
Temp = ShopGoods[Q];
ShopGoods[Q] = ShopGoods[i];
ShopGoods[i] = Temp;
}
for (let i = 0; i < ShopGoods.length; i++) {
let Re = false;
for (let ii = 0; ii < ImgArr.length; ii++) {
if (ImgArr[ii].place == 'Shop') {
if (Re == false && ShopGoods[i] == ImgArr[ii].img.substring(0, ImgArr[ii].img.indexOf('.'))) {
makeBasketGood(NewShop, ShopGoods[i], i);
break;
}
if (ImgArr[ii].img.indexOf(ShopGoods[i]) != -1) {
makeBasketGood(NewShop, ShopGoods[i], i);
break;
}
if (i == ImgArr.length - 1) {
i = 0;
re = true;
}
}
}
}
scaleShop(NewShop);
MainCanvas.addChild(NewShop);
}
function makeBasketGood(con, e, num) {
let Basket = new createjs.Container();
Basket.name = 'Basket' + e;
let DiffMaskH = 170;
let DiffMaskY = -30;
if (num < 3 || num >= 7) {
con.addChild(Basket);
DiffMaskH = 70;
DiffMaskY = -130;
} else if (num >= 5 && num < 7) {
for (var i = 0; i < con.children.length; i++) {
if (con.children[i].name == 'Plane1') {
con.addChild(Basket);
// con.children.splice(i + 1, 0, Basket);
break;
}
}
} else if (num >= 3 && num < 5) {
for (var i = 0; i < con.children.length; i++) {
if (con.children[i].name == 'ShadowRect1') {
con.addChild(Basket);
break;
}
}
}
let MaskCoords = [{
x: 260,
y: 1950
}, {
x: 800,
y: 1950
}, {
x: 1330,
y: 1950
}, {
x: 1862,
y: 1950
}, {
x: 2400,
y: 1950
}, {
x: 1878,
y: 1360
}, {
x: 2390,
y: 1360
}, {
x: 1878,
y: 860
}, {
x: 2390,
y: 860
}];
if (num < 5) {
let Dno = TempImgCon.getChildByName('Дно_Ящик_1').clone();
let Ramka = TempImgCon.getChildByName('Рамка_Ящик_1').clone();
let Lico = TempImgCon.getChildByName('Перед_Ящик_1').clone();
Dno.alpha = Ramka.alpha = Lico.alpha = 1;
Basket.addChild(Dno, Ramka, Lico);
Basket.setTransform(MaskCoords[num].x, MaskCoords[num].y);
} else {
let Dno = TempImgCon.getChildByName('Дно_Ящик_2').clone();
let Ramka = TempImgCon.getChildByName('Рамка_Ящик_2').clone();
let Lico = TempImgCon.getChildByName('Перед_Ящик_2').clone();
Dno.alpha = Ramka.alpha = Lico.alpha = 1;
Basket.addChild(Dno, Ramka, Lico);
Basket.setTransform(MaskCoords[num].x, MaskCoords[num].y);
}
let Goods = [];
for (let i = 0; i < ImgArr.length; i++) {
if (ImgArr[i].place == 'Shop') {
if (ImgArr[i].img.indexOf(e) != -1) {
Goods.push(ImgArr[i].img.substring(0, ImgArr[i].img.indexOf('.')));
}
}
}
let MaskW = Basket.children[0].image.naturalWidth;
let MaskH = Basket.children[0].image.naturalHeight;
let NewMask = new createjs.Shape();
NewMask.graphics.beginFill('red').drawRect(-40, DiffMaskY, MaskW + 80, MaskH - DiffMaskH);
NewMask.name = 'Mask_' + num;
for (var i = 0; i < TempImgCon.children.length; i++) {
if (TempImgCon.children[i].name == e || TempImgCon.children[i].name.indexOf(e) != -1) {
if (TempImgCon.children[i].name.length <= e.length + 2 && TempImgCon.children[i].image.src.indexOf('Shop') != -1) {
let NewImg = TempImgCon.children[i].clone();
let ImgW = NewImg.image.naturalWidth * NewImg.scaleX;
let ImgH = NewImg.image.naturalHeight * NewImg.scaleY;
let RectW = MaskW;
let RectH = MaskH - 200;
let NewScale = NewImg.scaleX;
if (ImgW > NewMask.graphics._activeInstructions[0].w) {
NewScale = (NewMask.graphics._activeInstructions[0].w / (ImgW / 100)) / 100;
}
if (ImgH > NewMask.graphics._activeInstructions[0].h) {
let Temp = (NewMask.graphics._activeInstructions[0].h / (ImgH / 100)) / 100;
Temp > NewScale ? NewScale : Temp;
}
let MinImgW = NewImg.image.naturalWidth * NewScale - (NewImg.image.naturalWidth * NewScale / 100) * 30;
let MinImgH = NewImg.image.naturalHeight * NewScale - (NewImg.image.naturalHeight * NewScale / 100) * 30;
let CountW = Math.ceil(RectW / MinImgW);
let CountH = Math.ceil(RectH / MinImgH);
// отсюда можно придумать заполнение рандомное контейнеров
// но мне не хватилоу ума придумать как это сделать
NewImg.alpha = 1;
Basket.children.splice(2, 0, NewImg);
let NewX = (RectW - NewImg.image.naturalWidth * NewScale) / 2;
let NewY = (RectH - NewImg.image.naturalHeight * NewScale) / 2;
NewImg.x = NewX;
NewImg.y = NewY;
NewImg.scaleX = NewImg.scaleY = NewScale;
}
}
}
// для интернет-странички
// Для работы на стац компе
let x1 = -40;
let y1 = DiffMaskY;
let maxW = MaskW + 80;
let maxH = MaskH - DiffMaskH + 200;
Basket.addChild(makeDishRect(x1, y1, maxW, maxH));
Basket.children[Basket.children.length - 1].on('click', clickOnShopGood);
// console.log(Basket.children[Basket.children.length - 1]);
}
function scaleShop(e) {
let x1 = 0;
let y1 = 0;
let x2 = 0;
let y2 = 0;
let maxW = e.children[0].image.naturalWidth;
let maxH = e.children[0].image.naturalHeight;
let oldX = e.children[0].x + e.children[0].regX;
let oldY = e.children[0].y + e.children[0].regY;
oldX > x1 ? x1 : x1 = oldX;
oldY > y1 ? y1 : y1 = oldY;
oldX + maxW < x2 ? x2 : x2 = oldX + maxW;
oldY + maxH < y2 ? y2 : y2 = oldY + maxH;
let newW = (WIN_W / 100) * (0.9) * 100;
let newH = (WIN_H / 100) * (0.9) * 100;
let newS = 1;
let maxW2 = x2 - x1;
let maxH2 = y2 - y1;
if (maxW2 > newW) {
newS = (newW / (maxW2 / 100)) / 100;
}
if (maxH2 > newH) {
var temp = (newH / (maxH2 / 100)) / 100;
temp < newS ? newS = temp : newS;
}
// e.addChild(makeDishRect(x1, y1, maxW * 1.4, maxH * 1.4));
let newX = WIN_W / 2 - (maxW2 * newS) / 2;
let newY = WIN_H - maxH2 * newS - 100 * newS;
e.setTransform(newX, newY, newS, newS);
let FaryFace = MainCanvas.getChildByName('FARY_FACE');
let FFY = MainCanvas.getChildByName('FARY_FACE').y;
let diffX = FFY - newY;
FFY = diffX + newY
new createjs.Tween.get().to({}, 1500).call(Stay_Idle, [FaryFace]);
Jump(FaryFace);
new createjs.Tween.get(FaryFace).to({
x: newX + 50 * newS,
y: FFY - 1000 * newS + 120 * FaryFace.scaleY
}, 750);
new createjs.Tween.get(e).to({
alpha: 1
}, 150);
}
function clickOnShopGood(e) {
let GoodName = e.currentTarget.parent.name.substring(6)
for (let i = 0; i < MealGoodsArr.length; i++) {
if (GoodName == MealGoodsArr[i]) {
e.currentTarget.removeAllEventListeners('click');
rightChoiceGood(e.currentTarget.parent);
break;
}
if (i == MealGoodsArr.length - 1) {
wrongChoiceGood();
}
}
}
function rightChoiceGood(e) {
let SucGood = e.children[2]
e.removeChild(SucGood);
let BasCon = e.parent.getChildByName('Basket');
let Bas = e.parent.getChildByName('Basket').getChildByName('Basket');
BasCon.children.splice(BasCon.children.length - 1, 0, SucGood)
let BaskW = Bas.image.naturalWidth * Bas.scaleX;
let BaskH = Bas.image.naturalHeight * Bas.scaleY;
let GoodW = SucGood.image.naturalWidth * SucGood.scaleX;
let GoodH = SucGood.image.naturalHeight * SucGood.scaleY;
let MinX = Bas.x + 200;
let MaxX = Bas.x + BaskW - 200 - GoodW;
let MinY = Bas.y;
let MaxY = Bas.y + BaskH - GoodH;
let NewX = Math.floor(MinX + Math.random() * (MaxX + 1 - MinX));
let NewY = Math.floor(MinY + Math.random() * (MaxY + 1 - MinY));
SucGood.setTransform(NewX, NewY, SucGood.scaleX, SucGood.scaleY);
if (BasCon.children.length == MealGoodsArr.length + 1) {
let FaryFace = MainCanvas.getChildByName('FARY_FACE');
goToKitchen(BasCon, FaryFace);
}
}
function wrongChoiceGood() {
console.log('нет такого продукта1');
}
|
44dba8e93c6656bd7241fa7d375e8da2473bed01
|
[
"JavaScript"
] | 7 |
JavaScript
|
EropForWork/Game01
|
85a969db7dbe28655e1750b07687325040f1df60
|
1a034b3cda3989651ccae7fc9f043b1723ab9807
|
refs/heads/master
|
<repo_name>43790/back-end<file_sep>/src/main/java/ha/yass/forumback/entity/Post.java
package ha.yass.forumback.entity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "Post")
public class Post {
@Id
@GeneratedValue( strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "created_at")
private Date createdAt;
@Column(name = "modified_at")
private Date modifiedAt;
@Column(name = "content")
private String content;
@Column(name = "author_id")
private String author;
@Column(name = "categorie")
private int categorie;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getModifiedAt() {
return modifiedAt;
}
public void setModifiedAt(Date modifiedAt) {
this.modifiedAt = modifiedAt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getCategorie() {
return categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
}
<file_sep>/src/main/resources/application.properties
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url=jdbc:mysql://sql11.freesqldatabase.com:3306/sql11440810
spring.datasource.username=sql11440810
spring.datasource.password=<PASSWORD>
|
909e417a66e7f1723cb122cf283290e88b9af12d
|
[
"Java",
"INI"
] | 2 |
Java
|
43790/back-end
|
a1dab1e480946f93340a567b5e511c1ffc0b8d5d
|
1aaef55173d94fe04c88853f3c214f8da4f16250
|
refs/heads/master
|
<repo_name>nublikaska/webApp<file_sep>/src/main/java/HelloServlet.java
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(urlPatterns = "/hello2")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().append("hello1" + req.getMethod());
HttpSession httpSession = req.getSession();
if(httpSession.getValue("name") == null) {
httpSession.putValue("name", "hello session");
resp.getWriter().append("no session");
} else {
resp.getWriter().append((String)httpSession .getValue("name"));
}
}
}
|
2b87b8f84893d9c721154a83e82f4847018bd543
|
[
"Java"
] | 1 |
Java
|
nublikaska/webApp
|
3d18128bc84aab98e01e655bccac2686317fb41f
|
4f912b1e56ef9b2cdeb3846343c1be0109269abe
|
refs/heads/master
|
<file_sep>import os
import sys
from dvc import command
class Dvc:
@staticmethod
def check_installed():
return os.path.isdir(".dvc")
@staticmethod
def install():
command.init()
__all__ = ["Dvc"]
<file_sep># study-project
<div align="center">
[](https://github.com/lucasiscovici/study-project/actions?query=workflow%3Abuild)
[](https://pypi.org/project/study-project/)
[](https://github.com/lucasiscovici/study-project/pulls?utf8=%E2%9C%93&q=is%3Apr%20author%3Aapp%2Fdependabot)
[](https://github.com/psf/black)
[](https://github.com/PyCQA/bandit)
[](https://github.com/lucasiscovici/study-project/blob/master/.pre-commit-config.yaml)
[](https://github.com/lucasiscovici/study-project/releases)
[](https://github.com/lucasiscovici/study-project/blob/master/LICENSE)
DataScience and ML MAnagement
</div>
# CLI
```bash
curl -L -s https://tinyurl.com/study-project-init | sh -s my-project
#with alias
alias study-project-init="curl -L -s https://tinyurl.com/study-project-init | sh -s "
study-project-init my-project
```
This command will **init**:
- add directory my-project
- check if image 'studyproject/scipy-notebook' is up-to-date
- pull if not
- run container in port from 8888 to 8898 (check witch port is open)
```bash
study-project-init my-project --open
```
This command will
- **init** if need
- open the jupyter notebook in your browser
- the token is : study-project
## 🛡 License
[](https://github.com/lucasiscovici/study-project/blob/master/LICENSE)
This project is licensed under the terms of the `MIT` license. See [LICENSE](https://github.com/lucasiscovici/study-project/blob/master/LICENSE) for more details.
## 📃 Citation
```
@misc{study-project,
author = {study-project},
title = {DataScience and ML MAnagement},
year = {2020},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {\url{https://github.com/lucasiscovici/study-project}}
}
```
## Credits
This project was generated with [`python-package-template`](https://github.com/TezRomacH/python-package-template).
<file_sep># mypy: ignore-errors
import ast
import inspect
import io
import os
import sys
import tempfile
import warnings
import cloudpickle
import dvc.api
import git
from dvc import main
class StudyProjectPickle(cloudpickle.CloudPickler):
def __init__(
self,
file,
protocol=None,
buffer_callback=None,
cb_reducer_override=lambda obj, superValue: True,
):
super().__init__(file, protocol, buffer_callback)
self.cb_reducer_override = cb_reducer_override
def reducer_override(self, obj):
superValue = super().reducer_override(obj)
if self.cb_reducer_override:
self.cb_reducer_override(obj, superValue)
return superValue
def unicodetoascii(text):
uni2ascii = {
ord("\xe2\x80\x99".decode("utf-8")): ord("'"),
ord("\xe2\x80\x9c".decode("utf-8")): ord('"'),
ord("\xe2\x80\x9d".decode("utf-8")): ord('"'),
ord("\xe2\x80\x9e".decode("utf-8")): ord('"'),
ord("\xe2\x80\x9f".decode("utf-8")): ord('"'),
ord("\xc3\xa9".decode("utf-8")): ord("e"),
ord("\xe2\x80\x9c".decode("utf-8")): ord('"'),
ord("\xe2\x80\x93".decode("utf-8")): ord("-"),
ord("\xe2\x80\x92".decode("utf-8")): ord("-"),
ord("\xe2\x80\x94".decode("utf-8")): ord("-"),
ord("\xe2\x80\x94".decode("utf-8")): ord("-"),
ord("\xe2\x80\x98".decode("utf-8")): ord("'"),
ord("\xe2\x80\x9b".decode("utf-8")): ord("'"),
ord("\xe2\x80\x90".decode("utf-8")): ord("-"),
ord("\xe2\x80\x91".decode("utf-8")): ord("-"),
ord("\xe2\x80\xb2".decode("utf-8")): ord("'"),
ord("\xe2\x80\xb3".decode("utf-8")): ord("'"),
ord("\xe2\x80\xb4".decode("utf-8")): ord("'"),
ord("\xe2\x80\xb5".decode("utf-8")): ord("'"),
ord("\xe2\x80\xb6".decode("utf-8")): ord("'"),
ord("\xe2\x80\xb7".decode("utf-8")): ord("'"),
ord("\xe2\x81\xba".decode("utf-8")): ord("+"),
ord("\xe2\x81\xbb".decode("utf-8")): ord("-"),
ord("\xe2\x81\xbc".decode("utf-8")): ord("="),
ord("\xe2\x81\xbd".decode("utf-8")): ord("("),
ord("\xe2\x81\xbe".decode("utf-8")): ord(")"),
}
return text.decode("utf-8").translate(uni2ascii).encode("ascii")
class ImportFinder(ast.NodeVisitor):
def __init__(self):
self.imports = []
def processImport(self, full_name):
self.imports.append(full_name)
def visit_Import(self, node):
for alias in node.names:
self.processImport(alias.name)
def visit_ImportFrom(self, node):
if node.module == "__future__":
return
for alias in node.names:
name = alias.name
fullname = f"{node.module}.{name}" if node.module else name
self.processImport(fullname)
class Utils:
class Pickle:
@staticmethod
def find_imports(text):
root = ast.parse(text)
visitor = ImportFinder()
visitor.visit(root)
return visitor.imports
@staticmethod
def find_imports_from_obj(obj):
return Utils.Pickle.find_imports(inspect.getsource(obj).strip())
@staticmethod
def dump(
obj,
file,
protocol=None,
buffer_callback=None,
return_modules=False,
log=False,
):
"""Serialize obj as bytes streamed into file
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
speed between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
modules = set()
def cb_reducer(obj, value):
if log:
print(
"(Utils.Pickle.dump:cb_reducer:obj,value) : ",
obj,
value,
)
if hasattr(obj, "__module__"):
modules.add(obj.__module__)
pickler = StudyProjectPickle(
file,
protocol=protocol,
buffer_callback=buffer_callback,
cb_reducer_override=cb_reducer if return_modules else None,
)
pickler.dump(obj)
if return_modules:
return modules
load = cloudpickle.load
loads = cloudpickle.loads
@staticmethod
def dumps(
obj,
protocol=None,
buffer_callback=None,
return_modules=False,
log=False,
):
"""Serialize obj as a string of bytes allocated in memory
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
speed between processes running the same Python version.
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
compatibility with older versions of Python.
"""
modules = list()
def cb_reducer(obj, value):
if log:
print(
"(Utils.Pickle.dumps:cb_reducer:obj,value) : ",
obj,
value,
)
if hasattr(obj, "__module__"):
modules.append(obj.__module__)
try:
m = Utils.Pickle.find_imports_from_obj(obj)
modules.extend(list(m))
except Exception as e:
pass
with io.BytesIO() as file:
cp = StudyProjectPickle(
file,
protocol=protocol,
buffer_callback=buffer_callback,
cb_reducer_override=cb_reducer if return_modules else None,
)
cp.dump(obj)
modules = set(modules)
return (
file.getvalue()
if not return_modules
else (file.getvalue(), modules)
)
class RE:
@staticmethod
def captureValueInLine(text, pattern, sep=":"):
import re
return re.findall(
f"^.*{pattern}{sep}(.+)$", text, flags=re.MULTILINE
)[0].strip()
@staticmethod
def match(text, pattern):
import re
return re.match(pattern, text) is not None
@staticmethod
def findall(text, pattern, flags=None):
import re
return re.findall(pattern, text)
class Hash:
@staticmethod
def md5(string):
import hashlib
return hashlib.md5(string.encode()).hexdigest() # nosec
@staticmethod
def function_md5(func):
import inspect
return Utils.Hash.md5(inspect.getsource(func))
class Df:
@staticmethod
def to_csv(df, filename, index=True):
df.to_csv(filename, index=False)
@staticmethod
def to_csv_string(df, index=True):
import io
s = io.StringIO()
Utils.Df.to_csv(df, s, index=index)
return s.getvalue()
@staticmethod
def from_csv_string(csvString):
import io
import pandas as pd
s = io.StringIO(csvString)
return pd.read_csv(s)
class String:
@staticmethod
def remove_accents(text):
import unicodedata
return "".join(
c
for c in unicodedata.normalize("NFD", text)
if unicodedata.category(c) != "Mn"
)
@staticmethod
def remove_not_alphanumeric(text):
import re
return re.sub("[^a-zA-Z0-9 ]", "", text)
@staticmethod
def parse(text, sep=":"):
import re
dico = {}
if len(text) == 0:
return dico
for i in text.split("\n"):
m = re.findall(f"^([^{sep}]+){sep}(.+)$", i)
if len(m) == 0:
continue
dico[m[0][0].strip()] = m[0][1].strip()
return dico
@staticmethod
def unicodeToString(uni):
return unicodetoascii(uni)
class Shell:
@staticmethod
def command(commandString, shell=False):
import shlex
import subprocess
# process = subprocess.Popen(
# shlex.split(commandString) if not shell else commandString,
# stdout=subprocess.PIPE,
# shell=shell, # nosec
# )
p = subprocess.run(
shlex.split(commandString) if not shell else commandString,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell, # nosec
)
output, error = p.stdout, p.stderr
error2 = (
None
if p.returncode == 0
else (
output.decode("utf-8")
if (output and "error" in output.decode("utf-8").lower())
else error
)
)
return Struct(
**{
"output": output.decode("utf-8"),
"output_orgi": output,
"error": error2,
"errorOrig": error,
"commandString": commandString,
}
)
class File:
@staticmethod
def exist(file):
import os.path
return os.path.isfile(file)
@staticmethod
def read(filename):
with open(filename) as f:
output = f.read()
return output
@staticmethod
def write(text, filename):
with open(filename, "w") as f:
f.write(text)
@staticmethod
def tmp(ext="csv"):
file = TMP_FILE()
return file.get_filename(ext)
@staticmethod
def write_in_tmp(text, ext="csv"):
file = TMP_FILE()
filename = file.get_filename(ext)
Utils.File.write(text, filename)
return filename
@staticmethod
def tmp_delete(filename):
file = TMP_FILE()
file.filename = filename
file.delete()
@staticmethod
def touch(file):
Utils.Shell.command(f"touch '{file}'")
class Dir:
@staticmethod
def mk(dir, p=None):
os.mkdir(dir)
@staticmethod
def exist(dir):
return os.path.isdir(dir)
@staticmethod
def ifelse(condition, true, false=""):
return true if condition else false
@staticmethod
def md5FromDf(df, index=False):
md5 = Utils.Hash.md5(Utils.Df.to_csv_string(df, index=index))
return md5
class TMP_FILE:
def __init__(self):
self.filename = None
def get_filename(self, ext="png"):
if self.filename is not None:
self.delete()
_, self.filename = tempfile.mkstemp(suffix="." + ext)
return self.filename
def delete(self):
# print(self.i)
os.remove(self.filename)
class Struct(dict):
def __init__(self, **kw):
dict.__init__(self, kw)
self.__dict__.update(kw)
def __str__(self):
a = ""
for i in self.__dict__.keys():
a += f"{i} :"
a += f"\n\t{self.__dict__[i]}\n"
return a
class Git:
installed = False
path = ".git"
gitignore = ".gitignore"
@staticmethod
def getGit():
return git.cmd.Git(os.getcwd())
@staticmethod
def commandGit(command, *args, **xargs):
rep = Utils.Shell.command(f"git {command}", *args, **xargs)
return rep
@staticmethod
def check_installed():
return Git.installed or os.path.isdir(os.getcwd() + f"/{Git.path}")
@staticmethod
def install(add=True, commit=True, message="git installed", name=None):
print("\tset up Git...")
g = Git.getGit()
g.init()
if name is not None:
Git.addBranch(name)
Utils.Shell.command(f"touch {Git.gitignore}")
if add:
Git.add([Git.gitignore])
if commit:
StudyProjectEnv.commit(message)
print("\tGit initialized")
Git.installed = True
@staticmethod
def addTag(name, desc):
g = Git.getGit()
g.tag(["-a", f"'{name}'", "-m", f"'{desc}'"])
@staticmethod
def getRefBranches():
rep = Git.commandGit("branch --format '%(refname)'")
if rep.error:
raise Exception(rep)
return rep.output.strip()
@staticmethod
def getRefAndHeadBranches():
rep = Git.commandGit("branch --format '%(refname) %(objectname)'")
if rep.error:
raise Exception(rep)
return rep.output.strip()
@staticmethod
def reset():
rep = Git.commandGit("reset")
if rep.error:
raise Exception(rep)
@staticmethod
def ignoreChanges(pathToIgnore=[]):
if len(pathToIgnore) == 0:
rep = Git.commandGit("rm --cached --ignore-unmatch *")
if rep.error:
raise Exception(rep)
else:
g = Git.getGit()
g.rm(["--cached"] + pathToIgnore)
@staticmethod
def getBranches(pattern=None, withHash=False):
if not withHash:
refBranches = Git.getRefBranches()
branches = [i.split("/")[2] for i in refBranches.split("\n")]
if pattern is not None:
return [
i
for i in branches
if Utils.RE.match(text=i, pattern=pattern)
]
return branches
refBranches = Utils.String.parse(Git.getRefAndHeadBranches(), sep=" ")
branches = {
ref.split("/")[2]: head for ref, head in refBranches.items()
}
if pattern is not None:
return {
k: v
for k, v in branches.items()
if Utils.RE.match(text=k, pattern=pattern)
}
return branches
@staticmethod
def getBranch():
rep = Git.commandGit(f"branch --show-current")
if rep.error:
raise Exception(rep)
return rep.output.strip()
@staticmethod
def deleteBranch(name, force=False):
Git.commandGit(f"branch {Utils.ifelse(force,'-D','-d')} {name}")
@staticmethod
def checkBranch(name):
rep = Git.commandGit(
f"branch --list '{name}' | tr -d ' '", shell=True # nosec
)
if rep.error:
raise Exception(rep)
branch = rep.output
return len(branch) > 0
@staticmethod
def addBranch(name, checkout=True, show_rep=False):
if Git.checkBranch(name):
return
if checkout:
g = Git.getGit()
g.checkout(["-b", f"{name}"])
else:
g = Git.getGit()
g.branch([f"{name}"])
@staticmethod
def getNoHooks():
return " -c core.hooksPath=/dev/null "
@staticmethod
def getStaged():
stagedString = Git.commandGit(
"diff --name-only --cached"
).output.rstrip()
if len(stagedString) == 0:
return []
return stagedString.split("\n")
@staticmethod
def getModified():
stagedString = Git.commandGit("diff --name-only").output.rstrip()
if len(stagedString) == 0:
return []
return stagedString.split("\n")
@staticmethod
def temporaryCommit():
m = Git.getModified()
if len(m) == 0:
return False
Git.reset()
# print(Git.getBranch(),m)
Git.ignoreChanges(m)
# Git.add(u=True)
staged = Git.getStaged()
# print(staged)
if len(staged) == 0:
return False
StudyProjectEnv.commit("tempCommit")
return True
@staticmethod
def backCommit():
Git.commandGit("reset --mixed HEAD^1")
@staticmethod
def temporaryCommitBack():
Git.backCommit()
# Git.reset()
@staticmethod
def goToBranch(name, no_hooks=False, show_rep=False, no_reset=True):
# g = Git.getGit()
# g.checkout([f"{name}"])
tempCommit = Git.temporaryCommit() if not no_reset else False
# if not no_reset:
# Git.reset()
# Git.ignoreChanges()
hooks = Git.getNoHooks() if no_hooks else ""
rep = Git.commandGit(f"{hooks}checkout {name}")
if show_rep:
print(rep)
if rep.error:
print(rep)
raise Exception(rep)
return tempCommit
@staticmethod
def toBrancheName(name, sep="-"):
import re
name = name.strip()
name = Utils.String.remove_accents(name)
name = Utils.String.remove_not_alphanumeric(name)
name = re.sub(" +", " ", name)
name = re.sub(" ", sep, name)
name = name.lower()
return name
@staticmethod
def getConfigUser(author):
return " ".join(
[
"-c",
f"user.name='{author.split('<')[0].strip()}'",
"-c",
f"user.email='{author.split('<')[1][:-1].strip()}'",
]
)
@staticmethod
def commit(message, author=""):
if len(author) > 0:
commiter = Git.getConfigUser(author)
author = f'--author="{author}"'
message = message.replace("'", '"')
rep = Git.commandGit(f"{commiter} commit {author} -m '{message}'")
if rep.error:
print(rep)
raise Exception(rep.error)
# if rep.output:
# print(rep.output,rep.commandString)
return
g = Git.getGit()
if author:
g.commit([author, "-m", f"'{message}'"])
else:
g.commit(["-m", f"'{message}'"])
@staticmethod
def merge(branch, no_ff=True, message="", author=""):
if len(author) > 0:
commiter = Git.getConfigUser(author)
message = message.replace("'", '"')
messageN = f"-m '{message}'"
rep = Git.commandGit(
f"{commiter} merge {Utils.ifelse(no_ff,'--no-ff')} {Utils.ifelse(message,messageN)} {branch}"
)
if rep.error:
print(rep)
raise Exception(rep.error)
# if rep.output:
# print(rep.output, rep.commandString)
return
g = Git.getGit()
g.merge([Utils.ifelse(no_ff, "--no-ff"), branch])
@staticmethod
def add(listToAdd=[], u=False):
g = Git.getGit()
if u:
g.add("-u", [] + listToAdd)
else:
g.add([] + listToAdd)
@staticmethod
def checkIdentity():
rep = Git.config("user.name", globally=True)
if rep.error:
raise Exception(rep.error)
rep2 = Git.config("user.name", globally=False)
if rep2.error:
raise Exception(rep2.error)
return len(rep.output) > 0 or len(rep2.output) > 0
@staticmethod
def config(k, v=None, globally=False, remove=False):
return Git.commandGit(
f"config {Utils.ifelse(globally,'--global')} {Utils.ifelse(v is None and not remove,'--get')} {Utils.ifelse(remove,'--unset')} {k} {Utils.ifelse(v is not None, v)}"
)
class Dvc:
path = ".dvc"
installed = False
dvcignore = ".dvcignore"
author = "DvcBot <<EMAIL>>"
textCheckDocker = """
check_docker_container(){
container="${1}"
lignes=$(docker ps -a --filter "name=^${container}$" | wc -l | tr -d ' ')
[ "$lignes" -gt 1 ]
return $?
}
if [ -z "$DOCKER_CONTAINER_NAME" ]; then
if ! command -v dvc &> /dev/null
then
if ! command -v docker &> /dev/null
then
exit
else
if [ -f ".study-project-init" ]; then
DOCKER_CONTAINER_NAME=$(cat ".study-project-init")
if check_docker_container "$DOCKER_CONTAINER_NAME"
then
alias exec="docker exec -d "$DOCKER_CONTAINER_NAME""
fi
fi
fi
fi
fi
"""
@staticmethod
def check_installed():
return Dvc.installed or os.path.isdir(os.getcwd() + f"/{Dvc.path}")
@staticmethod
def changeHookDVC(name):
fileLines = Utils.File.read(f"{Git.path}/hooks/{name}").split("\n")
newLines = (
fileLines[:1] + Dvc.textCheckDocker.split("\n") + fileLines[1:]
)
Utils.File.write("\n".join(newLines), f"{Git.path}/hooks/{name}")
@staticmethod
def changeHooksDVC():
for i in ["pre-commit", "pre-push", "post-checkout"]:
Dvc.changeHookDVC(i)
@staticmethod
def install():
print("\tset up dvc...")
k = main.main(["init", "--quiet"])
Dvc.config("core.autostage", "true")
Git.add([f"{Dvc.path}/config"])
main.main(["install"])
Dvc.changeHooksDVC()
StudyProjectEnv.commit("dvc installed (config+hooks)")
print("\tDvc initialized")
Dvc.installed = True
@staticmethod
def commit(message, author=None):
author = Dvc.author if author is None else author
return Git.commit(message, author=Dvc.author)
@staticmethod
def merge(branch, no_ff=True, message="", author=None):
author = Dvc.author if author is None else author
return Git.merge(branch, no_ff=no_ff, author=author, message=message)
@staticmethod
def config(k, v):
main.main(["config", k, v])
@staticmethod
def addDataFromDF(df, name, path="", to="csv", ext="csv", index=False):
file = TMP_FILE()
if to not in ["csv"]:
print(f"to:'{to}' not implemented")
return
if len(path) > 0:
path = path + "/"
df.to_csv(f"{path}{name}.{ext}", index=index)
main.main(
[
"add",
f"{path}{name}.{ext}",
]
)
@staticmethod
def getMd5(filename, path="", ext="csv"):
if len(path) > 0:
path = path + "/"
if not Utils.File.exist(f"{path}{filename}.{ext}.dvc"):
return None
file = Utils.File.read(f"{path}{filename}.{ext}.dvc")
return Utils.RE.captureValueInLine(file, "md5")
@staticmethod
def open(fileName):
with dvc.api.open(fileName) as fd:
text = fd.read()
return text
@staticmethod
def read(fileName):
return dvc.api.read(fileName)
class StudyProjectEnv:
prefix_branch = "study_project"
master = f"{prefix_branch}/study_project"
nb = "master"
installed = False
path_docker_init = ".study-project-init"
path = ".study_project"
study_project_config = ".config"
step = 0
prefixe = "study_project : "
default_branch = "study_project_set_up"
data_path = "data"
study_project_data = "data"
study_project_projects = "projects"
study_project_studies = "studies"
# proj
projSetUp = "setup"
projData = "data"
project_prefixe = "project"
gitIgnore = f"""
{path_docker_init}
__pycache__/
.ipynb_checkpoints/
{Git.gitignore}.*
{data_path}/*
"""
gitIgnoreBranch = f"""
*
!/{path}/
!/{path}/*
!/{Dvc.path}/
!/{Dvc.path}/*
!/{data_path}/
!/{data_path}/
!{Git.gitignore}
!{Dvc.dvcignore}
"""
# TODO: alias git when destination path change per_exemple()
postCheckoutGitignoreCheck = f"""
old_ref=$1
new_ref=$2
branch_switched=$3
if [ $branch_switched != '1' ]
then
echo "---- NO CHECKOUT ----"
exit 0
fi
echo "---- POST CHECKOUT ----"
current_branch=$(git rev-parse --abbrev-ref HEAD | tr '/' '_')
hook_dir=$(dirname $0)
root_dir="$(pwd -P)"
info_dir="$root_dir/{Git.path}/info"
exclude_target='{Git.gitignore}'
if [ -f "$root_dir/$exclude_target.$current_branch" ]
then
echo "Prepare to use {Git.gitignore}.$current_branch as exclude file"
exclude_target={Git.gitignore}.$current_branch
fi
cd "$info_dir"
rm exclude
echo "Copy {Git.gitignore}.$current_branch file in place of exclude"
cp "$root_dir/$exclude_target" exclude
echo "--- POST CHECKOUT END ---"
cd "$root_dir"
"""
@staticmethod
def addGitIgnore():
Utils.File.write(f"{StudyProjectEnv.gitIgnore}", Git.gitignore)
@staticmethod
def addGitIgnoreBranch(branchName):
branchName = branchName.replace("/", "_")
Utils.File.write(
StudyProjectEnv.gitIgnoreBranch, f"{Git.gitignore}.{branchName}"
)
@staticmethod
def addPostCheckoutHook():
name = "post-checkout"
fileLines = Utils.File.read(f"{Git.path}/hooks/{name}").split("\n")
newLines = (
fileLines[:1]
+ StudyProjectEnv.postCheckoutGitignoreCheck.split("\n")
+ fileLines[1:]
)
Utils.File.write("\n".join(newLines), f"{Git.path}/hooks/{name}")
@staticmethod
def addPreCommitHook():
name = "pre-commit"
fileLines = Utils.File.read(f"{Git.path}/hooks/{name}").split("\n")
newLines = (
fileLines[:1]
+ StudyProjectEnv.textPreCommit.split("\n")
+ fileLines[1:]
)
Utils.File.write("\n".join(newLines), f"{Git.path}/hooks/{name}")
@staticmethod
def add():
Git.add([StudyProjectEnv.path + "/", Git.gitignore])
@staticmethod
def check_installed():
return StudyProjectEnv.installed or os.path.isdir(
os.getcwd() + "/" + StudyProjectEnv.path
)
@staticmethod
def install():
print("\tset up study_project...")
os.mkdir(StudyProjectEnv.path)
StudyProjectEnv.addGitIgnore()
os.mkdir(StudyProjectEnv.data_path)
Utils.File.touch(StudyProjectEnv.data_path + f"/{Git.gitignore}")
os.mkdir(
StudyProjectEnv.path + f"/{StudyProjectEnv.study_project_projects}"
)
os.mkdir(
StudyProjectEnv.path + f"/{StudyProjectEnv.study_project_config}"
)
Utils.File.touch(
StudyProjectEnv.path
+ f"/{StudyProjectEnv.study_project_projects}"
+ f"/{Git.gitignore}"
)
os.mkdir(
StudyProjectEnv.path + f"/{StudyProjectEnv.study_project_studies}"
)
Utils.File.touch(
StudyProjectEnv.path
+ f"/{StudyProjectEnv.study_project_studies}"
+ f"/{Git.gitignore}"
)
os.mkdir(
StudyProjectEnv.path + f"/{StudyProjectEnv.study_project_data}"
)
Utils.File.touch(
StudyProjectEnv.path
+ f"/{StudyProjectEnv.study_project_data}"
+ f"/{Git.gitignore}"
)
Utils.File.write(
f"\n{StudyProjectEnv.study_project_config}\n"
+ StudyProjectEnv.gitIgnore,
f"{StudyProjectEnv.path}/{Git.gitignore}",
)
StudyProjectEnv.addPostCheckoutHook()
print("\tstudy_project initialized")
StudyProjectEnv.installed = True
Git.add(
[
StudyProjectEnv.path,
StudyProjectEnv.path + "/",
StudyProjectEnv.data_path,
# StudyProjectEnv.data_path + "/",
Git.gitignore,
]
)
StudyProjectEnv.commit("study_project installed")
@staticmethod
def addBranch(name, *args, **xargs):
brName = f"{StudyProjectEnv.step}-{name}"
Git.addBranch(brName, *args, **xargs)
StudyProjectEnv.step += 1
return brName
@staticmethod
def getProjectVersions(id):
projName = StudyProjectEnv.getProjectBranchName(id, no_prefix=True)
# StudyProjectEnv.getConfigProject(id)
if Utils.File.exist(
f"{StudyProjectEnv.path}/{StudyProjectEnv.study_project_config}/{projName}"
):
return Utils.File.read(
f"{StudyProjectEnv.path}/{StudyProjectEnv.study_project_config}/{projName}"
)
return ""
@staticmethod
def saveProjectVersions(id, versions):
projName = StudyProjectEnv.getProjectBranchName(id, no_prefix=True)
if not Utils.Dir.exist(
f"{StudyProjectEnv.path}/{StudyProjectEnv.study_project_config}"
):
Utils.Dir.mk(
f"{StudyProjectEnv.path}/{StudyProjectEnv.study_project_config}"
)
Utils.File.write(
versions,
filename=f"{StudyProjectEnv.path}/{StudyProjectEnv.study_project_config}/{projName}",
)
return versions
@staticmethod
def getVersions(id):
# projName = StudyProjectEnv.getProjectBranchName(id)
return StudyProjectEnv.getProjectVersions(id)
@staticmethod
def getVersion(hash, id):
versionsDict = StudyProjectEnv.getVersionsDict(id)
return versionsDict[hash] if hash in versionsDict else None
@staticmethod
def getHashFromVersion(version, id):
versionsDict = StudyProjectEnv.getVersionsDict(id)
return versionsDict[version] if version in versionsDict else None
@staticmethod
def saveVersions(id, versions):
return StudyProjectEnv.saveProjectVersions(id, versions)
@staticmethod
def getVersionsDict(id):
versions = Utils.String.parse(StudyProjectEnv.getVersions(id))
return versions
@staticmethod
def getVersionNumber(id):
versions = StudyProjectEnv.getVersionsDict(id)
return len(versions) // 2
@staticmethod
def addVersion(v, hash, id):
versions = StudyProjectEnv.getVersions(id)
versionsDict = Utils.String.parse(versions)
last = f"{versions}\n" if len(versions) > 0 else ""
StudyProjectEnv.saveVersions(id, f"{last}{hash}: {v}\n{v}: {hash}")
@staticmethod
def addProjectBranch(id):
nb = StudyProjectEnv.getVersionNumber(id)
brName = StudyProjectEnv.getProjectBranchName(id, nb)
Git.addBranch(brName, checkout=False)
tempCommit = Git.goToBranch(brName, no_reset=False)
StudyProjectEnv.addGitIgnoreBranch(brName)
return (brName, nb, tempCommit)
@staticmethod
def check_all_installed():
install = False
if (
not Git.check_installed()
or not Dvc.check_installed()
or not StudyProjectEnv.check_installed()
):
if (
Git.check_installed()
or Dvc.check_installed()
or StudyProjectEnv.check_installed()
):
print(
"study_project : git/Dvc/study_project are already installed, we can't for the moment install only on off them"
)
# StudyProjectEnv.check_config()
return False
install = True
print("Set Up Study Project ....")
if not Git.check_installed():
# StudyProjectEnv.check_init()
Git.install(name=StudyProjectEnv.master)
StudyProjectEnv.addBranch(f"set-up")
# Git.checkout("master")
# Git.merge("install-git")
if not Dvc.check_installed():
# StudyProjectEnv.addBranch(f"install-dvc")
Dvc.install()
if not StudyProjectEnv.check_installed():
# StudyProjectEnv.addBranch(f"install-study-project")
StudyProjectEnv.install()
currBranche = Git.getBranch()
# print("isntall").
Git.goToBranch(StudyProjectEnv.master, no_hooks=True)
StudyProjectEnv.merge(currBranche, message="set-up")
Git.deleteBranch(currBranche)
# add nb branch
Git.addBranch(StudyProjectEnv.nb)
print("Study Project OK")
# return True
StudyProjectEnv.check_config()
return True
@staticmethod
def find_projects():
from collections import defaultdict
branches = Git.getBranches(
pattern=f"^{StudyProjectEnv.project_prefixe}-.+"
)
proj = defaultdict(list)
for i in branches:
projName = Utils.RE.findall(
text=i, pattern=f"^{StudyProjectEnv.project_prefixe}-(.+)-v.+$"
)[0]
proj[projName].append(i)
for projName, branch in proj.items():
projList = []
for i in branch:
StudyProjectEnv.goToBranch(i)
projList.append()
return proj
@staticmethod
def check_config():
if not Utils.Dir.exist(
f"{StudyProjectEnv.path}/{StudyProjectEnv.study_project_config}"
):
Utils.Dir.mk(
StudyProjectEnv.path
+ f"/{StudyProjectEnv.study_project_config}"
)
Utils.File.write(
f"{StudyProjectEnv.study_project_config}",
f"{StudyProjectEnv.path}/{Git.gitignore}",
)
StudyProjectEnv.find_projects()
# print("OK")
@staticmethod
def check_init():
rep = Git.commandGit("branch")
if rep.error:
raise Exception(rep.error)
if len(rep.output) == 0:
Utils.Shell.command("touch .initial_commit")
Git.add([".initial_commit"])
Git.commit()
@staticmethod
def goToBranch(*args, **xargs):
return Git.goToBranch(*args, **xargs)
@staticmethod
def commit(message, prefixe=None):
prefixe = StudyProjectEnv.prefixe if prefixe is None else prefixe
return Dvc.commit(f"{prefixe}{message}")
@staticmethod
def merge(*args, message="", prefixe=None, **xargs):
prefixe = StudyProjectEnv.prefixe if prefixe is None else prefixe
message = message if len(message) == 0 else f"{prefixe}{message}"
return Dvc.merge(*args, message=message, **xargs)
@staticmethod
def addData(data, filename, path=None):
path = StudyProjectEnv.data_path if path is None else path
md5OfData = Utils.md5FromDf(data)
md5InFileName = Dvc.getMd5(filename, path)
if md5InFileName != md5OfData:
Dvc.addDataFromDF(data, filename, path=path)
return (True, md5OfData)
return (False, md5OfData)
@staticmethod
def getFileData(dataParsed, data_name, id):
fileName = Git.toBrancheName(id, sep="_")
path = f"{StudyProjectEnv.data_path}/{fileName}_{data_name}.csv"
pathDvc = f"{path}.dvc"
return Utils.Df.from_csv_string(Dvc.read(path))
if Utils.File.exist(pathDvc): # save fileName in data
dataFile = Utils.File.read(pathDvc)
md5File = Utils.RE.captureValueInLine(dataFile, "md5")
pathFile = Utils.RE.captureValueInLine(dataFile, "path")
if dataParsed[data_name] == md5File:
fileData = Dvc.read(pathFile)
return Utils.Df.from_csv_string(fileData)
@staticmethod
def getData(*args, **xargs):
return Data.getData(*args, **xargs)
@staticmethod
def saveData(*args, **xargs):
Data.saveData(*args, **xargs)
@staticmethod
def forgotData(dataHash):
pass
@staticmethod
def getProjPath(id):
return (
StudyProjectEnv.path
+ f"/{StudyProjectEnv.study_project_projects}/"
+ Git.toBrancheName(id, sep="_")
)
@staticmethod
def saveProject(project):
def addCommit():
StudyProjectEnv.add()
StudyProjectEnv.commit(f"save Project '{project.id}'")
def upVersion(dataHash, setUpMd5Proj):
StudyProjectEnv.addVersion(
project.v,
Utils.Hash.md5(f"{dataHash}\n{setUpMd5Proj}"),
project.id,
)
projPath = StudyProjectEnv.getProjPath(project.id)
if not Utils.Dir.exist(projPath):
Utils.Dir.mk(projPath)
# os.mkdir(StudyProjectEnv.path+"/project/"+Git.toBrancheName(project.id,sep="_")+"/studies")
# os.mkdir(StudyProjectEnv.path+"/project/"+Git.toBrancheName(project.id,sep="_")+"/data")
dataHash = {data.get_hash(): data.id for data in project.data.values()}
dataHash = dict(sorted(dataHash.items(), key=lambda a: a[0]))
dataHashDico = dataHash
dataHashStr = "\n".join(dataHash.keys())
if not Utils.File.exist(f"{projPath}/{StudyProjectEnv.projData}"):
lastDataHashStr = ""
else:
lastDataHashStr = Utils.File.read(
f"{projPath}/{StudyProjectEnv.projData}"
)
if lastDataHashStr != dataHashStr:
Utils.File.write(
dataHashStr, filename=f"{projPath}/{StudyProjectEnv.projData}"
)
lastDataHash = set(lastDataHashStr.split("\n"))
dataHash = set(dataHash.keys())
newData = dataHash - lastDataHash
pastData = lastDataHash - dataHash
for i in newData:
StudyProjectEnv.saveData(project.data[dataHashDico[i]], i)
for i in pastData:
StudyProjectEnv.forgotData(i)
if project.setUp:
setUpMd5Proj = Utils.Hash.function_md5(project.setUp)
if Utils.File.exist(f"{projPath}/{StudyProjectEnv.projSetUp}"):
setUpMd5 = Utils.File.read(
f"{projPath}/{StudyProjectEnv.projSetUp}"
)
if setUpMd5Proj == setUpMd5:
# upVersion("", setUpMd5Proj)
return
Utils.File.write(
setUpMd5Proj, filename=f"{projPath}/{StudyProjectEnv.projSetUp}"
)
addCommit()
upVersion("", setUpMd5Proj)
@staticmethod
def getProjectBranchName(id, v=None, no_prefix=False):
versions = "" if v is None else f"-v{v}"
prefix = f"{StudyProjectEnv.prefix_branch}/" if not no_prefix else ""
return f"{prefix}{StudyProjectEnv.project_prefixe}-{Git.toBrancheName(id)}{versions}"
@staticmethod
def getProjectBranch(id, setUp=None, version=None):
import warnings
def getProjHash():
setUpMd5Proj = Utils.Hash.function_md5(setUp)
return Utils.Hash.md5(f"\n{setUpMd5Proj}")
branchName = StudyProjectEnv.getProjectBranchName(id, v=version)
if setUp is None and version is None:
vNum = StudyProjectEnv.getVersionNumber(id)
if vNum == 0:
return None
version = vNum - 1
branchName = StudyProjectEnv.getProjectBranchName(id, v=version)
if version is not None:
if Git.checkBranch(branchName):
if setUp is None:
return branchName
else:
projHash = getProjHash()
hashInConfig = StudyProjectEnv.getHashFromVersion(
version, id
)
if projHash != hashInConfig:
warnings.warn(
"/!\\ setUp different de celui en memoire : Vous devez créer une nouvelle version du project"
)
return None
return branchName
projHash = getProjHash()
v = StudyProjectEnv.getVersion(projHash, id)
return branchName + f"-v{v}" if v is not None else None
# studiesHash=[study.get_hash() for study in project.studies.values()]
# Utils.File.write("\n".join(dataHash),filename=f"{projPath}/studies")
# hash([project.data,project.studies])
# StudyProjectEnv.create_project()
@staticmethod
def getProject(id, setUp):
projPath = StudyProjectEnv.getProjPath(id)
projStr = ""
if Utils.Dir.exist(projPath):
proj = StudyProject(id)
setUpMd5Proj = None
if Utils.File.exist(f"{projPath}/{StudyProjectEnv.projSetUp}"):
setUpMd5 = Utils.File.read(
f"{projPath}/{StudyProjectEnv.projSetUp}"
)
if setUp is None:
setUpMd5Proj = setUpMd5
# TODO: retrieve setUp source code
proj.setUp = None
else:
setUpMd5Proj = Utils.Hash.function_md5(setUp)
if setUpMd5Proj == setUpMd5:
proj.setUp = setUp
else:
proj.setUp = "outdated"
print("SetUp is not the saved")
return proj
# projStr+="\n"+setUpMd5
if Utils.File.exist(f"{projPath}/{StudyProjectEnv.projData}"):
DataHash = Utils.File.read(
f"{projPath}/{StudyProjectEnv.projData}"
)
data = {
i.id: i
for i in [
StudyProjectEnv.getData(Datahashi)
for Datahashi in DataHash.split("\n")
]
}
proj.data = Struct(**data)
projHash = Utils.Hash.md5(f"\n{setUpMd5Proj}")
proj.v = StudyProjectEnv.getVersion(projHash, proj.id)
return proj
return None
class Data:
@staticmethod
def getTrainName(fileName):
return f"{fileName}_train"
@staticmethod
def getTestName(fileName):
return f"{fileName}_test"
@staticmethod
def getDataName(fileName, k):
return f"{fileName}_data_{k}"
@staticmethod
def getData(dataHash):
projPath = (
StudyProjectEnv.path + f"/{StudyProjectEnv.study_project_data}"
)
if Utils.File.exist(projPath + "/" + dataHash):
dataString = Utils.File.read(projPath + "/" + dataHash)
dataParsed2 = Utils.String.parse(
dataString, sep=":"
) # {i: Utils.String.parse(dataString,sep=":") for i in ["id","comment","train","test","target"]}
data = {}
dataParsed = {}
for k, v in dataParsed2.items():
if Utils.RE.match(k, "^data."):
data[k[len("data.") :]] = StudyProjectEnv.getFileData(
{"data_" + k[len("data.") :]: v},
"data_" + k[len("data.") :],
dataParsed["id"],
)
else:
dataParsed[k] = v
dataParsed["data"] = data
dataFiles = {
i: StudyProjectEnv.getFileData(dataParsed, i, dataParsed["id"])
for i in ["train", "test"]
}
dataReady = {**dataParsed, **dataFiles}
return Data().setData(**dataReady)
print(f"error : {projPath} / {dataHash}")
return Data()
@staticmethod
def saveData(data, dataHash):
projPath = StudyProjectEnv.path + "/data"
if not Utils.File.exist(projPath + "/" + dataHash):
StudyProjectEnv.addData(
data.train, Data.getTrainName(data.fileName)
)
StudyProjectEnv.addData(data.test, Data.getTestName(data.fileName))
fileStr = Data.get_file_export(
data,
lambda name, data_: StudyProjectEnv.addData(
data_, Data.getDataName(data.fileName, name)
),
)
Utils.File.write(fileStr, projPath + "/" + dataHash)
def setData(self, /, id, train, test, target, comment="", data={}):
# check is pandas df, series
self.id = id
self.train = train
self.test = test
self.target = target
self.comment = comment
self.data = data
# maybe -> StudyProjectEnv should do that
brName = Git.toBrancheName(id)
self.fileName = Git.toBrancheName(id, sep="_")
fileName = self.fileName
(new, md5_train) = StudyProjectEnv.addData(
self.train, Data.getTrainName(fileName)
)
# (new2, md5_target) = StudyProjectEnv.addData(
# self.target, f"{fileName}_target"
# )
(new2, md5_test) = StudyProjectEnv.addData(
self.test, Data.getTestName(fileName)
)
new3 = False
data_md5 = {}
for k, v in self.data.items():
(new_, md5_data_) = StudyProjectEnv.addData(
v, Data.getDataName(fileName, k)
)
data_md5[k] = md5_data_
new3 = new3 or new_
self.data_md5 = data_md5
self.md5_train = md5_train
self.md5_test = md5_test
if new or new2 or new3:
StudyProjectEnv.commit(f"add Data '{id}'")
# StudyProjectEnv.addBranch(f"add-data-{brName}")
return self
@staticmethod
def get_file_export(data, data_data_cb=lambda name, data_: True):
comment = data.comment.replace("\n", "\\n")
fileStr = f"""id: {data.id}
comment: {comment}
target: {data.target}
train: {data.md5_train}
test: {data.md5_test}"""
for name, data_ in data.data.items():
data_data_cb(name, data_)
fileStr += f"\ndata.{name}: {data.data_md5[name]}"
return fileStr
def get_hash(self):
fileStr = Data.get_file_export(self)
return Utils.Hash.md5(fileStr)
class Study:
"""docstring for Study"""
def __init__(self, id, data=None):
self.id = id
self.data = data
class StudyProject:
env = StudyProjectEnv
dvc = Dvc
git = Git
utils = Utils
def __init__(self, id, saveProject=True):
self.data = {}
self.studies = {}
self.id = id
self.saveProject = saveProject
def saveData(self, id, train, test, target, comment="", data={}):
if id in self.data:
print(f"\tData '{id}' : loaded ")
return self.data[id]
print(f"\tData '{id}' : creating... ")
dataObj = Data()
dataObj.setData(id, train, test, target, comment, data)
self.data[id] = dataObj
self.data = Struct(**self.data)
print(f"\tData '{id}' : ok ")
if self.saveProject:
StudyProjectEnv.saveProject(self)
@classmethod
def getOrCreate(self, id, setUp=None, version=None, recreate=False):
if not StudyProjectEnv.check_all_installed():
return
# GOTO BRANCH MASTER:
tempCommitBranchCurr = None
branchCurr = Git.getBranch()
if branchCurr != StudyProjectEnv.master:
# TODO: check if the branche is study-project and force to be in master if it
# print(f"getOrCreate {branchCurr}")
tempCommitBranchCurr = Git.goToBranch(
StudyProjectEnv.master, no_reset=False
)
if tempCommitBranchCurr:
warnings.warn(
f"Ton travail a été commit dans un commit temporaire sur la branche {branchCurr}"
)
if Utils.RE.match(
pattern=f"^{StudyProjectEnv.prefix_branch}/", text=branchCurr
):
branchCurr = StudyProjectEnv.nb
tempCommitBranchCurr = False
else:
branchCurr = StudyProjectEnv.nb
tempCommitBranchCurr = False
def comeBackMaster(tempCommit):
# print("comeBackMaster")
tempCommitToMaster = Git.goToBranch(
StudyProjectEnv.master, no_reset=False
)
if tempCommitToMaster:
warnings.warn(
f"Wtf pb il y a eu un commit temporaire : '{Git.getBranch()}' [{tempCommit}] -> '{StudyProjectEnv.master}'? "
)
sys.exit()
if tempCommit:
Git.backCommit()
def comeBackBranchCurr():
# print("comeBackBranchCurr", Git.getBranch(),
# branchCur:r, tempCommitBranchCurr)
if Git.getBranch() == branchCurr:
return
tempCommitToBranchCurr = Git.goToBranch(branchCurr, no_reset=False)
if tempCommitToBranchCurr:
warnings.warn(
f"Wtf pb il y a eu un commit temporaire : '{Git.getBranch()}' -> '{branchCurr}'? "
)
sys.exit()
if tempCommitBranchCurr:
Git.backCommit()
# tempCommitBranchCurr=False
def create_project():
if setUp is None:
print("setUp must me set when create project")
comeBackBranchCurr()
return
if Git.getBranch() != StudyProjectEnv.master:
warnings.warn(f"Wtf tu fou quoi ici : '{branchCurr}' ? ")
sys.exit()
# Git.goToBranch(StudyProjectEnv.master)
(brName, v, tempCommit) = StudyProjectEnv.addProjectBranch(id)
df = " " * len(f"Project '{id}' ")
print(f"Project '{id}' (v{v}) : creating...")
proj = self(id)
proj.setUp = setUp
proj.v = v
if setUp:
print(df + ": setUp....")
setUp(proj)
print(df + ": ok")
StudyProjectEnv.saveProject(proj)
# print(tempCommit)
comeBackMaster(tempCommit)
comeBackBranchCurr()
return proj
# "project-"+Git.toBrancheName(id)
projectBranch = StudyProjectEnv.getProjectBranch(id, setUp, version)
# print("projectBranch",projectBranch)
if projectBranch is not None and Git.checkBranch(projectBranch):
tempCommit = Git.goToBranch(projectBranch, no_reset=False)
project = StudyProjectEnv.getProject(id, setUp)
# setUpMd5=Utils.Hash.function_md5(setUp)
if project is not None and project.setUp == "outdated":
if tempCommitMaster:
if len(Git.getModified()) > 0:
warnings.warn(
"project {id} outdated(setUp) in branch {projectBranch} but there are Modifed files"
)
sys.exit()
comeBackMaster(tempCommit)
return create_project()
if project is not None:
comeBackMaster(tempCommit)
comeBackBranchCurr()
print(f"Project '{id}' (v{project.v}) : loaded")
return project
comeBackMaster(tempCommit)
comeBackBranchCurr()
print(f"Project {id} not load !!!")
return
# load projectloaded")
# return self.proj[id]
return create_project()
def getOrCreateStudy(self, id, setUp=None, data=None):
if id in self.studies:
print(f"Study '{id}' : loaded")
return self.studies[id]
df = " " * len(f"Study '{id}' ")
print(f"Study '{id}' : creating...")
self.studies[id] = Study(id, data=data)
if setUp is not None:
print(df + ": setUp....")
setUp(self.studies[id])
print(df + ": ok")
__all__ = ["StudyProject", "Data"]
<file_sep>#!/bin/bash
#init
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit $1
}
function catch()
{
export ex_code=$?
(( $SAVED_OPT_E )) && set +e
return $ex_code
}
function throwErrors()
{
set -e
}
function ignoreErrors()
{
set +e
}
repeatstr(){
# $1=number of patterns to repeat
# $2=pattern
printf -v "TEMP" '%*s' "$1"
echo ${TEMP// /$2}
}
check_im_exist(){
docker image inspect "$1" >/dev/null 2>&1
return $?
}
install_im(){
tab=${2:-0}
tabS=$(repeatstr "$tab" "\t")
echo "${tabS}pulling... '$1'"
docker pull "$1" >/dev/null 2>&1
}
image_up_to_date(){
ref="${1:-library/ubuntu:latest}"
if ! grep -q "/" <<<"$ref"; then
ref="library/$ref"
fi
if ! grep -q ":" <<<"$ref"; then
ref="${ref}:latest"
fi
repo="${ref%:*}"
tag="${ref##*:}"
tag="${tag:-latest}"
if ! check_im_exist "$ref"; then
install_im "$ref" 1
echo -e "\timage '${ref}' is up-to-date"
exit 0
fi
acceptM="application/vnd.docker.distribution.manifest.v2+json"
acceptML="application/vnd.docker.distribution.manifest.list.v2+json"
token=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:${repo}:pull" \
| sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^"token"/ {print $2}' | tr -d '"')
rep=$(curl -H "Accept: ${acceptM}" \
-H "Accept: ${acceptML}" \
-H "Authorization: Bearer $token" \
-I -s "https://registry-1.docker.io/v2/${repo}/manifests/${tag}" | grep "Docker-Content-Digest" | sed "s/Docker-Content-Digest: //" | sed -nE "s/^.+:(.+)$/\1/p" | tr -d '\n' | tr -d '\r')
repoDigest=$(docker image inspect "${ref}" --format '{{index .RepoDigests 0}}' 2>/dev/null | sed -E "s/.+:(.+)$/\1/" | tr -d '\n' | tr -d '\r' )
if [[ "${rep}" != "${repoDigest}" ]]; then
install_im "$ref"
# exit 0
fi
echo -e "\timage '${ref}' is up-to-date"
}
check_docker_container(){
container="${1}"
lignes=$(docker ps -a --filter "name=^${container}$" | wc -l | tr -d ' ')
[[ "$lignes" == "1" ]]
return $?
}
findPort(){
p=${2}
np=${1}
while nc -z "0.0.0.0" "$np" &>/dev/null && [ $np -le $p ] ; do
np=$((np+1))
done
if [[ $np -eq $p ]];then
return 1
else
echo "${np}"
return 0
fi
}
stop_docker_container(){
docker stop "$1" &>/dev/null
}
remove_dir(){
if [[ -d "$1" ]]; then
d=$(du -s "$1" | tr '\t' ' ' | cut -d ' ' -f1)
if [[ "$d" != "0" ]]; then
read "STOREDVAR?The directory '$1' is not empty, are your sure to remove it ? (y/N) "
if [[ "$STOREDVAR" = "y" ]]; then
rm -rf "$1"
echo "'$1' directory removed"
fi
else
rm -rf "$1"
echo "'$1' directory removed"
fi
fi
}
# Report usage
usage() {
echo "Usage:"
echo "$(basename $0) [-d/--dirname NAME -h/--help -p/--port '8888' -pm/--port-max '8898' -h/--host '0.0.0.0'\
-w/--workdir 'work' -i/--image 'studyproject/[scipy-notebook,datascience-notebook]'] [--] NAME"
# Optionally exit with a status code
if [ -n "$1" ]; then
exit "$1"
fi
}
invalid() {
echo "ERROR: Unrecognized argument: $1" >&2
usage 1
}
open_in_browser(){
xdg-open "$1" &> /dev/null
if ! xdg-open "$1" &> /dev/null;then
if ! open "$1" &> /dev/null; then
start "$1" &> /dev/null
fi
fi
exit
}
parse_json_end(){
stringVar="$1"
open=$((0))
for ((i=1;i<=${#stringVar};i++)); do
var="${stringVar:$i-1:1}"
if [[ "$var" = "{" ]]; then
#statements
open=$((open + 1))
elif [[ "$var" = "[" ]]; then
#statements
open=$((open + 1))
elif [[ "$var" = "]" ]]; then
#statements
open=$((open - 1))
elif [[ "$var" = "}" ]]; then
#statements
open=$((open - 1))
fi
if [[ ("$open" = "0" || $open -eq 0) && "$i" == "1" ]]; then
echo ${stringVar}
return 0;
fi
if [[ "$open" = "0" || $open -eq 0 ]]; then
echo ${stringVar:0:$i}
return 0;
fi
done
return 1
}
getvaluejson(){
cut -d',' -f1 <<<"$1" | cut -d'}' -f1 | cut -d']' -f1
}
getlittle(){
if [[ -z "$2" ]]; then
return
fi
textToKeep="$1"
text="$2"
a=$(echo "$text" | sed -E "s|.*${textToKeep}:(.+)|\1|")
parse_json_end "$a"
}
find_container_addr(){
a=$(docker inspect "$1" --format '{{json .NetworkSettings.Ports}}' 2>/dev/null | tr -d '"' | sed -E "s/^.(.*).$/\1/")
a=$(getlittle "$PORT_NB/tcp" "$a")
if [[ "$a" = "null" ]]; then
return 0
fi
b=$(getlittle 'HostIp' "$a")
hostIp=$(getvaluejson "$b")
c=$(getlittle 'HostPort' "$a")
hostPort=$(getvaluejson "$c")
echo "http://$hostIp:$hostPort"
}
# Pre-process options to:
# - expand -xyz into -x -y -z
# - expand --longopt=arg into --longopt arg
ARGV=()
END_OF_OPT=
while [[ $# -gt 0 ]]; do
arg="$1"; shift
case "${END_OF_OPT}${arg}" in
--) ARGV+=("$arg"); END_OF_OPT=1 ;;
--*=*) ARGV+=("${arg%%=*}" "${arg#*=}") ;;
--*) ARGV+=("$arg") ;;
-*) for i in $(seq 2 ${#arg}); do cc=${arg:$i-1:1};ARGV+=("-${cc}"); done ;;
*) ARGV+=("$arg") ;;
esac
done
# # Apply pre-processed options
set -- "${ARGV[@]}"
# Parse options
END_OF_OPT=
POSITIONAL=()
while [[ $# -gt 0 ]]; do
case "${END_OF_OPT}${1}" in
-h|--help) usage 0 ;;
# -p|--password) shift; PASSWORD="$1" ;;
# -u|--username) shift; USERNAME="$1" ;;
--pm|--port-max) shift; PORT_MAX="$1" ;;
--p|-p|--port) shift; PORT="$1" ;;
-h|--host) shift; HOST="$1" ;;
--pn|--port-nb) shift; PORT_NB="$1" ;;
-w|--workdir) shift; WORKDIR="$1" ;;
--im|--image) shift; IMAGE="$1" ;;
-t|--token) shift; TOKEN="$1" ;;
-d|--dirname) shift; DIRNAME="$1" ;;
-r|--recreate) RECREATE="1" ;;
--rm|--remove) REMOVE="1" ;;
--open) OPEN="1" ;;
# -q|--quiet) QUIET=1 ;;
# -C|--copy) COPY=1 ;;
# -N|--notify) NOTIFY=1 ;;
# --stdin) READ_STDIN=1 ;;
--) END_OF_OPT=1 ;;
-*) invalid "$1" ;;
*) POSITIONAL+=("$1") ;;
esac
shift
done
# # Restore positional parameters
set -- "${POSITIONAL[@]}"
if [[ $# -ne 1 ]]; then
echo "name must be specified"
exit 1
fi
NAME="$1"
if [[ -z "$NAME" ]]; then
echo "name must be specified"
exit 1
fi
PORT_NB=${PORT_NB:-8888}
DIRNAME="${DIRNAME:-$NAME}"
IMAGE="${IMAGE:-studyproject/scipy-notebook}"
# add studyProject library
###################################
###################################
REMOVE="${REMOVE:-0}"
if [[ "$REMOVE" = "1" ]]; then
remove_dir "$DIRNAME"
echo "'$NAME' container stopping..."
stop_docker_container "$NAME"
exit 0
fi
PORT="${PORT:-8888}"
PORT_MAX=${PORT_MAX:-8898}
HOST="${HOST:-0.0.0.0}"
WORKDIR="${WORKDIR:-${PWD}/${DIRNAME}/work}"
TOKEN="${TOKEN:-<PASSWORD>}"
RECREATE="${RECREATE:-0}"
OPEN="${OPEN:-0}"
if [[ "$OPEN" = "1" ]]; then
if ! check_docker_container "$NAME"; then
if [[ "$RECREATE" = "0" ]]; then
portContainer=$(find_container_addr "$NAME")
if [[ -z "$portContainer" ]]; then
echo "PORT du container '$NAME' not found"
exit 1
fi
open_in_browser "$portContainer"
fi
fi
fi
if [[ -d "$WORKDIR" ]]; then
echo "directory already exist : '$WORKDIR'"
else
echo "create directory : '$WORKDIR'"
mkdir -p "$WORKDIR"
fi
# TODO function description
# @param TODO The first parameter
# @return
# echo "study-project : create structure\n\twork/ : source code"
# mkdir -p work
echo "check if image '$IMAGE' is up-to-date"
image_up_to_date "$IMAGE"
#check volume path absolute
#check docker container
if ! check_docker_container "$NAME"; then
echo "'${NAME}' container already exist"
if [[ "$RECREATE" = "1" ]]; then
echo "stop container '${NAME}' ..."
stop_docker_container "$NAME"
else
if [[ "$OPEN" = "1" ]]; then
portContainer=$(find_container_addr "$NAME")
if [[ -z "$portContainer" ]]; then
echo "PORT du container '$NAME' not found"
exit 1
fi
open_in_browser "$portContainer"
fi
exit 1
fi
fi
#check port open
a=$(findPort "$PORT" "$PORT_MAX")
if [[ -z "$a" ]]; then
echo "pas de port"
else
echo "port : $a"
PORT="$a"
fi
docker run --env DOCKER_CONTAINER_NAME="$NAME" --name "$NAME" --rm -d -p "$PORT":"$PORT_NB" -v "$WORKDIR:/home/study-project/work" "$IMAGE" start-notebook.sh --NotebookApp.token="$TOKEN" &> /dev/null
echo "Docker container started : '$NAME'"
echo "$NAME" > "$WORKDIR/.study-project-init"
if [[ "$OPEN" = "1" ]]; then
portContainer=$(find_container_addr "$NAME")
if [[ -z "$portContainer" ]]; then
echo "PORT du container '$NAME' not found"
exit 1
fi
open_in_browser "$portContainer"
fi
|
e03bf09aa981fed01ef266ec1a6d811baf176f59
|
[
"Markdown",
"Python",
"Shell"
] | 4 |
Python
|
studyproject-mlds/study-project
|
91b6a6172c8a710bb6d812bf138890b696bfd75b
|
218d2ff4617308e5e2bff155032a600891a79633
|
refs/heads/master
|
<file_sep>"""
SYNOPSIS
This will take the file named Distances1.csv, add create a json for the
nodes and edges that it finds.
AUTHOR
Programmer: <NAME> <<EMAIL>>
"""
import csv
import json
filename = 'Distances1.csv'
# Open csv file, add raw data to array
with open(filename, 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
data = []
for row in spamreader:
data.append(row)
# The two main components. Second one is a set to keep elements unique
Nodes = set([])
Edges = []
# for each row, add in nodes and weight associations
for row in data:
Nodes.add(row[0])
Nodes.add(row[1])
try:
curr = {"association": [row[0],row[1]], "weight":float(row[2])}
Edges.append(curr)
except:
print("mistake")
pass
# Construct overall dict object and write to the file
with open('SampleGraph2.json', 'w') as outfile:
json.dump({"nodes":sorted(Nodes), "edges":Edges}, outfile)<file_sep>
// AlternateRoutesDlg.h : header file
//
#pragma once
#include "afxcmn.h"
#include "afxwin.h"
#include "graph.h"
#define WM_MY_THREAD_MESSAGE WM_APP+100
// CAlternateRoutesDlg dialog
class CAlternateRoutesDlg : public CDialog
{
// Construction
public:
CAlternateRoutesDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ALTERNATEROUTES_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
CString algorithm_select;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CSpinButtonCtrl num_paths_spin;
CSpinButtonCtrl m_efficiency_spin;
Graph graph;
afx_msg void OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult);
CEdit m_num_paths_edit;
afx_msg void OnNMReleasedcaptureSlider1(NMHDR *pNMHDR, LRESULT *pResult);
CEdit m_efficiency_edit;
afx_msg void OnNMCustomdrawSlider1(NMHDR *pNMHDR, LRESULT *pResult);
CSliderCtrl m_efficiency_slider;
afx_msg void OnDeltaposSpin2(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedGraphupload();
afx_msg void OnEnChangeEdit1();
afx_msg void StatusUpdate(CString msg);
void OnBnClickedKshortest2();
CEdit m_status;
CTabCtrl m_ctrlTAB;
CButton m_go;
CButton m_heuristic;
CButton m_shortest;
CButton m_shortest_lap;
afx_msg void OnBnClickedHeuristic();
afx_msg void OnBnClickedKshortest1();
void disableInputs();
CButton m_abort;
afx_msg void OnBnClickedGo();
afx_msg void OnBnClickedAbort();
LRESULT OnThreadMessage(WPARAM wParam, LPARAM);
};
<file_sep>#include "stdafx.h"
#include "Graph.h"
#include "json.hpp"
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <climits>
using json = nlohmann::json;
using namespace std;
Graph::Graph() {
}
Graph::~Graph()
{
}
int Graph::getSize()
{
return this->vertexCount;
}
void Graph::addEdge(int a, int b, float weight)
{
if (a >= 0 && a < vertexCount && b >= 0 && b < vertexCount) {
adjacencyMatrix[a][b] = weight;
adjacencyMatrix[b][a] = weight;
}
}
// Get distance between two neighbors
float Graph::getDistance(string a, string b)
{
if (adjacencyMatrix[verticesHash[a]][verticesHash[b]] != -1.0) {
return adjacencyMatrix[verticesHash[a]][verticesHash[b]];
}
return NULL;
}
// Overloaded function in case we want the index of the string
float Graph::getDistance(int a, int b)
{
if (adjacencyMatrix[a][b] != -1.0) {
return adjacencyMatrix[a][b];
}
return NULL;
}
// See http://www.geeksforgeeks.org/greedy-algorithms-set-6-dijkstras-shortest-path-algorithm/
int Graph::minDistance(float dist[], bool sptSet[])
{
// Initialize min value
float min = FLT_MAX, min_index;
for (int v = 0; v < this->getSize(); v++){
if (sptSet[v] == false && dist[v] <= min) {
dist[v];
v;
min = dist[v], min_index = v;
}
}
return min_index;
}
// See http://www.geeksforgeeks.org/greedy-algorithms-set-6-dijkstras-shortest-path-algorithm/
void Graph::shortestPath(string src) {
// Dynamically sized array of floats or booleans
float* dist = NULL;
int n = this->getSize();
dist = new float[n];
bool* sptSet = NULL;
int p = this->getSize();
sptSet = new bool[p];
int V = this->getSize();
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < V; i++)
dist[i] = FLT_MAX, sptSet[i] = false;
// Distance of source vertex from itself is always 0
int index = this->verticesHash[src];
dist[index] = 0.0;
// Find shortest path for all vertices
for (int count = 0; count < V; count++)
{
// Pick the minimum distance vertex from the set of vertices not
// yet processed. u is always equal to src in first iteration.
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = true;
// Update dist value of the adjacent vertices of the picked vertex.
for (int v = 0; v < V; v++) {
// Update dist[v] only if is not in sptSet, there is an edge from
// u to v, and total weight of path from src to v through u is
// smaller than current value of dist[v]
float aye = this->getDistance(u, v);
if (!sptSet[v] && this->getDistance(u, v) && dist[u] != FLT_MAX
&& dist[u] + this->getDistance(u, v) < dist[v]){
dist[v] = dist[u] + this->getDistance(u, v);
}
}
}
// print the constructed distance array
printSolution(dist, V);
}
void Graph::printSolution(float dist[], int n)
{
ofstream log;
log.open("results.txt");
// Find the key based on the value
for (int i = 0; i < this->getSize(); i++) {
string key;
for (auto &j : this->verticesHash) {
if (j.second == i) {
key = j.first;
break;
}
}
log << key << " takes " << dist[i] << "meters\n";
}
log << "End Session \n\n";
log.close();
}<file_sep># AlternateRoutes
A .NET Application that calculates alternate routes.
# Introduction
I began my internship in Redlands, CA Summer 2017, where I carpooled to and from work each day.
The first few days, we used Google Maps in order to get home. We hoped we would memorize the
path home eventually. To our surprise, Google Maps put us on a different route home each day.
Based on this, we decided to make it our mission to take a different path home, for the duration of
the internship. I decided to write an algorithm that would give us different paths home and I
built an application to do it.
## Data set
I used [ArcGIS online](http://www.arcgis.com/home/webmap/viewer.html?webmap=b2cb612edf4b441584cff9f7c49133b0) to create a map that would eventually
turn into a graph structure.

I converted it to a graph and calculated the distance between each node:
 
The application uses .json as input (using a script) to create a representation of
an undirected graph as well as specify the starting and ending nodes. The syntax goes as follows:
```json
{
"starting" : "node1",
"ending" : "node5",
"nodes" : ["node1","node2","node3","node4","node5"],
"edges" : [
{
"association" : ["node1","node2"], "weight" : 1.0
},
{
"association" : ["node2","node3"], "weight" : 2.3
},
{
"association" : ["node3","node4"], "weight" : 1.8
},
{
"association" : ["node4","node5"], "weight" : 6.8
}]
}
```
## Execution
The MFC Visual C++ program prompts you to upload the .json file. Please see the sample data to get started.
After that, you can choose one of three algorithms using the designed user interface:

Based on your selection, additional input parameters may be required.
When done, a user can select "Go" in order to execute the algorithm. There is an option to halt execution
in case something goes awry.
# Algorithms
In this application, my solution is labelled as the Heuristic Algorithm. The other two are implementations of existing routing solutions that I could use to practice and compare results.
## Heuristic (In Progress)
I simply needed to find permutations of the Dijkstra's shortest path in order to come up with different paths
home. I realized I could simply take away certain edges until I have the number of paths I wanted.
I could queue up the edges and "dance" around them.
However, a simpler approach to my problem was to define a path efficiency threshold and then run a Depth First Search
on the graph. If a path reachs the ending node and it is within a specified path efficiency (relative
to the shortest path solution), then it is good enough to be included in the set.
Inputs:
- Number of paths desired
- Path efficiency
## k-Shortest Path problem (Pending)
Practice algorithm implementation by following David Eppstein's solution for finding the
[k-shortest path](https://en.wikipedia.org/wiki/K_shortest_path_routing).
## k-Shortest Path with Minimal Overlap (Pending)
One step further, apply the problem to finding the shortest path, but limiting the amount of overlap
between routes. Academic reference: [Alternative Routing: k-Shortest Paths with Limited Overlap](http://cs.au.dk/~bouros/docs/sigspatial15.pdf).<file_sep>
// AlternateRoutesDlg.cpp : implementation file
//
#include "stdafx.h"
#include "AlternateRoutes.h"
#include "AlternateRoutesDlg.h"
#include "afxdialogex.h"
#include <iostream>
#include <fstream>
#include <string>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
CWinThread* m_hThread;
HANDLE m_hKillEvent;
UINT HeuristicAnalysis(void*);
UINT ShortestPathLowOverlapAnalysis(void*);
UINT ShortestPathAnalysis(void*);
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CAlternateRoutesDlg dialog
CAlternateRoutesDlg::CAlternateRoutesDlg(CWnd* pParent /*=NULL*/)
: CDialog(IDD_ALTERNATEROUTES_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CAlternateRoutesDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT1, m_num_paths_edit);
DDX_Control(pDX, IDC_EDIT2, m_efficiency_edit);
DDX_Control(pDX, IDC_SLIDER1, m_efficiency_slider);
DDX_Control(pDX, IDC_EDIT4, m_status);
DDX_Control(pDX, IDC_GO, m_go);
DDX_Control(pDX, IDC_HEURISTIC, m_heuristic);
DDX_Control(pDX, IDC_KSHORTEST1, m_shortest);
DDX_Control(pDX, IDC_KSHORTEST2, m_shortest_lap);
DDX_Control(pDX, IDC_ABORT, m_abort);
}
BEGIN_MESSAGE_MAP(CAlternateRoutesDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_SLIDER1, &CAlternateRoutesDlg::OnNMReleasedcaptureSlider1)
ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER1, &CAlternateRoutesDlg::OnNMCustomdrawSlider1)
ON_EN_CHANGE(IDC_EDIT1, &CAlternateRoutesDlg::OnEnChangeEdit1)
ON_BN_CLICKED(IDC_KSHORTEST2, &CAlternateRoutesDlg::OnBnClickedKshortest2)
ON_BN_CLICKED(IDC_HEURISTIC, &CAlternateRoutesDlg::OnBnClickedHeuristic)
ON_BN_CLICKED(IDC_KSHORTEST1, &CAlternateRoutesDlg::OnBnClickedKshortest1)
ON_BN_CLICKED(IDC_GO, &CAlternateRoutesDlg::OnBnClickedGo)
ON_BN_CLICKED(IDC_ABORT, &CAlternateRoutesDlg::OnBnClickedAbort)
ON_MESSAGE(WM_MY_THREAD_MESSAGE, OnThreadMessage)
END_MESSAGE_MAP()
// CAlternateRoutesDlg message handlers
BOOL CAlternateRoutesDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// Slider Control
m_efficiency_slider.SetPos(85);
// Edit Control Settings
CFont *myFont = new CFont();
myFont->CreateFont(24, 0, 0, 0, FW_HEAVY, true, false,
0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
FIXED_PITCH | FF_MODERN, _T("Times New ROman"));
m_num_paths_edit.SetFont(myFont);
m_efficiency_edit.SetFont(myFont);
m_num_paths_edit.SetWindowTextW(_T("500"));
disableInputs();
MessageBox(_T("Welcome to Alternate Routes, please upload a graph to begin."), MB_OK);
CFileDialog dlgFile(TRUE);
CString fileName;
const int c_cMaxFiles = 100;
const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;
dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(c_cbBuffSize);
dlgFile.GetOFN().nMaxFile = c_cbBuffSize;
dlgFile.DoModal();
fileName.ReleaseBuffer();
CString a;
a.Format(_T("File '%s' uploaded successfully"), PathFindFileName(fileName));
StatusUpdate(a);
algorithm_select = "none";
json json_data;
std::ifstream graph_file(fileName, std::ifstream::binary);
graph_file >> json_data;
graph = Graph::Graph(json_data);
int size = graph.getSize();
graph.shortestPath(json_data["starting"]);
return TRUE; // return TRUE unless you set the focus to a control
}
void CAlternateRoutesDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CAlternateRoutesDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CAlternateRoutesDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CAlternateRoutesDlg::OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
}
void CAlternateRoutesDlg::OnNMReleasedcaptureSlider1(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: Add your control notification handler code here
*pResult = 0;
CString a;
a.Format(_T("Efficiency changed to %d%%"), m_efficiency_slider.GetPos());
}
void CAlternateRoutesDlg::OnNMCustomdrawSlider1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
CString a;
a.Format(_T("%d %%"), m_efficiency_slider.GetPos());
m_efficiency_edit.SetWindowTextW(a);
}
void CAlternateRoutesDlg::OnDeltaposSpin2(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
}
void CAlternateRoutesDlg::OnBnClickedGraphupload()
{
CFileDialog dlgFile(TRUE);
CString fileName;
const int c_cMaxFiles = 100;
const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;
dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(c_cbBuffSize);
dlgFile.GetOFN().nMaxFile = c_cbBuffSize;
dlgFile.DoModal();
fileName.ReleaseBuffer();
CString a;
a.Format(_T("File '%s' uploaded successfully"), PathFindFileName(fileName));
}
// TODO: Add your control notification handler code here
void CAlternateRoutesDlg::OnEnChangeEdit1()
{
CString sWindowText;
CString a;
m_num_paths_edit.GetWindowText(sWindowText);
a.Format(_T("Number of paths changed to %d"), _ttoi(sWindowText));
StatusUpdate(a);
}
void CAlternateRoutesDlg::StatusUpdate(CString msg)
{
m_status.SetWindowTextW(msg);
}
void CAlternateRoutesDlg::OnBnClickedHeuristic()
{
// Disable all inputs and enable the ones that are necessary for Heuristic
// Here we need the number of paths as well as the efficiency threshold (See HeuristicAnalysis)
disableInputs();
m_efficiency_slider.EnableWindow(TRUE);
m_efficiency_edit.EnableWindow(TRUE);
m_num_paths_edit.EnableWindow(TRUE);
m_go.EnableWindow(TRUE);
// Disable selected algorithm button and enable the other two if user changes their mind
m_heuristic.EnableWindow(FALSE);
m_shortest.EnableWindow(TRUE);
m_shortest_lap.EnableWindow(TRUE);
// Populate algorithm selection variable
algorithm_select = "heuristic";
StatusUpdate(_T("Selection: Heuristic Algorithm"));
}
void CAlternateRoutesDlg::OnBnClickedKshortest1()
{
// Disable all inputs and enable the ones that are necessary for k-ShortestPath algorithm
// Here we only need the number of paths desired (See ShortestPathAnalysis)
disableInputs();
m_num_paths_edit.EnableWindow(TRUE);
m_go.EnableWindow(TRUE);
// Disable selected algorithm button and enable the other two if user changes their mind
m_shortest.EnableWindow(FALSE);
m_heuristic.EnableWindow(TRUE);
m_shortest_lap.EnableWindow(TRUE);
// Populate algorithm selection variable
algorithm_select = "shortest";
StatusUpdate(_T("Selection: k-Shortest Path Algorithm"));
}
void CAlternateRoutesDlg::OnBnClickedKshortest2()
{
// Disable all inputs and enable the ones that are necessary for k-ShortestPath algorithm
// Here we only need the number of paths desired (See ShortestPathLowOverlapAnalysis)
disableInputs();
m_num_paths_edit.EnableWindow(TRUE);
m_go.EnableWindow(TRUE);
// Disable selected algorithm button and enable the other two if user changes their mind
m_shortest_lap.EnableWindow(FALSE);
m_heuristic.EnableWindow(TRUE);
m_shortest.EnableWindow(TRUE);
// Populate algorithm selection variable
algorithm_select = "shortest_lap";
StatusUpdate(_T("Selection: k-Shortest Path with Limited Overlap Algorithm"));
}
void CAlternateRoutesDlg::disableInputs()
{
m_efficiency_slider.EnableWindow(FALSE);
m_efficiency_edit.EnableWindow(FALSE);
m_num_paths_edit.EnableWindow(FALSE);
m_abort.EnableWindow(FALSE);
m_go.EnableWindow(FALSE);
}
void CAlternateRoutesDlg::OnBnClickedGo()
{
disableInputs();
m_abort.EnableWindow(TRUE);
m_heuristic.EnableWindow(FALSE);
m_shortest.EnableWindow(FALSE);
m_shortest_lap.EnableWindow(FALSE);
if (algorithm_select == "heuristic") {
m_hThread = AfxBeginThread(HeuristicAnalysis, this);
} else if (algorithm_select == "shortest") {
m_hThread = AfxBeginThread(ShortestPathAnalysis, this);
} else if (algorithm_select == "shortest_lap") {
m_hThread = AfxBeginThread(ShortestPathLowOverlapAnalysis, this);
}
else {
StatusUpdate(_T("Unexpected Error, try again"));
disableInputs();
m_heuristic.EnableWindow(TRUE);
m_shortest.EnableWindow(TRUE);
m_shortest_lap.EnableWindow(TRUE);
}
// TODO: Add your control notification handler code here
}
UINT HeuristicAnalysis(void *pParam)
{
CAlternateRoutesDlg* pThis = (CAlternateRoutesDlg*)pParam;
pThis->SendMessage(WM_MY_THREAD_MESSAGE, 0);
return 0;
}
UINT ShortestPathAnalysis(void *pParam)
{
CAlternateRoutesDlg* pThis = (CAlternateRoutesDlg*)pParam;
pThis->SendMessage(WM_MY_THREAD_MESSAGE, 1);
return 0;
}
UINT ShortestPathLowOverlapAnalysis(void *pParam)
{
CAlternateRoutesDlg* pThis = (CAlternateRoutesDlg*)pParam;
pThis->SendMessage(WM_MY_THREAD_MESSAGE, 2);
return 0;
}
void CAlternateRoutesDlg::OnBnClickedAbort()
{
StatusUpdate(_T("Please select an algorithm to restart"));
// Disable input parameters and enable the algorithm selection
// Effectively resets the program
disableInputs();
m_heuristic.EnableWindow(TRUE);
m_shortest.EnableWindow(TRUE);
m_shortest_lap.EnableWindow(TRUE);
// Wait till target thread responds, and exists
WaitForSingleObject(m_hThread->m_hThread, INFINITE);
// TODO: Add your control notification handler code here
}
LRESULT CAlternateRoutesDlg::OnThreadMessage(WPARAM wParam, LPARAM)
{
switch (wParam) {
case 0:
StatusUpdate(_T("aye"));
break;
case 1:
StatusUpdate(_T("shortest"));
break;
case 2:
StatusUpdate(_T("shortest lap"));
break;
default:
StatusUpdate(_T("no aye"));
break;
}
return 0;
}<file_sep>// main.cpp : implementation file
//
#include "stdafx.h"
#include "AlternateRoutes.h"
#include "main.h"
#include "afxdialogex.h"
// main dialog
IMPLEMENT_DYNAMIC(main, CDialogEx)
main::main(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_ALTERNATEROUTESMAIN, pParent)
{
}
main::~main()
{
}
void main::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT4, m_status);
DDX_Control(pDX, IDC_EDIT1, m_status2);
}
BEGIN_MESSAGE_MAP(main, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &main::OnBnClickedButton1)
END_MESSAGE_MAP()
// main message handlers
void main::OnBnClickedButton1()
{
m_status2.SetWindowTextW(_T("HI"));
// TODO: Add your control notification handler code here
}
<file_sep>#pragma once
#include "afxwin.h"
// main dialog
class main : public CDialogEx
{
DECLARE_DYNAMIC(main)
public:
main(CWnd* pParent = NULL); // standard constructor
virtual ~main();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ALTERNATEROUTESMAIN };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
void StatusUpdate(CString msg);
DECLARE_MESSAGE_MAP()
public:
CEdit m_status;
afx_msg void OnBnClickedButton1();
CEdit m_status2;
};
<file_sep>#pragma
#include "json.hpp"
#include <fstream>
#include <string>
#include <unordered_map>
using namespace std;
using json = nlohmann::json;
class Graph{
private:
float** adjacencyMatrix;
int vertexCount;
int edgesCount;
map<string, int> verticesHash;
public:
json data;
Graph(json data) : data(data) {
vertexCount = data["nodes"].size();
edgesCount = data["edges"].size();
adjacencyMatrix = new float*[vertexCount];
for (int i = 0; i < vertexCount; i++) {
if (!verticesHash[data["nodes"][i]]) {
verticesHash[data["nodes"][i]] = i;
} else {
}
}
for (int i = 0; i < vertexCount; i++) {
adjacencyMatrix[i] = new float[vertexCount];
for (int j = 0; j < vertexCount; j++)
adjacencyMatrix[i][j] = -1.0;
}
for (int i = 0; i < edgesCount; i++) {
int edge = verticesHash[data["edges"][i]["association"][0]];
int edge1 = verticesHash[data["edges"][i]["association"][1]];
this->addEdge(edge, edge1, data["edges"][i]["weight"]);
}
};
Graph();
~Graph();
int getSize();
void addEdge(int a, int b, float weight);
float getDistance(string a, string b);
float getDistance(int a, int b);
int minDistance(float dist[], bool sptSet[]);
void shortestPath(string src);
void printSolution(float dist[], int n);
};
|
19f9d4133a9c1519cb2e9e78edaab6e0bfdfe0b7
|
[
"Markdown",
"Python",
"C++"
] | 8 |
Python
|
tchangalov/AlternateRoutes
|
325936c3449409a853b8256601708cdb6724b0a6
|
2177a233b59ff50e2f4a908d229c128c7a14ab16
|
refs/heads/main
|
<file_sep>from manim import*
import math
class Spiral(MovingCameraScene):
def construct(self):
pp = PolarPlane(
azimuth_units="PI radians",
size=60,
radius_max=30,
azimuth_label_scale=0.7,
radius_config={"number_scale_value": 0.7},
)
self.add(pp)
self.camera.frame.set(width=30)
def prime(n):
if n == 1:
return False
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
max_divisor = math.floor(math.sqrt(n))
for d in range(3, 1 + max_divisor, 2):
if n % d == 0:
return False
return True
for n in range(1, 50):
pdot = Dot(pp.polar_to_point(n, prime(n)),radius=1)
pdot.set_color(YELLOW_C)
self.add(pdot)
<file_sep># Puzzle-Animation
**Math Physics, Coding animation [channel](https://www.youtube.com/channel/UC1zAcjvBEewJIZHZCE5eCOw)**
**this repo contain source code for videos in [my channel](https://www.youtube.com/channel/UC1zAcjvBEewJIZHZCE5eCOw)**
# Manim
to render file on this repository you have to download [manim](https://github.com/3b1b/manim)(Python libary create by <NAME>)
if you already download, run the following command
> manim file_name.py class_name -p/-ql
*-p for 1080p and -ql for 480p*
# Example
Number Spiral: ((p,p)in polar coordiate, p for every positive integer)

<file_sep>from chanim import *
class ChanimScene(Scene):
def construct(self):
## ChemWithName creates a chemical diagram with a name label
grid = NumberPlane()
t0 = Text("there are many type of C3H6O")
t = Text("How many type of C3H6O that non-reactive with Na metal ").scale(0.7)
t1 = Text("Answer").scale(0.7).to_edge(UP)
chem = ChemWithName("H-c(-[2]H)(-[6]H)-c(=[2]O)-c(-[2]H)(-H)(-[6]H)", "C3H6O")
chem2 = ChemWithName("H_3C-[7]CH_2-[1]C(=[2]O)-[7]H","C3H6O\npropane")
chem3 = ChemWithName("H_3C-[1]C(=[2]O)-[7]CH_3","C3H6O\nacetone")
chem4 = ChemWithName("H_2C=CH-[7]CH_2-[1]O-H","C3H6O\n2-propen-1-ol")
x1 = Tex("C3H6O")
x2 = Tex("C=C").shift(2*LEFT)
x3 = Tex("C=O").shift(2*RIGHT)
x4 = Tex("Ether").shift(2*LEFT)
x5 = Tex("Alcohol").shift(5*LEFT)
x6 = Tex("Aldehyde").shift(2*RIGHT)
x7 = Tex("Ketone").shift(5*RIGHT)
a1 = Arrow([-2,1.5,0],x4)
a2 = Arrow([-2,1.5,0],x5)
a3 = Arrow([2,1.5,0],x6)
a4 = Arrow([2,1.5,0],x7)
a = VGroup(a1,a2,a3,a4)
c = Cross(x5,stroke_color=RED,stroke_width=7)
self.play(Write(t0))
self.wait(2)
self.play(FadeOut(t0))
self.play(chem.creation_anim())
self.wait()
self.play(Transform(chem,chem2))
self.wait()
self.play(Transform(chem,chem3))
self.wait()
self.play(Transform(chem,chem4))
self.wait()
self.wait()
self.clear()
#self.add(grid)
self.play(FadeInFromLarge(t))
self.wait(5)
self.play(t.animate.shift(2.8*UP))
self.play(Transform(t,t1))
self.play(FadeOut(t))
self.play(Write(x1))
self.play(TransformFromCopy (x1,x2),TransformFromCopy (x1,x3))
self.play(FadeOut(x1))
self.play(x2.animate.shift(2*UP),x3.animate.shift(2*UP))
self.play(Write(a))
self.play(Write(x4),Write(x5),Write(x6),Write(x7),run_time=4)
self.play(Indicate(x5))
self.play(Indicate(x4))
self.wait(2)
self.play(Indicate(x6))
self.play(Indicate(x7))
self.wait()
self.play(FocusOn(x5))
self.wait(3)
self.play(Create(c))
self.wait(3)<file_sep>from manim import *
import numpy as np
import hashlib
##### Intro #####
class Introduction_to_lorenzAttractor(Scene):
def construct(self):
tex = Tex("Lorenz Attractor","(Butterfly effect)").shift(3.4*UP).scale(0.8)
tex2 = Tex("Lorenz Attractor is a set of"," ordinary differential equation").scale(0.8).next_to(tex,DOWN)
math = MathTex(r"\frac{\mathrm{d} x}{\mathrm{d} t}=\sigma (y-x)")
math2 = MathTex(r"\frac{\mathrm{d} y}{\mathrm{d} t}=x (\rho -z)-y").next_to(math,DOWN)
math3 = MathTex(r"\frac{\mathrm{d} z}{\mathrm{d} t}=xy-\beta z").next_to(math2,DOWN)
mat = VGroup(math,math2,math3).scale(0.9).shift(0.7*UP)
box = SurroundingRectangle(mat)
matbox = VGroup(math,math2,math3,box)
self.wait()
self.play(Write(tex))
self.play(tex[1].animate.set_color(BLUE))
self.play(Write(tex2))
self.play(Write(math),Write(math2),Write(math3),Create(box),run_time=2)
self.play(ShowPassingFlashAround(tex2[1]),rate_func=rate_functions.ease_in_out_expo,run_time=2)
self.wait()
self.play(FadeOut(tex[0]),FadeOut(tex2),FadeOut(matbox))
self.play(tex[1].animate.shift(1.5*LEFT))
self.play(tex[1].animate.scale(1.5))
sha = Text('SHA256').next_to(tex[1],DOWN).scale(0.8)
self.play(FadeInFromLarge(sha))
myMsg = "11111"
myMsg2 = "01111"
myMsgEncoded = myMsg.encode()
print(f"Original message: {myMsg}")
m = hashlib.sha256(myMsgEncoded)
msgHash = m.hexdigest()
msgHash = msgHash[:16]+'\n'+msgHash[16:]
msgHash = msgHash[:32]+'\n'+msgHash[32:]
msgHash = msgHash[:48]+'\n'+msgHash[48:]
print(f"Message hash: {msgHash}")
string = f"{msgHash}"
myMsg2Encoded = myMsg2.encode()
print(f"Original message: {myMsg2}")
m = hashlib.sha256(myMsg2Encoded)
msg2Hash = m.hexdigest()
msg2Hash = msg2Hash[:16]+'\n'+msg2Hash[16:]
msg2Hash = msg2Hash[:32]+'\n'+msg2Hash[32:]
msg2Hash = msg2Hash[:48]+'\n'+msg2Hash[48:]
print(f"Message hash: {msg2Hash}")
string2 = f"{msg2Hash}"
hash_string = Text(string).scale(0.5).shift(3*RIGHT)
box2 = SurroundingRectangle(hash_string,color=YELLOW, buff=0.25)
hexdi = VGroup(hash_string,box2)
hash_string2 = Text(string2).scale(0.5).shift(3*RIGHT)
box22 = SurroundingRectangle(hash_string2,color=YELLOW, buff=0.25)
hexdi2 = VGroup(hash_string2,box22)
inp = Text(f"SHA({myMsg})").scale(0.5).shift(2*LEFT)
inp2 = Text(f"SHA({myMsg2})").scale(0.5).shift(2*LEFT)
arrow = Arrow(inp, [1,0,0])
hashtext = Text("hash").scale(0.3)
hashtext.next_to(arrow,0.5*UP)
self.play(Write(inp))
self.play(Write(hexdi),GrowArrow(arrow),Write(hashtext))
self.wait(2)
self.play(Transform(inp,inp2))
self.play(FocusOn(inp2))
self.play(Transform(hexdi,hexdi2))
br = Brace(box2, sharpness=1.0)
change = br.get_text('output completely change').scale(0.8)
self.play(FadeIn(br))
self.play(Write(change))
self.wait(2)
self.clear()
self.wait()
##########################################################################################################################
class Lorenz_Attractor(ThreeDScene):
def construct(self):
dot = Sphere(radius=0.001,fill_color=BLUE,fill_opacity=0).move_to(0*RIGHT + 0.1*UP + 0.105*OUT)
self.set_camera_orientation(phi=65 * DEGREES,theta=30*DEGREES)
self.begin_ambient_camera_rotation(rate=0.01) #Start move camera
dtime = 0.005
numsteps = 30
self.add(dot)
def lorenz(x, y, z, s=10, r=28, b=2.667):
x_dot = s*(y - x)
y_dot = r*x - y - x*z
z_dot = x*y - b*z
return x_dot, y_dot, z_dot
def update_trajectory(self, dt):
new_point = dot.get_center()
if np.linalg.norm(new_point - self.points[-1]) > 0.01:
self.add_smooth_curve_to(new_point)
traj = VMobject()
traj.start_new_path(dot.get_center())
traj.set_stroke(BLUE, 1.5, opacity=0.8)
traj.add_updater(update_trajectory)
self.add(traj)
def update_position(self,dt):
x_dot, y_dot, z_dot = lorenz(dot.get_center()[0]*10, dot.get_center()[1]*10, dot.get_center()[2]*10)
x = x_dot * dt/10
y = y_dot * dt/10
z = z_dot * dt/10
self.shift(x/10*RIGHT + y/10*UP + z/10*OUT)
dot.add_updater(update_position)
self.wait(420)
|
d5b834b0fffb5c99ba0737cc23690c68100cafa0
|
[
"Markdown",
"Python"
] | 4 |
Python
|
thanniti/Puzzle-Animation
|
67154ad2bba2da5b564e347e9bd1dc2e90cfa06d
|
2db658f7cb904eb2598601f9e06e5460bc396c80
|
refs/heads/master
|
<file_sep>Simple Python Script which uses smtplib to send plaintext emails.
How to Use:
Change Email Accordingly and enter password as input.
<file_sep>import smtplib, ssl
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender= "<EMAIL>"
receiver = "<EMAIL>"
password = input("Type your password and press enter: ")
message = """\
Subject: Subject CHM101A
Bura na maano Holi hai
'Fraud na maaro' PClub ki boli hai
~~~~python here don't mind hissss~~~~
"""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, receiver, message)
|
cd30d06123bb41326e5d27cac1ef54607b87f8b3
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
ankurbanga/Email-through-Python
|
66ab02f229a7b8a7c4f8caa0a9bebd86eda904ec
|
d7c7a2938ca8c5a3ae86352c6b8edb6a98232f83
|
refs/heads/main
|
<file_sep>const gorjeta = function () {
if (this.valor < 50) {
return (this.gorjeta = this.valor * (20 / 100));
} else if (this.valor > 50 && this.valor < 200) {
return (this.gorjeta = this.valor * (15 / 100));
} else if (this.valor > 200) {
return (this.gorjeta = this.valor * (10 / 100));
}
};
const exibirTotal = function () {
return (this.toString = `Restaurante ${this.nome} [Valor: R$${
this.valor
} | Gorjeta: R$ ${this.gorjeta}| Total: R$ ${this.gorjeta + this.valor} ]`);
};
let rest = prompt("Quantos restaurantes são?");
let restaurantes = new Array(rest);
for (let r = 0; r <= rest - 1; r++) {
restaurantes[r] = {
nome: prompt("nome do restaurante"),
valor: parseInt(prompt("valor da conta")),
gorjeta: gorjeta,
toString: exibirTotal,
};
restaurantes[r].gorjeta();
restaurantes[r].toString();
}
restaurantes.imprimir = function () {
maior = 0
gastos = new Array(restaurantes.length);
console.log(`Restaurantes visitados no feriado ${restaurantes.length}
Lista de restaurantes:`);
for (let i=0; i<restaurantes.length;i++) {
console.log(`${restaurantes[i].toString}`);
gastos[i] = (restaurantes[i].gorjeta + restaurantes[i].valor);
if(gastos[i]>maior){
maior = gastos[i];
resta = restaurantes[i]
}
}
tudo = 0;
for(const gast of gastos){
tudo += gast;
}
console.log(`Total de gastos: R$ ${tudo}
Média de gastos: R$ ${ tudo/ restaurantes.length}
Restaurante com maior gasto total:
${resta.toString}`);
};
restaurantes.imprimir();
|
9217961dd198a39ac8478b1eb11f6b90d04be709
|
[
"JavaScript"
] | 1 |
JavaScript
|
trallerd/atvd5-bonus-JavaScript
|
01da9415c50ece5fc31ae25dc2123ee8ff242abb
|
22f28132c3e6f48ed4c581fcdb4ce25ed214e6b6
|
refs/heads/master
|
<file_sep>package pl.siepsiak.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@NotEmpty
private String name;
@NotNull
private Float price;
public Product() {
}
public Product(@NotNull @NotEmpty String name, @NotNull @NotEmpty Float price) {
this.name = name;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
<file_sep>package pl.siepsiak.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.siepsiak.model.Product;
public interface ProductRepository extends JpaRepository<Product, Long> {
boolean existsById(Long id);
}
<file_sep>package pl.siepsiak.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pl.siepsiak.model.Product;
import pl.siepsiak.services.ProductService;
import java.util.List;
import java.util.NoSuchElementException;
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/products")
public ResponseEntity<List<Product>> getProducts() {
List<Product> products = productService.listAll();
if (products.isEmpty()) {
return new ResponseEntity<>(products,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(products, HttpStatus.OK);
}
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
try {
Product product = productService.get(id);
return ResponseEntity.ok(product);
} catch (NoSuchElementException e) {
return ResponseEntity.notFound().build();
}
}
@PostMapping(path = "/products", consumes = "application/json", produces = "application/json")
public void addProduct(@RequestBody Product product) {
productService.save(product);
}
@PutMapping(path = "/products/{id}", consumes = "application/json", produces = "application/json")
public ResponseEntity<Product> updateProduct(@RequestBody Product product,
@PathVariable Long id) {
try {
Product currentProduct = productService.get(id);
if (product.getName().isEmpty()) {
currentProduct.setName(currentProduct.getName());
} else {
currentProduct.setName(product.getName());
}
if (product.getPrice() == null) {
currentProduct.setPrice(currentProduct.getPrice());
} else {
currentProduct.setPrice(product.getPrice());
}
productService.save(currentProduct);
return ResponseEntity.ok(currentProduct);
} catch (NoSuchElementException e) {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/products/{id}")
public ResponseEntity<Product> delete(@PathVariable Long id) {
try {
productService.deleteById(id);
return new ResponseEntity<>(HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
<file_sep># springSerwer
Rest API sharing all CRUD operation.
It was using for mobile CRUD apps.
|
b41c4a9c0858fab6ea8d75bd4b2a1f8019a48467
|
[
"Markdown",
"Java"
] | 4 |
Java
|
lukaszSiepsiak/springSerwer
|
5935ba5ece3b41c72d3b909b37e1b51783f638e9
|
0f3ec8837f97bbadbd3de250f3f1ef75379db8c4
|
refs/heads/master
|
<file_sep>import os
import csv
csvpath = os.path.join("raw_data", "budget_data_1.csv")
date_ori = 0
rev = 0
total_diff = 0
diff_new =[]
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
next(csvreader)
new_reader = list(csvreader)
for i, j in enumerate(new_reader):
date_ori = date_ori + 1
rev = rev + int(j[1])
print("Total Month is: "+ str(date_ori))
print("Total Revenue is: " + str(rev))
for i, j in enumerate(new_reader):
if i+1 < date_ori:
diff = int(new_reader[i+1][1]) - int(new_reader[i][1])
total_diff = total_diff + diff
avg_diff = round(total_diff/date_ori,2)
diff = int(new_reader[i+1][1]) - int(new_reader[i][1])
diff_new.append(diff)
print("Average Revenue Change is: " + str(avg_diff))
#print(diff_new)
diff_abs =[]
for i in diff_new:
diff_abs.append(abs(i))
x_1 = min(diff_abs)
x_2 = diff_abs.index(x_1)
y_1 = max(diff_abs)
y_2 = diff_abs.index(y_1)
print("Greatest Decrese in Revenue:" + str(new_reader[x_2 + 1][0]) +
", $"+ str(diff_new[x_2]))
print("Greatest Increase in Revenue:" + str(new_reader[y_2 + 1][0]) +
", $"+ str(diff_new[y_2]))
####################################
with open("Pybank_output.txt", "w") as output:
output.write("Total Month is: "+ str(date_ori) + "\n")
output.write("Total Revenue is: " + str(rev) + "\n")
output.write("Average Revenue Change is: " + str(avg_diff) + "\n")
output.write("Greatest Decrese in Revenue:" + str(new_reader[x_2 + 1][0]) +
", $"+ str(diff_new[x_2]) + "\n")
output.write ("Greatest Increase in Revenue:" + str(new_reader[y_2 + 1][0]) +
", $"+ str(diff_new[y_2]))
<file_sep>import os
import csv
csvpath = os.path.join("raw_data", "budget_data_1.csv")
date_ori = 0
rev = 0
total_diff = 0
diff_new =[]
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
new_reader = list(csvreader)
for i, j in enumerate(new_reader):
date_ori = date_ori + 1
rev = rev + int(j[1])
print("Total Month is: "+ str(date_ori))
print("Total Revenue is: " + str(rev))
for i, j in enumerate(new_reader):
if i+1 < date_ori:
diff = int(new_reader[i+1][1]) - int(new_reader[i][1])
diff_new.append(diff)
print(diff_new)
#diff_2 = int(new_reader[i+2][1]) - int(new_reader[i+1][1])
'''if abs(diff_2) > abs(diff_1):
print(diff_2)
else:
print(diff_1)'''
<file_sep>import os
import csv
count_row = 0
#candidateList = []
candidate_votes_dict = {}
csvpath = os.path.join("raw_data", "election_data_1.csv")
with open(csvpath, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
next(csvreader)
for voteid, county, candidate in csvreader:
count_row += 1
#count_row = count_row + 1
#if m not in candidateList:
#candidateList.append(m)
#print(candidateList)
#print("Total votes: " + str(count_row))
if candidate not in candidate_votes_dict.keys():
candidate_votes_dict[candidate] = 1
else:
candidate_votes_dict[candidate] +=1
print("Total votes: " + str(count_row))
print("-------------------------------")
for i, j in candidate_votes_dict.items():
vote_percent = (j/count_row)*100
print(i + ": " + str(j) + " " + str(vote_percent) + "%")
#######################
'''with open("Pypoll_output.txt", "w") as output:
output.write("Total votes: " + str(count_row) + "\n")
output.write("-------------------------------" + "\n")
output.write(i + ": " + str(j) + " " + str(vote_percent) + "%" + "\n")
output.write("-------------------------------" + "\n")
output.write ("Winner: " + max(candidate_votes_dict))'''
|
7bf4759b9f3f26c0be282cc6564fae50414bc45d
|
[
"Python"
] | 3 |
Python
|
jiali0821/python-challenge
|
1f8b80fade4ce92f6b46ea4ff70bacf7273e415f
|
7a5af5435f214c689504cc89fe24514ac5069b7c
|
refs/heads/master
|
<repo_name>zheng-sun/scrapy<file_sep>/scrapytest/scrapytest/spiders/jingdong.py
# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from selenium import webdriver
class JingdongSpider(Spider):
name = 'jingdong'
def __init__(self):
self.browser = webdriver.Chrome("E:\\PythonCode\\scrapy\\chromedriver_73.exe")
self.browser.set_page_load_timeout(30)
# chrome_options = Options()
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--disable-gpu')
# driver = webdriver.Chrome(executable_path='./chromedriver', chrome_options=chrome_options)
# driver.get("https://www.baidu.com")
# print(driver.page_source)
# driver.close()
def closed(self,spider):
print("spider closed")
self.browser.close()
def start_requests(self):
start_urls = ['http://list.suning.com/0-20006-0.html']
for url in start_urls:
yield Request(url=url, callback=self.parse)
def parse(self, response):
#selector = response.xpath('//ul[@class="gl-warp clearfix"]/li')
selector = response.xpath('//ul[@class="general clearfix"]/li')
print(len(selector))
print('---------------------------------------------------')
<file_sep>/douban/douban/spiders/douban_spider.py
# -*- coding: utf-8 -*-
import scrapy
class DoubanSpiderSpider(scrapy.Spider):
#爬虫名称
name = 'douban_spider'
#允许的域名
allowed_domains = ['movie.douban.com']
#入口url,扔到调度器里面
start_urls = ['https://movie.douban.com/top250']
def parse(self, response):
print (response.text)
<file_sep>/douban/douban/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
import pymysql
import pymysql.cursors
class DoubanPipeline(object):
def __init__(self):
# 连接数据库
self.connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='douban',
user='root',
passwd='<PASSWORD>',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
self.cursor = self.connect.cursor()
def process_item(self, item, spider):
sql = """insert into list(serial_number,title,rating_num,comment,`desc`) values (%s, %s, %s, %s, %s)"""
self.cursor.execute(sql, (item['serial_number'], item['title'], item['rating_num'], item['comment'], item['desc'],))
self.connect.commit()
return item
<file_sep>/mofcom/begin.py
import multiprocessing
#import threading
#import os
from scrapy import cmdline
#from concurrent.futures import ThreadPoolExecutor
def action(number):
print('start price_list crawl', str(number))
cmdline.execute('scrapy crawl price_list'.split())
if __name__ == '__main__':
with multiprocessing.Pool(processes=4) as pool:
# 使用线程执行map计算
# 后面元组有3个元素,因此程序启动3条进程来执行action函数
results = pool.map(action, (1, 2, 3))
print('--------------')
# from scrapy.crawler import CrawlerProcess
# from mofcom.spiders.list import ListSpider as price_list_spider
# from mofcom.spiders.product_screen import ProductScreenSpider as product_screen_spider
# from scrapy.utils.project import get_project_settings
#
# def start_spider():
# try:
# process = CrawlerProcess(get_project_settings())
# process.crawl(price_list_spider)
# process.crawl(price_list_spider)
# process.crawl(price_list_spider)
# process.crawl(price_list_spider)
# process.start()
# except Exception as e:
# print('---出现错误---', e)
#
# if __name__ == '__main__':
# start_spider()
<file_sep>/mofcom/mysqlTest3.py
import pymysql
import pymysql.cursors
from DBUtils.PooledDB import PooledDB
import threading
import time
class DB:
__pool = None
def __init__(self):
# 连接数据库
self._conn = DB.db_connect().connection()
self._cursor = self._conn.cursor(cursor=pymysql.cursors.DictCursor)
# 连接数据库
@staticmethod
def db_connect():
if DB.__pool is None:
DB.__pool = PooledDB(creator=pymysql,
maxconnections=10,
mincached=10,
maxcached=10,
blocking=True,
host='127.0.0.1',
port=3306,
user='root',
passwd='<PASSWORD>',
db='kaola',
charset='utf8')
return DB.__pool
def getSql1(self):
print('查询getSql1')
sql = """select * from good_comment"""
self._cursor.execute(sql, )
self._conn.commit()
def getSql2(self):
print('查询getSql2')
sql = """select commentContent from good_comment"""
self._cursor.execute(sql, )
self._conn.commit()
def task1():
while True:
print('运行task1')
DB().getSql1()
time.sleep(1)
def task2():
while True:
print('运行task2')
DB().getSql2()
time.sleep(3)
# 创建并启动第一个线程
t1 =threading.Thread(target=task1)
t1.start()
# 创建并启动第二个线程
t2 =threading.Thread(target=task2)
t2.start()
print('主线程执行完成!')
<file_sep>/douban/douban/spiders/douban_top_250_spider.py
# -*- coding: utf-8 -*-
import scrapy
class DoubanTop250SpiderSpider(scrapy.Spider):
name = 'douban_top_250_spider'
allowed_domains = ['movie.douban.com']
start_urls = ['https://movie.douban.com/top250']
def parse(self, response):
#response.css
for item in response.css('.item'):
yield {
'serial_number': item.css('em::text').extract_first(),
'title': item.css('.title::text').extract_first(),
'rating_num': item.css('.rating_num::text').extract_first(),
'comment': response.css('.star span::text')[3].extract(),
'desc': item.css('.inq::text').extract_first(),
}
next_page = response.css('span.next a::attr(href)').extract_first()
print(next_page)
if next_page is not None:
print(response.urljoin(next_page))
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
<file_sep>/mofcom/mofcom/spiders/product_screen.py
# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from selenium import webdriver
import mofcom.items
class ProductScreenSpider(Spider):
name = 'product_screen'
#allowed_domains = ['nc.mofcom.gov.cn']
#start_urls = ['']
def __init__(self, name=None, **kwargs):
kwargs.pop('_job')
super(ProductScreenSpider, self).__init__(name, **kwargs)
#chrome_options = Options()
#chrome_options.add_argument('--headless')
#chrome_options.add_argument('--disable-gpu')
#self.browser = webdriver.Chrome(executable_path='E:\\PythonCode\\scrapy\\chromedriver_73.exe"')
#self.browser = webdriver.Chrome("D:\\PythonCode\\scrapy\\chromedriver_74.exe")
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
self.browser = webdriver.Chrome(executable_path='D:\\PythonCode\\scrapy\\chromedriver_74.exe', chrome_options=chrome_options)
self.browser.set_page_load_timeout(120)
def closed(self, spider):
print("spider closed")
self.browser.close()
# 截取请求地址获取参数
def getParam(self, url, file):
url_split = url.split('?')
para = {}
if len(url_split) > 1:
params = url_split[1].split('&')
for param in params:
p = param.split('=')
para[p[0]] = p[1]
if file in para:
return para[file]
return ''
def start_requests(self):
start_urls = ['http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml']
for url in start_urls:
yield Request(url=url, callback=self.parse)
def parse(self, response):
# 获取产品
par_craft_index_select = response.xpath('//select[@id="par_craft_index"]/option')
for par_craft_index_option in par_craft_index_select:
category_id = par_craft_index_option.xpath('@value').extract_first()
name = par_craft_index_option.xpath('text()').extract_first()
if category_id is not '':
CategoryItem = mofcom.items.CategoryItem()
CategoryItem['category_id'] = category_id
CategoryItem['name'] = name
yield CategoryItem
# 循环抓取下级农产品分类
next_page = "http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=" + str(category_id)
yield Request(url=next_page, callback=self.craft_index_parse)
# 获取区域
par_p_index_select = response.xpath('//select[@id="par_p_index"]/option')
for par_p_index_option in par_p_index_select:
region_id = par_p_index_option.xpath('@value').extract_first()
name = par_p_index_option.xpath('text()').extract_first()
if region_id is not '':
RegionItem = mofcom.items.RegionItem()
RegionItem['region_id'] = region_id
RegionItem['name'] = name
yield RegionItem
# 获取区域下的市场
next_page = "http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=" + str(region_id)
yield Request(url=next_page, callback=self.p_index_parse)
# 获取市场信息
def p_index_parse(self, response):
# url 截取出参数
region_id = self.getParam(response.url, 'par_p_index')
# 获取下级市场
p_index_select = response.xpath('//select[@id="p_index"]/option')
for p_index_option in p_index_select:
market_id = p_index_option.xpath('@value').extract_first()
name = p_index_option.xpath('text()').extract_first()
if market_id is not '':
MarkerItem = mofcom.items.MarkerItem()
MarkerItem['market_id'] = market_id
MarkerItem['name'] = name
MarkerItem['region_id'] = region_id
yield MarkerItem
# 获取产品信息
def craft_index_parse(self, response):
# url 截取出参数
category_id = self.getParam(response.url, 'par_craft_index')
# 获取下级产品
craft_index_select = response.xpath('//select[@id="craft_index"]/option')
for craft_index_option in craft_index_select:
product_id = craft_index_option.xpath('@value').extract_first()
name = craft_index_option.xpath('text()').extract_first()
if product_id is not '':
ProductItem = mofcom.items.ProductItem()
ProductItem['product_id'] = product_id
ProductItem['name'] = name
ProductItem['category_id'] = category_id
yield ProductItem
<file_sep>/mofcom/mysqlTest2.py
import pymysql
import pymysql.cursors
from DBUtils.PooledDB import PooledDB
import threading
class DB:
def __init__(self):
self.connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='<PASSWORD>',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
self.cursor = self.connect.cursor()
def getSql1(self):
print('查询getSql1')
sql = """select * from good_comment"""
self.cursor.execute(sql, )
self.connect.commit()
def getSql2(self):
print('查询getSql2')
sql = """select commentContent from good_comment"""
self.cursor.execute(sql, )
self.connect.commit()
def task1():
while True:
print('运行task1')
DB().getSql1()
def task2():
while True:
print('运行task2')
DB().getSql2()
# 创建并启动第一个线程
t1 =threading.Thread(target=task1)
t1.start()
# 创建并启动第二个线程
t2 =threading.Thread(target=task2)
t2.start()
print('主线程执行完成!')
<file_sep>/mofcom/mofcom/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
# 分类
class CategoryItem(scrapy.Item):
category_id = scrapy.Field()
name = scrapy.Field()
# 产品
class ProductItem(scrapy.Item):
product_id = scrapy.Field()
category_id = scrapy.Field()
name = scrapy.Field()
# 区域
class RegionItem(scrapy.Item):
region_id = scrapy.Field()
name = scrapy.Field()
# 市场
class MarkerItem(scrapy.Item):
market_id = scrapy.Field()
region_id = scrapy.Field()
name = scrapy.Field()
# 商品价格历史
class ProductPriceHistoryItem(scrapy.Item):
date = scrapy.Field()
product = scrapy.Field()
price = scrapy.Field()
unit = scrapy.Field()
market = scrapy.Field()
region_id = scrapy.Field()
class ReptileUrlItem(scrapy.Item):
spider_name = scrapy.Field()
url = scrapy.Field()
code = scrapy.Field()
<file_sep>/kaola/kaola/spiders/good_comment.py
# -*- coding: utf-8 -*-
import scrapy
import pymysql
import pymysql.cursors
import kaola.items
import json
class GoodCommentSpider(scrapy.Spider):
name = 'good_comment'
allowed_domains = ['search.kaola.com', 'goods.kaola.com']
def __init__(self):
# 连接数据库
self.connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
self.cursor = self.connect.cursor()
def updateUrlLogStatus(self, url):
sql = """
update url_log set `status` = 1 where `url` = %s
"""
self.cursor.execute(sql, (url))
self.connect.commit()
def start_requests(self):
while True:
urls = self.getUrl()
for url in urls:
yield scrapy.Request(url, callback=self.parse)
def getUrl(self):
# 获取category 爬取地址
sql = """select url from url_log where type = 'good_comment' and status = 0 limit 10"""
self.cursor.execute(sql)
data = self.cursor.fetchall()
return_data = []
for d in data:
d_list = list(d)
return_data.append(d_list[0])
self.updateUrlLogStatus(d_list[0])
return return_data
def parse(self, response):
dict_json = json.loads(response.body)
commentPage = dict_json['data']['commentPage']
if commentPage['totalCount'] > 0:
good_comment_item = kaola.items.KaolaGoodCommentItem()
for result in commentPage['result']:
good_comment_item['good_id'] = result['goodsId']
good_comment_item['goodsCommentId'] = result['goodsCommentId']
good_comment_item['appType'] = result['appType']
good_comment_item['orderId'] = result['orderId']
good_comment_item['account_id'] = result['accountId']
good_comment_item['point'] = result['commentPoint']
good_comment_item['commentContent'] = result['commentContent']
good_comment_item['createTime'] = result['createTime']
good_comment_item['updateTime'] = result['updateTime']
good_comment_item['zanCount'] = result['zanCount']
yield good_comment_item
# 获取商品评论下一页数据
if commentPage['pageNo'] < commentPage['totalPage']:
good_id = dict_json['data']['commentStat']['goodsId']
pageNo = commentPage['pageNo'] + 1
pageNo = str(pageNo)
good_id = str(good_id)
apiUrl = 'https://goods.kaola.com/commentAjax/comment_list_new.json?goodsId=' + good_id + '&pageSize=100&pageNo=' + pageNo
yield scrapy.Request(apiUrl, callback=self.parse)
<file_sep>/suning/suning/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class SuningCategoryItem(scrapy.Item):
# 分类id
CategoryId = scrapy.Field()
# 分类名称
CategoryName = scrapy.Field()
# 上级id
parentId = scrapy.Field()
class SuningUrlLogItem(scrapy.Item):
# 爬取地址
url = scrapy.Field()
# 爬虫类型
type = scrapy.Field()
# 爬虫地址名称
title = scrapy.Field()
# 爬虫来源地址
RefererUrl = scrapy.Field()
class SuningItem(scrapy.Item):
pass
<file_sep>/suning/suning/SuningMiddlewares/ResponseMiddleware.py
class SuningResponseMiddleware(object):
def process_response(self, request, response, spider):
print('SuningResponseMiddleware process_response, request_url: %s, response_code: %s, spider: %s',request.url, response.status, spider.name)
# ReptileUrlItem = {}
# ReptileUrlItem['spider_name'] = spider.name
# ReptileUrlItem['url'] = response.url
# ReptileUrlItem['code'] = response.status
# Add().insertReptile(ReptileUrlItem)
return response<file_sep>/suning/suning/spiders/ListCategory.py
# -*- coding: utf-8 -*-
import scrapy
import pymysql
import pymysql.cursors
import suning.items
from scrapy_redis.spiders import RedisSpider
class ListCategorySpider(RedisSpider):
name = 'ListCategory'
redis_key = "ListSpider:start_urls"
#allowed_domains = ['list.suning.com']
#start_urls = ['http://list.suning.com/']
def __init__(self, *args, **kwargs):
domain = kwargs.pop('domain', '')
self.allowed_domains = filter(None, domain.split(','))
super(ListCategorySpider, self).__init__(*args, **kwargs)
def parse(self, response):
#获取大分类
search_main = response.xpath('//div[@class="search-main introduce clearfix"]/div')
for category in search_main:
# 一级分类
# category_id = list.xpath('@id').extract_first()
# category_name = list.xpath('h2/text()').extract()
#parentId = 0
# 二级分类
box_data = category.xpath('div[@class="title-box clearfix"]')
for category_2 in box_data:
UrlLogItem = suning.items.SuningUrlLogItem()
href = category_2.xpath('div[@class="t-left fl clearfix"]/a/@href').extract_first()
title = category_2.xpath('div[@class="t-left fl clearfix"]/a/text()').extract_first()
UrlLogItem['url'] = response.urljoin(href)
UrlLogItem['title'] = title
UrlLogItem['type'] = 'category'
UrlLogItem['RefererUrl'] = response.url
yield UrlLogItem
# 三级分类
for category_3 in category_2.xpath('div[@class="t-right fl clearfix"]'):
href_3 = category_3.xpath('a/@href').extract_first()
if href_3 is not None:
title_3 = category_3.xpath('a/text()').extract_first()
UrlLogItem = suning.items.SuningUrlLogItem()
UrlLogItem['url'] = response.urljoin(href_3)
UrlLogItem['title'] = title_3
UrlLogItem['type'] = 'category'
UrlLogItem['RefererUrl'] = response.url
yield UrlLogItem
#self.updateUrlLogStatus(url=response.url)
<file_sep>/mofcom/mysqlTest.py
import pymysql
import pymysql.cursors
from DBUtils.PooledDB import PooledDB
import threading
# 连接数据库
connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='<PASSWORD>',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
cursor = connect.cursor()
def tsk1():
while True:
print('运行tsk1')
sql = """select * from good_comment"""
cursor.execute(sql, )
connect.commit()
def tsk2():
while True:
print('运行tsk2')
sql = """select commentContent from good_comment"""
cursor.execute(sql, )
connect.commit()
tsk1()
# 创建并启动第一个线程
# t1 =threading.Thread(target=tsk1)
# t1.start()
# # 创建并启动第二个线程
# t2 =threading.Thread(target=tsk2)
# t2.start()
print('主线程执行完成!')
<file_sep>/kaola/kaola/spiders/search.py
# -*- coding: utf-8 -*-
import scrapy
import requests
import json
import kaola.items
#import KaolaGoodItem
# 获取评论 https://goods.kaola.com/commentAjax/comment_list_new.json?goodsId=1301389
# 获取品牌,分类 https://goods.kaola.com/product/breadcrumbTrail/1301389.json
# 获取商品价格,活动信息 https://goods.kaola.com/product/getPcGoodsDetailDynamic.json?goodsId=1301389
# 推荐商品 https://goods.kaola.com/product/getGoodsRecommendInfo.json?goodsId=1301389&accountId=&recommendType=5&t=1555493105258
# 考拉分类品牌接口 https://search.kaola.com/api/getFrontCategory.shtml
class SearchSpider(scrapy.Spider):
name = 'search'
allowed_domains = ['search.kaola.com','goods.kaola.com']
#start_urls = ['https://search.kaola.com/category/1472/2639.html?key=&pageSize=60&pageNo=1&sortfield=0&isStock=false&isSelfProduct=false&isPromote=false&isTaxFree=false&factoryStoreTag=-1&isCommonSort=false&isDesc=true&b=&proIds=&source=false&country=&needBrandDirect=false&isNavigation=0&lowerPrice=-1&upperPrice=-1&backCategory=&headCategoryId=&changeContent=crumbs_country&#topTab']
#start_urls = ['https://search.kaola.com/category/1472.html']
start_urls = ['https://search.kaola.com/api/getFrontCategory.shtml']
def parse(self, response):
dict_json = json.loads(response.body)
frontCategoryList = dict_json['body']['frontCategoryList']
for categroy in self.handle_children_node_list(frontCategoryList):
yield categroy
def parse_search_list(self, response):
# 获取搜索下商品列表
hreflist = response.xpath('//div[@class="goodswrap promotion"]/a/@href').extract()
for href in hreflist:
yield scrapy.Request(response.urljoin(href), callback=self.parse_good, dont_filter=False)
# 搜索页下一页抓取
next_page = response.xpath('//div[@class="splitPages"]/a[@class="nextPage"]/@href').extract_first()
if next_page is not None:
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
def handle_children_node_list(self, datalist, parentId = 0, categoryId = 0):
for data in datalist:
Categoryitem = kaola.items.KaolaCategoryItem()
Categoryitem['categoryId'] = data['categoryId']
Categoryitem['parentId'] = data['parentId']
Categoryitem['categoryLevel'] = data['categoryLevel']
Categoryitem['categoryName'] = data['categoryName']
Categoryitem['categoryStatus'] = data['categoryStatus']
yield Categoryitem
# 根据分类id search 抓取商品数据
if data['categoryLevel'] == 2:
parentId = data['categoryId']
if data['categoryLevel'] == 3:
categoryId = data['categoryId']
# 发送请求
HttpsUrl = 'https://search.kaola.com/category/' + str(parentId) + '/' + str(categoryId) + '.html'
yield scrapy.Request(HttpsUrl, callback=self.parse_search_list)
# 迭代下一层
if 'childrenNodeList' in data:
for categorys in self.handle_children_node_list(data['childrenNodeList'], parentId, categoryId):
yield categorys
# 商品信息
def parse_good(self, response):
good_item = kaola.items.KaolaGoodItem()
# 截取商品id
good_id = self.good_url_split(response.url)
good_item['good_id'] = good_id
# 获取商品价格
good_price = self.getGoodMarkprice(good_id)
good_item['marketPrice'] = good_price['marketPrice']
good_item['currentPrice'] = good_price['currentPrice']
good_item['name'] = response.xpath('//dt[@class="product-title"]/text()').extract_first()
good_item['orig_country'] = response.xpath('//dt[@class="orig-country"]/span/text()').extract_first()
good_item['brand'] = response.xpath('//dt[@class="orig-country"]/a/text()').extract_first()
yield good_item
# 获取商品评论信息
apiUrl = 'https://goods.kaola.com/commentAjax/comment_list_new.json?goodsId='+good_id + '&pageSize=100'
yield scrapy.Request(apiUrl, callback=self.getGoodComment)
# 获取推荐商品信息
RecommendGoodUrls = response.xpath('//div[@id="j-listsimilar"]/div/div/a/@href').extract()
for GoodUrl in RecommendGoodUrls:
yield scrapy.Request(response.urljoin(GoodUrl), callback=self.parse_good, dont_filter=False)
# 通过请求id截取商品id
def good_url_split(self, goodUrl):
goodUrlList = goodUrl.split('/')
goodidList = goodUrlList[4].split('.')
good_id = goodidList[0]
return good_id
# 获取商品价格
def getGoodMarkprice(self, goodId):
params = {'goodsId': goodId}
apiUrl = 'https://goods.kaola.com/product/getPcGoodsDetailDynamic.json'
res = requests.get(apiUrl, params=params)
json_requests = res.content.decode()
dict_json = json.loads(json_requests)
return_dict = {}
marketPrice = dict_json['data']['skuPrice']['marketPrice']
return_dict['marketPrice'] = marketPrice
currentPrice = dict_json['data']['skuPrice']['currentPrice']
return_dict['currentPrice'] = currentPrice
return return_dict
# 获取商品评论
def getGoodComment(self, response):
dict_json = json.loads(response.body)
commentPage = dict_json['data']['commentPage']
if commentPage['totalCount'] > 0:
good_comment_item = kaola.items.KaolaGoodCommentItem()
for result in commentPage['result']:
good_comment_item['good_id'] = result['goodsId']
good_comment_item['goodsCommentId'] = result['goodsCommentId']
good_comment_item['appType'] = result['appType']
good_comment_item['orderId'] = result['orderId']
good_comment_item['account_id'] = result['accountId']
good_comment_item['point'] = result['commentPoint']
good_comment_item['commentContent'] = result['commentContent']
good_comment_item['createTime'] = result['createTime']
good_comment_item['updateTime'] = result['updateTime']
good_comment_item['zanCount'] = result['zanCount']
yield good_comment_item
# 获取商品评论下一页数据
if commentPage['pageNo'] < commentPage['totalPage']:
good_id = dict_json['data']['commentStat']['goodsId']
pageNo = commentPage['pageNo'] + 1
pageNo = str(pageNo)
good_id = str(good_id)
apiUrl = 'https://goods.kaola.com/commentAjax/comment_list_new.json?goodsId=' + good_id + '&pageSize=100&pageNo='+ pageNo
yield scrapy.Request(apiUrl, callback=self.getGoodComment)<file_sep>/suning/main.py
# from scrapy import cmdline
#
# cmdline.execute('scrapy crawl list'.split())
import os
os.system('scrapy crawl list')<file_sep>/suning/suning/spiders/ProductList.py
# -*- coding: utf-8 -*-
import scrapy
import pymysql
import pymysql.cursors
import suning.items
import redis
from scrapy.spiders import Spider, CrawlSpider
import six
from scrapy.exceptions import DontCloseSpider
from scrapy import signals
from scrapy_redis.utils import bytes_to_str
from scrapy_redis import scheduler
from scrapy_redis.queue import SpiderStack
class ProductListSpider(Spider):
name = 'ProductList'
#redis_key = "ListSpider:start_urls"
redis_encoding = None
#allowed_domains = ['list.suning.com']
#start_urls = ['http://list.suning.com/']
#def __init__(self, *args, **kwargs):
# domain = kwargs.pop('domain', '')
# print(domain)
# self.allowed_domains = filter(None, domain.split(','))
# print(self.allowed_domains)
# super(ProductListSpider, self).__init__(*args, **kwargs)
def start_requests(self):
print('start_requests')
return self.next_requests()
def next_requests(self):
found = 0
while found < 30:
redis_conn = redis.Redis(host='127.0.0.1', port='6379')
redis_llen = redis_conn.llen('ProductListSpider:start_urls')
print('next_requests redis_llen:', redis_llen)
if redis_llen > 0:
data = redis_conn.lpop('ProductListSpider:start_urls')
yield self.make_request_from_data(data)
found += 1
else:
break
def setup_redis(self, crawler=None):
crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)
def make_request_from_data(self, data):
print('make_request_from_data')
print(data)
url = data.decode('utf-8')
# url = bytes_to_str(data, self.redis_encoding)
print(url)
return self.make_requests_from_url(url)
def schedule_next_requests(self):
print('start11111')
"""Schedules a request if available"""
# TODO: While there is capacity, schedule a batch of redis requests.
for req in self.next_requests():
self.crawler.engine.crawl(req, spider=self)
def spider_idle(self):
"""Schedules a request if available, otherwise waits."""
# XXX: Handle a sentinel to close the spider.
print('spider_idle')
self.schedule_next_requests()
raise DontCloseSpider
@classmethod
def from_crawler(self, crawler, *args, **kwargs):
print('from_crawler')
obj = super(ProductListSpider, self).from_crawler(crawler, *args, **kwargs)
obj.setup_redis(crawler)
return obj
def parse(self, response):
# 获取下一页地址
isNextPage = False
next_page_list = response.xpath('//div[@class="search-page page-fruits clearfix"]/a/@href').extract()
for next_page in next_page_list:
if (response.url == response.urljoin(next_page)):
isNextPage = True
continue
if (isNextPage) :
UrlLogItem = suning.items.SuningUrlLogItem()
UrlLogItem['url'] = response.urljoin(next_page)
SpiderStack.push(UrlLogItem['url'])
<file_sep>/mofcom/mofcom/spiders/list.py
# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from selenium import webdriver
import mofcom.items
from mofcom.Models.GetData import GetData
import time
class ListSpider(Spider):
name = 'price_list'
def __init__(self):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
#D:\\PythonCode\\scrapy\\chromedriver_74.exe
self.browser = webdriver.Chrome(executable_path='E:\\PythonCode\\scrapy\\chromedriver_73.exe', chrome_options=chrome_options)
#self.browser = webdriver.Chrome("E:\\PythonCode\\scrapy\\chromedriver_73.exe")
self.browser.set_page_load_timeout(120)
def closed(self, spider):
print("spider closed")
self.browser.close()
# 截取请求地址获取参数
def getParam(self, url, file):
url_split = url.split('?')
para = {}
if len(url_split) > 1:
params = url_split[1].split('&')
for param in params:
p = param.split('=')
para[p[0]] = p[1]
if file in para:
if para[file] is not None:
return para[file]
return ''
# start_urls = ['http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=13079&craft_index=13233&par_p_index=35']
# self.crawler.engine.close_spider(self, '计数超过10,停止爬虫!')
def start_requests(self):
self.logger.info("start_requests %s", self.name)
start_urls = GetData().getReptile({"code": '0', "spider_name": 'price_list'})
for url in start_urls:
yield Request(url=url['url'], callback=self.parse)
def parse(self, response):
self.logger.info("response url:%s", response.url)
region_id = self.getParam(response.url, 'par_p_index')
table = response.xpath('//table[@class="table-01 mt30"]/tbody/tr')
for tr in table:
tds = tr.xpath('td')
if len(tds) > 0:
ProductPriceHistoryItem = mofcom.items.ProductPriceHistoryItem()
ProductPriceHistoryItem['date'] = tds[0].xpath('text()').extract_first()
ProductPriceHistoryItem['product'] = tds[1].xpath('span/text()').extract_first()
ProductPriceHistoryItem['price'] = tds[2].xpath('span/text()').extract_first()
ProductPriceHistoryItem['unit'] = tds[2].xpath('text()').extract_first()
ProductPriceHistoryItem['market'] = tds[3].xpath('a/text()').extract_first()
ProductPriceHistoryItem['region_id'] = region_id
yield ProductPriceHistoryItem
# 请求下一页
next_button = response.xpath('//a[@class="next"]').extract()
if len(next_button) > 0:
page = self.getParam(response.url, 'page')
if page == '': #page为空,第一页
next_page = response.url + '&page=2'
else: #page不为空,页码 + 1
if int(page) > 9:
next_page = response.url[:-2] + str(int(page) + 1)
elif int(page) > 99:
next_page = response.url[:-3] + str(int(page) + 1)
else:
next_page = response.url[:-1] + str(int(page) + 1)
yield Request(next_page, callback=self.parse)
else: #本页抓取完成,开启下一页
self.logger.info("succes response url:%s", response.url)
start_urls = GetData().getReptile({"code": '0', "spider_name": 'price_list'})
if start_urls is not False:
for url in start_urls:
yield Request(url=url['url'], callback=self.parse)
else:
self.crawler.engine.close_spider(self, 'price_list 地址抓取完成, 停止爬虫!')
# 存入下一页地址
# ReptileUrlItem = mofcom.items.ReptileUrlItem()
# ReptileUrlItem['spider_name'] = 'price_list'
# ReptileUrlItem['url'] = next_page
# ReptileUrlItem['code'] = '0'
# yield ReptileUrlItem
<file_sep>/mofcom/mofcom/Models/db.py
import pymysql
import pymysql.cursors
from DBUtils.PooledDB import PooledDB
import traceback
from mofcom.Config.PoolDBConfig import DBPoolConfig
class DB(object):
# 连接池对象
__pool = None
def __init__(self):
# 连接数据库update
self._conn = DBPoolConfig.MYSQL_POOL.connection()
self._cursor = self._conn.cursor(cursor=pymysql.cursors.DictCursor)
# 查询所有数据
def get_all(self, sql, param=None):
try:
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
if count > 0:
result = self._cursor.fetchall()
else:
result = False
return result
except Exception as e:
traceback.print_exc(e)
# 查询某一个数据
def get_one(self, sql, param=None):
try:
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
if count > 0:
result = self._cursor.fetchone()
else:
result = False
return result
except Exception as e:
traceback.print_exc(e)
# 查询数量
def get_count(self, sql, param=None):
try:
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
return count
except Exception as e:
traceback.print_exc(e)
# 查询部分
def get_many(self, sql, param=None, num=0):
try:
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
if count > 0:
if num > 0:
result = self._cursor.fetchmany(num)
else:
result = self._cursor.fetchall()
else:
return False
return result
except Exception as e:
traceback.print_exc(e)
# 插入一条数据
def insert_one(self, sql, value):
try:
row_count = self._cursor.execute(sql, value)
return row_count
except Exception as e:
traceback.print_exc(e)
self.end("rollback")
# 插入多条数据
def insert_many(self, sql, values):
try:
row_count = self._cursor.executemany(sql, values)
return row_count
except Exception as e:
traceback.print_exc(e)
self.end("rollback")
# 执行sql
def __query(self, sql, param=None):
try:
if param is None:
count = self._cursor.execute(sql)
else:
count = self._cursor.execute(sql, param)
return count
except Exception as e:
traceback.print_exc(e)
# 更新
def update(self, sql, param=None):
return self.__query(sql, param)
# 删除
def delete(self, sql, param=None):
return self.__query(sql, param)
def begin(self):
self._conn.autocommit(0)
def end(self, option='commit'):
if option == 'commit':
self._conn.commit()
else:
self._conn.rollback()
# 关闭数据库连接,释放连接池资源
def dispose(self, is_end=1):
if is_end == 1:
self.end('commit')
else:
self.end('rollback')
self._cursor.close()
self._conn.close()<file_sep>/kaola/kaola/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class KaolaBrandItem(scrapy.Item):
# 品牌id
brandId = scrapy.Field()
# 品牌名称
brandName = scrapy.Field()
class KaolaGoodBrandItem(scrapy.Item):
# 商品id
good_id = scrapy.Field()
# 品牌id
brandId = scrapy.Field()
class KaolaGoodCategoryItem(scrapy.Item):
# 商品id
good_id = scrapy.Field()
# 分类id
categoryId = scrapy.Field()
# 分类名称
categoryName = scrapy.Field()
# 级别
level = scrapy.Field()
leaf = scrapy.Field()
# 地址信息
class KaolaUrlLogItem(scrapy.Item):
# 地址
url = scrapy.Field()
# 地址类型
type = scrapy.Field()
# 分类信息
class KaolaCategoryItem(scrapy.Item):
# 分类id
categoryId = scrapy.Field()
# 上级分类id
parentId = scrapy.Field()
# 分类级别
categoryLevel = scrapy.Field()
# 分类名称
categoryName = scrapy.Field()
# 分类状态
categoryStatus = scrapy.Field()
# 商品基础信息
class KaolaGoodItem(scrapy.Item):
#商品id
good_id = scrapy.Field()
# 商品名称
name = scrapy.Field()
# 产地(原产国)
orig_country = scrapy.Field()
# 品牌
brand = scrapy.Field()
# 售价
currentPrice = scrapy.Field()
# 参考价
marketPrice = scrapy.Field()
# 税费
#taxAmoun = scrapy.Field()
# 商品评论信息
class KaolaGoodCommentItem(scrapy.Item):
#商品id
good_id = scrapy.Field()
# 评论id
goodsCommentId = scrapy.Field()
# 评论设备
appType = scrapy.Field()
# 订单id
orderId = scrapy.Field()
# 用户名
account_id = scrapy.Field()
# 星级
point = scrapy.Field()
# 评论内容
commentContent = scrapy.Field()
# 评论时间
createTime = scrapy.Field()
# 修改时间
updateTime = scrapy.Field()
# 点赞数
zanCount = scrapy.Field()
<file_sep>/kaola/kaola/spiders/getUrlLog.py
# -*- coding: utf-8 -*-
import scrapy
import json
import kaola.items
class GeturllogSpider(scrapy.Spider):
name = 'getUrlLog'
allowed_domains = ['search.kaola.com']
start_urls = ['https://search.kaola.com/api/getFrontCategory.shtml']
def __init__(self, name=None, **kwargs):
kwargs.pop('_job')
super(GeturllogSpider, self).__init__(name, **kwargs)
def parse(self, response):
dict_json = json.loads(response.body)
frontCategoryList = dict_json['body']['frontCategoryList']
for categroy in self.handle_children_node_list(frontCategoryList):
yield categroy
# 迭代循环处分类信息
def handle_children_node_list(self, datalist, parentId = 0, categoryId = 0):
for data in datalist:
Categoryitem = kaola.items.KaolaCategoryItem()
Categoryitem['categoryId'] = data['categoryId']
Categoryitem['parentId'] = data['parentId']
Categoryitem['categoryLevel'] = data['categoryLevel']
Categoryitem['categoryName'] = data['categoryName']
Categoryitem['categoryStatus'] = data['categoryStatus']
yield Categoryitem
# 根据分类id search 抓取商品数据
if data['categoryLevel'] == 2:
parentId = data['categoryId']
if data['categoryLevel'] == 3:
categoryId = data['categoryId']
# 发送请求
HttpsUrl = 'https://search.kaola.com/category/' + str(parentId) + '/' + str(categoryId) + '.html'
UrlLogitem = kaola.items.KaolaUrlLogItem()
UrlLogitem['url'] = HttpsUrl
UrlLogitem['type'] = 'category'
yield UrlLogitem
#yield scrapy.Request(HttpsUrl, callback=self.parse_search_list)
# 迭代下一层
if 'childrenNodeList' in data:
for categorys in self.handle_children_node_list(data['childrenNodeList'], parentId, categoryId):
yield categorys<file_sep>/kaola/kaola/spiders/categroy.py
# -*- coding: utf-8 -*-
import scrapy
import pymysql
import pymysql.cursors
import kaola.items
class CategroySpider(scrapy.Spider):
name = 'categroy'
allowed_domains = ['www.kaola.com']
def __init__(self):
# 连接数据库
self.connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='<PASSWORD>',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
self.cursor = self.connect.cursor()
def updateUrlLogStatus(self, url):
sql = """
update url_log set `status` = 1 where `url` = %s
"""
self.cursor.execute(sql, (url))
self.connect.commit()
def start_requests(self):
while True:
urls = self.getUrl()
for url in urls:
yield scrapy.Request(url, callback=self.parse)
def getUrl(self):
# 获取category 爬取地址
sql = """select url from url_log where type = 'category' and status = 0 limit 10"""
self.cursor.execute(sql)
data = self.cursor.fetchall()
return_data = []
for d in data:
d_list = list(d)
return_data.append(d_list[0])
self.updateUrlLogStatus(d_list[0])
return return_data
def parse(self, response):
# 获取搜索下商品列表
hreflist = response.xpath('//div[@class="goodswrap promotion"]/a/@href').extract()
for href in hreflist:
UrlLogitem = kaola.items.KaolaUrlLogItem()
UrlLogitem['url'] = response.urljoin(href)
UrlLogitem['type'] = 'good'
yield UrlLogitem
#yield scrapy.Request(response.urljoin(href), callback=self.parse_good, dont_filter=False)
# 搜索页下一页抓取
next_page = response.xpath('//div[@class="splitPages"]/a[@class="nextPage"]/@href').extract_first()
if next_page is not None:
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)<file_sep>/kaola/kaola/spiders/goods.py
# -*- coding: utf-8 -*-
import scrapy
import pymysql
import pymysql.cursors
import kaola.items
import json
import requests
class GoodsSpider(scrapy.Spider):
name = 'goods'
allowed_domains = ['goods.kaola.com']
def __init__(self):
# 连接数据库
self.connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
self.cursor = self.connect.cursor()
def updateUrlLogStatus(self, url):
sql = """
update url_log set `status` = 1 where `url` = %s
"""
self.cursor.execute(sql, (url))
self.connect.commit()
def start_requests(self):
while True:
urls = self.getUrl()
for url in urls:
yield scrapy.Request(url, callback=self.parse_good, dont_filter=False)
def getUrl(self):
# 获取category 爬取地址
sql = """select url from url_log where type = 'good' and status = 0 limit 1"""
self.cursor.execute(sql)
data = self.cursor.fetchall()
return_data = []
for d in data:
d_list = list(d)
return_data.append(d_list[0])
self.updateUrlLogStatus(d_list[0])
return return_data
# 商品信息
def parse_good(self, response):
good_item = kaola.items.KaolaGoodItem()
# 截取商品id
good_id = self.good_url_split(response.url)
good_item['good_id'] = good_id
# 获取商品价格
good_price = self.getGoodMarkprice(good_id)
good_item['marketPrice'] = good_price['marketPrice']
good_item['currentPrice'] = good_price['currentPrice']
good_item['name'] = response.xpath('//dt[@class="product-title"]/text()').extract_first()
good_item['orig_country'] = response.xpath('//dt[@class="orig-country"]/span/text()').extract_first()
good_item['brand'] = response.xpath('//dt[@class="orig-country"]/a/text()').extract_first()
yield good_item
# 获取商品评论信息
apiUrl = 'https://goods.kaola.com/commentAjax/comment_list_new.json?goodsId='+good_id + '&pageSize=100'
UrlLogitem = kaola.items.KaolaUrlLogItem()
UrlLogitem['url'] = apiUrl
UrlLogitem['type'] = 'good_comment'
yield UrlLogitem
#yield scrapy.Request(apiUrl, callback=self.getGoodComment)
# 获取推荐商品信息
RecommendGoodUrls = response.xpath('//div[@id="j-listsimilar"]/div/div/a/@href').extract()
for GoodUrl in RecommendGoodUrls:
UrlLogitem = kaola.items.KaolaUrlLogItem()
UrlLogitem['url'] = GoodUrl
UrlLogitem['type'] = 'good'
yield UrlLogitem
#yield scrapy.Request(response.urljoin(GoodUrl), callback=self.parse_good, dont_filter=False)
# 获取商品品牌信息
APIUrl = 'https://goods.kaola.com/product/breadcrumbTrail/'+ good_id +'.json'
yield scrapy.Request(APIUrl, callback = self.parse_category)
def parse_category(self, response):
dict_json = json.loads(response.body)
retdata = dict_json['retdata']
good_id = self.good_url_split_good_category(response.url)
# 品牌信息
brandItem = kaola.items.KaolaBrandItem()
brandItem['brandId'] = retdata['brandId']
brandItem['brandName'] = retdata['brandName']
yield brandItem
# 商品品牌信息
GoodBrandItem = kaola.items.KaolaGoodBrandItem()
GoodBrandItem['good_id'] = good_id
GoodBrandItem['brandId'] = retdata['brandId']
yield GoodBrandItem
for category in dict_json['retdata']['categoryList']:
GoodCategoryItem = kaola.items.KaolaGoodCategoryItem()
GoodCategoryItem['good_id'] = good_id
GoodCategoryItem['categoryId'] = category['categoryId']
GoodCategoryItem['categoryName'] = category['categoryName']
GoodCategoryItem['level'] = category['level']
GoodCategoryItem['leaf'] = category['leaf']
yield GoodCategoryItem
# 通过请求id截取商品id
def good_url_split(self, goodUrl):
goodUrlList = goodUrl.split('/')
goodidList = goodUrlList[4].split('.')
good_id = goodidList[0]
return good_id
def good_url_split_good_category(self, goodUrl):
goodUrlList = goodUrl.split('/')
goodidList = goodUrlList[5].split('.')
good_id = goodidList[0]
return good_id
# 获取商品价格
def getGoodMarkprice(self, goodId):
params = {'goodsId': goodId}
apiUrl = 'https://goods.kaola.com/product/getPcGoodsDetailDynamic.json'
res = requests.get(apiUrl, params=params)
json_requests = res.content.decode()
dict_json = json.loads(json_requests)
return_dict = {}
marketPrice = dict_json['data']['skuPrice']['marketPrice']
return_dict['marketPrice'] = marketPrice
currentPrice = dict_json['data']['skuPrice']['currentPrice']
return_dict['currentPrice'] = currentPrice
return return_dict<file_sep>/bj_bilnd_date/bj_bilnd_date/spiders/beijing_spider.py
# -*- coding: utf-8 -*-
import scrapy
class BeijingSpiderSpider(scrapy.Spider):
name = 'beijing_spider'
allowed_domains = ['www.zhihu.com']
start_urls = ['http://www.zhihu.com/']
def parse(self, response):
pass
<file_sep>/kaola/kaola/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
import pymysql.cursors
from kaola.items import KaolaGoodItem, KaolaGoodCommentItem, KaolaCategoryItem, KaolaUrlLogItem, KaolaBrandItem, KaolaGoodBrandItem, KaolaGoodCategoryItem
class KaolaPipeline(object):
def __init__(self):
# 连接数据库
self.connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='<PASSWORD>',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
self.cursor = self.connect.cursor()
def process_item(self, item, spider):
if isinstance(item, KaolaGoodItem):
# 商品信息入库
self.insertGood(item)
elif isinstance(item, KaolaGoodCommentItem):
# 商品评论入库
self.insertGoodComment(item)
elif isinstance(item, KaolaCategoryItem):
# 商品分类入库
self.insertCategory(item)
elif isinstance(item, KaolaUrlLogItem):
self.insertUrlLog(item)
elif isinstance(item, KaolaBrandItem):
self.insertBrand(item)
elif isinstance(item, KaolaGoodBrandItem):
self.insertGoodBrand(item)
elif isinstance(item, KaolaGoodCategoryItem):
self.insertGoodCategory(item)
return item
# 品牌
def insertBrand(self, item):
sql = """replace into brand(brandId,brandName) values (%s, %s)"""
self.cursor.execute(sql, (item['brandId'], item['brandName']))
self.connect.commit()
# 商品品牌
def insertGoodBrand(self, item):
sql = """replace into good_brand(good_id,brandId) values (%s, %s)"""
self.cursor.execute(sql, (item['good_id'], item['brandId']))
self.connect.commit()
# 品牌
def insertGoodCategory(self, item):
sql = """replace into good_category(good_id, categoryId, categoryName, `level`, leaf) values (%s, %s, %s, %s, %s)"""
self.cursor.execute(sql, (item['good_id'], item['categoryId'], item['categoryName'], item['level'], item['leaf']))
self.connect.commit()
# 爬取地址
def insertUrlLog(self, item):
sql = """insert into url_log (url, `type`) values (%s, %s)"""
self.cursor.execute(sql, (item['url'], item['type']))
self.connect.commit()
# 商品信息入库
def insertGood(self, item):
sql = """replace into goods(good_id,good_name,orig_country,brand,`currentPrice`,`marketPrice`) values (%s, %s, %s, %s, %s, %s)"""
self.cursor.execute(sql, (item['good_id'], item['name'], item['orig_country'], item['brand'], item['currentPrice'], item['marketPrice']))
self.connect.commit()
# 商品信息入库
def insertGoodComment(self, item):
sql = """replace into good_comment(good_id, goodsCommentId, appType, orderId, account_id, point, commentContent, createTime, updateTime, zanCount)
values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
self.cursor.execute(sql,
(item['good_id'], item['goodsCommentId'], item['appType'], item['orderId'], item['account_id'], item['point'], item['commentContent'], item['createTime'], item['updateTime'], item['zanCount'])
)
self.connect.commit()
# 商品分类入库
def insertCategory(self, item):
sql = """replace into categorys(categoryId, parentId, categoryLevel, categoryName, categoryStatus) values (%s, %s, %s, %s, %s)"""
self.cursor.execute(sql, (item['categoryId'], item['parentId'], item['categoryLevel'], item['categoryName'], item['categoryStatus']))
self.connect.commit()<file_sep>/mofcom/mysqlTest1.py
import pymysql
import pymysql.cursors
from DBUtils.PooledDB import PooledDB
import threading
# 连接数据库
connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='<PASSWORD>',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
cursor = connect.cursor()
def tsk1():
while True:
print('运行tsk1')
sql = """select * from good_comment"""
cursor.execute(sql, )
connect.commit()
def tsk2():
while True:
print('运行tsk2')
sql = """select commentContent from good_comment"""
cursor.execute(sql, )
connect.commit()
tsk2()
print('主线程执行完成!')
<file_sep>/ReptilePractice/ReptilePractice/spiders/mofcom_spider.py
# -*- coding: utf-8 -*-
import scrapy
class MofcomSpider(scrapy.Spider):
name = 'mofcom'
start_urls = ['http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml']
def parse(self, response):
print(response)<file_sep>/kaola/kaola/Models/category.py
class categoryModel():
# 添加数据
def insertCategory(self, item):
sql = """replace into categorys(categoryId, parentId, categoryLevel, categoryName, categoryStatus) values (%s, %s, %s, %s, %s)"""
self.cursor.execute(sql, (
item['categoryId'], item['parentId'], item['categoryLevel'], item['categoryName'], item['categoryStatus']))
self.connect.commit()<file_sep>/myscrapy/myscrapy/spiders/jobbole_spider.py
# -*- coding: utf-8 -*-
import scrapy
class JobboleSpider(scrapy.Spider):
name = 'jobbole'
start_urls = ['http://date.jobbole.com/']
def parse(self, response):
for href in response.css('h3.p-tit a::attr(href)').extract():
yield scrapy.Request(response.urljoin(href), callback=self.parse_data)
next_page = response.css('#pagination-next-page a::attr(href)').extract_first()
if next_page is not None:
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
def parse_data(self, response):
content_list = self.contentHandle(response)
if content_list is not None:
content_list['title'] = response.css('h1.p-tit-single::text').extract_first()
content_list['release_time'] = response.css('p.p-meta span::text').extract_first()
content_list['city'] = response.css('p.p-meta span')[1].css('a::text').extract_first()
# yield {
# 'title': response.css('h1.p-tit-single::text').extract_first(),
# 'release_time': response.css('p.p-meta span::text').extract_first(),
# 'city': response.css('p.p-meta span')[1].css('a::text').extract_first(),
# 'content': content_list
# }
yield content_list
def contentHandle(self, response):
content = response.css('.p-entry p').extract_first()
if content is not None:
content_list = content.split('<br>\n')
if len(content_list) <= 1:
return None
details = {}
data_key = ['birth', # 出生日期
'height', #身高
'weight', #体重
'Education', #学历
'Location', #所在城市
'Household', #户籍
'Native_place', #籍贯
'Occupation', #职业
'income', #收入
'Hobby', #兴趣爱好
'Long-distance-love', #是否接受异地恋
'marry-year', #打算几年内结婚
'word', #一句话脱颖而出
'about_me', #自我介绍
]
count = 0
for data in content_list:
if count > 13:
break
data_rows = data.split(':')
details[data_key[count]] = data_rows[1]
count += 1
return details<file_sep>/mofcom/mofcom/Config/PoolDBConfig.py
import pymysql
import pymysql.cursors
from DBUtils.PooledDB import PooledDB
class DBPoolConfig(object):
MYSQL_POOL = PooledDB(creator=pymysql,
maxconnections=5,
mincached=5,
maxcached=0,
blocking=True,
host='127.0.0.1',
port=3306,
user='root',
passwd='<PASSWORD>',
db='mofcom',
charset='utf8')<file_sep>/mofcom/mofcom/Models/GetData.py
from mofcom.Models.db import DB
class GetData(DB):
# def __init__(self):
# super().__init__()
# def __del__(self):
# self.end()
def getCategory(self):
sql = """select * from category"""
return self.get_many(sql)
# self.cursor.execute(sql)
# return self.cursor.fetchall()
def getProduct(self):
sql = """select * from product"""
return self.get_many(sql)
# self.cursor.execute(sql)
# return self.cursor.fetchall()
def getRegion(self):
sql = """select * from region"""
return self.get_many(sql)
# self.cursor.execute(sql)
# return self.cursor.fetchall()
def getMarket(self):
sql = """select * from market"""
return self.get_many(sql)
# self.cursor.execute(sql)
# return self.cursor.fetchall()
def getReptile(self, param):
sql = """select url from reptile where code = %s and spider_name = %s"""
return self.get_many(sql, (param['code'], param['spider_name']), 32)
# self.cursor.execute(sql, (code, spider_name))
# return self.cursor.fetchall()
def getReptileByUrl(self, param):
sql = """select * from reptile where url = %s"""
return self.get_count(sql, param)
# self.cursor.execute(sql, ( url ))
# return self.cursor.fetchone()
<file_sep>/mofcom/mofcom/Models/Add.py
from mofcom.Models.db import DB
class Add(DB):
def __del__(self):
self.end()
# 分类
def insertCategory(self, item):
sql = """replace into category (`category_id`, `name`) values (%s, %s)"""
self.update(sql, (item['category_id'], item['name']))
# self.cursor.execute(sql, (item['category_id'], item['name']))
# self.connect.commit()
# 商品
def insertProduct(self, item):
sql = """replace into product (`product_id`, `category_id`, `name`) values (%s, %s, %s)"""
self.update(sql, (item['product_id'], item['category_id'], item['name']))
# self.cursor.execute(sql, (item['product_id'], item['category_id'], item['name']))
# self.connect.commit()
# 地区
def insertRegoin(self, item):
sql = """replace into region (`region_id`, `name`) values (%s, %s)"""
self.update(sql, (item['region_id'], item['name']))
# self.cursor.execute(sql, (item['region_id'], item['name']))
# self.connect.commit()
# 市场
def insertMarket(self, item):
sql = """replace into market ( `market_id`, `region_id`, `name`) values ( %s, %s, %s)"""
self.update(sql, (item['market_id'], item['region_id'], item['name']))
# self.cursor.execute(sql, (item['market_id'], item['region_id'], item['name']))
# self.connect.commit()
# 商品价格历史
def insertProductPriceHistory(self, item):
sql = """replace into product_price_history ( `date`, `product`, `price`, `unit`, `market`, `region_id`) values ( %s, %s, %s, %s, %s, %s)"""
self.update(sql, (item['date'], item['product'], item['price'], item['unit'], item['market'], item['region_id']))
# self.cursor.execute(sql, (item['date'], item['product'], item['price'], item['unit'], item['market'], item['region_id']))
# self.connect.commit()
# 地址
def insertReptile(self, item):
sql = """replace into reptile ( `spider_name`, `url`, `code`) values ( %s, %s, %s)"""
self.update(sql, (item['spider_name'], item['url'], item['code']))
# self.cursor.execute(sql, (item['spider_name'], item['url'], item['code']))
# self.connect.commit()<file_sep>/kaola/kaola/Models/__init__.py
# kaola.models __init__
import pymysql
import pymysql.cursors
def __init__() :
# 连接数据库
connect = pymysql.connect(
host='127.0.0.1',
port=3306,
db='kaola',
user='root',
passwd='',
charset='utf8',
use_unicode=True
)
# 通过cursor 执行sql
cursor = connect.cursor()<file_sep>/suning/suning/Models/urlLogModel.py
from suning.Models.db import DB
class UrlLogModel(DB):
# def __init__(self):
# self.cursor = db.initDB()
def __del__(self):
self.end()
# 爬取地址
def insertUrlLog(self, item):
sql = """insert into spider_url_log (url, `title`, `type`, RefererUrl) values (%s, %s, %s, %s)"""
# self.cursor.execute(sql, (item['url'], item['title'], item['type'], item['RefererUrl']))
# self.connect.commit()
self.update(sql, (item['url'], item['title'], item['type'], item['RefererUrl']))<file_sep>/mofcom/mofcom/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from mofcom.items import CategoryItem, ProductItem, RegionItem, MarkerItem, ProductPriceHistoryItem, ReptileUrlItem
from mofcom.Models.Add import Add
class MofcomPipeline(object):
def process_item(self, item, spider):
if isinstance(item, CategoryItem):
# 商品信息入库
Add().insertCategory(item)
elif isinstance(item, ProductItem):
# 商品信息入库
Add().insertProduct(item)
elif isinstance(item, RegionItem):
# 商品信息入库
Add().insertRegoin(item)
elif isinstance(item, MarkerItem):
# 商品信息入库
Add().insertMarket(item)
elif isinstance(item, ProductPriceHistoryItem):
# 商品信息入库
Add().insertProductPriceHistory(item)
elif isinstance(item, ReptileUrlItem):
# 商品信息入库
Add().insertReptile(item)
return item
<file_sep>/mofcom/main.py
from mofcom.Models.GetData import GetData
from mofcom.Models.Add import Add
import datetime
from dateutil.relativedelta import relativedelta
import time
import logging
# 写入日志
def get_logger():
log_dir = 'logs/main.log'
fh = logging.FileHandler(log_dir, encoding='utf-8') #创建一个文件流并设置编码utf8
logger = logging.getLogger() #获得一个logger对象,默认是root
logger.setLevel(logging.DEBUG) #设置最低等级debug
fm = logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s - %(message)s") #设置日志格式
logger.addHandler(fh) #把文件流添加进来,流向写入到文件
fh.setFormatter(fm) #把文件流添加写入格式
return logger
logger = get_logger()
# 循环获取需要读取的链接
def handles_region_product():
data_list = []
product_list = GetData().getProduct()
# print('product_list:')
# print(product_list)
# print(len(product_list))
region_list = GetData().getRegion()
# print('region_list:')
# print(region_list)
# print(len(region_list))
if product_list is not None:
for product_data in product_list:
if region_list is not None:
for region_data in region_list:
data = {}
data['category_id'] = product_data['category_id']
data['product_id'] = product_data['product_id']
data['region_id'] = region_data['region_id']
data_list.append(data)
return data_list
# 循环开始时间到今天的日期
def while_datetime(start_date, end_date):
datestart = datetime.datetime.strptime(start_date, '%Y-%m-%d')
dateend = datetime.datetime.strptime(end_date, '%Y-%m-%d')
# 时间间隔
month_differ = abs((datestart.year - dateend.year) * 12 + (datestart.month - dateend.month) * 1)
date_list = []
if month_differ > 1:
while datestart < dateend:
date_l = {}
date_l['start_date'] = datestart.strftime('%Y-%m-%d')
datestart = datestart + relativedelta(months=3)
date_l['end_date'] = datestart.strftime('%Y-%m-%d')
date_list.append(date_l)
else:
while datestart < dateend:
date_l = {}
date_l['start_date'] = datestart.strftime('%Y-%m-%d')
datestart += datetime.timedelta(days=1)
date_l['end_date'] = datestart.strftime('%Y-%m-%d')
date_list.append(date_l)
return date_list
def main():
start_date = '2014-01-01'
end_date = datetime.datetime.now().strftime('%Y-%m-%d')
region_product_list = handles_region_product()
while_date = while_datetime(start_date, end_date)
while len(region_product_list) > 0:
product = region_product_list.pop()
for date in while_date:
print('开始生成链接 product_id: %s , category_id: %s , region_id: %s', product['product_id'], product['category_id'], product['region_id'])
logger.info('开始生成链接 product_id: %s , category_id: %s , region_id: %s', product['product_id'], product['category_id'], product['region_id'])
item = {}
item['spider_name'] = 'price_list'
item['url'] = 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index='+str(product['category_id'])+'&craft_index='+str(product['product_id'])+'&par_p_index='+str(product['region_id'])+'&startTime='+str(date['start_date'])+'&endTime='+str(date['end_date'])
item['code'] = '0'
getOne = GetData().getReptileByUrl([item['url']])
if getOne == 0:
logger.info("生成链接: %s ", item['url'])
Add().insertReptile(item)
logger.info('暂停5秒')
time.sleep(5)
logger.info('链接生成完成,一共生成')
if __name__ == "__main__":
main()<file_sep>/suning/suning/spiders/SearchList.py
# -*- coding: utf-8 -*-
import scrapy
import pymysql
import pymysql.cursors
import suning.items
from scrapy import Request
from scrapy_redis.spiders import RedisSpider
import scrapy_redis.scheduler
from scrapy_redis.queue import SpiderStack
import redis
class SearchSpider(RedisSpider):
name = 'Search'
redis_key = "SearchSpider:start_urls"
def __init__(self, *args, **kwargs):
domain = kwargs.pop('domain', '')
self.allowed_domains = filter(None, domain.split(','))
super(SearchSpider, self).__init__(*args, **kwargs)
def parse(self, response):
# 获取商品地址
product_url_list = response.xpath('//a[@class="sellPoint"]')
for product_url in product_url_list:
UrlLogItem = suning.items.SuningUrlLogItem()
href = product_url.xpath('@href').extract_first()
title = product_url.xpath('@title').extract_first()
UrlLogItem['url'] = response.urljoin(href)
UrlLogItem['title'] = title
UrlLogItem['type'] = 'good'
UrlLogItem['RefererUrl'] = response.url
yield UrlLogItem
# 获取下一页地址
# isNextPage = False
# next_page_list = response.xpath('//div[@class="search-page page-fruits clearfix"]/a/@href').extract()
# for next_page in next_page_list:
# if (response.url == response.urljoin(next_page)):
# isNextPage = True
# continue
#
# if ( isNextPage ):
# UrlLogItem = suning.items.SuningUrlLogItem()
# UrlLogItem['url'] = response.urljoin(next_page)
# if UrlLogItem['url'].find('list') > 0:
# self.server.lpush(self.redis_key, UrlLogItem['url'])
#
# UrlLogItem['title'] = ''
# UrlLogItem['type'] = 'search_list'
# UrlLogItem['RefererUrl'] = response.url
# yield UrlLogItem
# break
<file_sep>/mofcom/mofcom.sql
-- --------------------------------------------------------
-- 主机: 127.0.0.1
-- 服务器版本: 5.7.24 - MySQL Community Server (GPL)
-- 服务器操作系统: Win64
-- HeidiSQL 版本: 10.1.0.5464
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- 导出 mofcom 的数据库结构
CREATE DATABASE IF NOT EXISTS `mofcom` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mofcom`;
-- 导出 表 mofcom.category 结构
CREATE TABLE IF NOT EXISTS `category` (
`category_id` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='分类表';
-- 正在导出表 mofcom.category 的数据:0 rows
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` (`category_id`, `name`) VALUES
(13079, '畜产品'),
(13080, '水产品'),
(13073, '粮油'),
(13076, '果品'),
(13075, '蔬菜');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
-- 导出 表 mofcom.market 结构
CREATE TABLE IF NOT EXISTS `market` (
`market_id` int(11) NOT NULL,
`region_id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`market_id`,`region_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='市场';
-- 正在导出表 mofcom.market 的数据:0 rows
/*!40000 ALTER TABLE `market` DISABLE KEYS */;
INSERT INTO `market` (`market_id`, `region_id`, `name`) VALUES
(2576578, 11, '北京昌平水屯农副产品批发市场'),
(20540, 11, '北京朝阳区大洋路农副产品批发市场'),
(20843, 34, '安徽安庆市龙狮桥蔬菜批发市场'),
(20857, 34, '安徽蚌埠蔬菜批发市场'),
(8756299, 62, '甘肃定西市安定区马铃薯批发市场'),
(21451, 11, '北京城北回龙观商品交易市场'),
(20531, 11, '北京丰台区新发地农产品批发市场'),
(45559, 34, '安徽和县皖江蔬菜批发大市场'),
(20859, 34, '安徽合肥周谷堆农产品批发市场'),
(20799, 35, '福建福鼎闽浙边界农贸中心市场'),
(45539, 35, '福建同安闽南果蔬批发市场'),
(2576518, 45, '广西南宁五里亭蔬菜批发市场'),
(20992, 45, '广西田阳农副产品综合批发市场'),
(21124, 62, '甘肃靖远县瓜果蔬菜批发市场'),
(15001931, 62, '甘肃酒泉春光农产品市场'),
(20532, 11, '北京京丰岳各庄农副产品批发市场'),
(20543, 11, '北京市锦绣大地农副产品批发市场'),
(70801139, 44, '佛山中南农产品交易中心'),
(45271, 44, '广东东莞大京九农副产品中心批发市场'),
(45544, 34, '安徽六安裕安区紫竹林农产品批发市场'),
(20849, 34, '安徽马鞍山安民农副产品批发交易市场'),
(20819, 35, '海峡农副产品批发物流中心'),
(20989, 45, '广西新柳邕农产品批发市场有限公司'),
(21120, 62, '甘肃秦安县果品市场'),
(45682, 62, '甘肃省陇西县首阳镇蔬菜果品批发市场'),
(21119, 62, '甘肃省武山县洛门蔬菜批发市场'),
(20546, 11, '北京市锦绣大地玉泉路粮油批发市场'),
(20548, 11, '北京市日上综合商品批发市场'),
(20835, 44, '广东东莞果菜副食交易市场'),
(45296, 44, '广东江门市水产冻品副食批发市场'),
(20776, 44, '广东江门市新会区水果食品批发市场有限公司'),
(21047, 52, '贵州贵阳市五里冲农副产品批发市场'),
(21063, 52, '贵州铜仁地区玉屏畜禽产地批发市场'),
(20840, 34, '安徽省阜阳农产品中心批发市场'),
(20822, 34, '安徽舒城蔬菜大市场'),
(20595, 41, '河南安阳豫北蔬菜批发市场'),
(20619, 41, '河南三门峡西原店蔬菜批发市场'),
(2550066, 62, '甘肃腾胜农产品集团'),
(21121, 62, '甘肃天水瀛池果菜批发市场'),
(20536, 11, '北京市通州八里桥农产品中心批发市场'),
(20551, 11, '北京顺义区顺鑫石门农产品批发市场'),
(2547920, 13, '沧州红枣交易市场'),
(9348019, 13, '荷花坑批发市场'),
(20754, 44, '广东汕头农副产品批发中心'),
(20742, 44, '广东省广州市江南农副产品市场'),
(21055, 52, '贵州遵义坪丰农副产综合批发市场'),
(21052, 52, '贵州遵义市虾子辣椒批发市场'),
(20825, 34, '安徽亳州蔬菜批发市场'),
(45482, 34, '安徽濉溪县中瑞农副产品批发市场'),
(2547955, 42, '鄂襄樊蔬菜批发市场'),
(20687, 42, '湖北洪湖市农贸市场'),
(20632, 41, '河南商丘市农产品中心批发市场'),
(20614, 41, '河南省濮阳市王助蔬菜瓜果批发市场'),
(21129, 62, '兰州大青山蔬菜瓜果批发市场'),
(20620, 13, '河北保定工农路蔬菜果品批发市场'),
(45060, 13, '河北沧州市红枣批发市场'),
(20926, 23, '黑龙江哈尔滨哈达果菜批发市场有限公司'),
(2604441, 23, '黑龙江鹤岗万圃源蔬菜批发市场'),
(32370712, 44, '阳春市三农生猪猪苗批发市场'),
(9060946, 34, '安徽砀山农产品中心惠丰批发市场'),
(70759091, 34, '蚌埠海吉星农产品物流有限公司'),
(20897, 22, '长春蔬菜中心批发市场'),
(20692, 42, '湖北黄冈黄州商城蔬菜批发市场'),
(8756123, 42, '湖北荆州两湖平原农产品交易物流中心'),
(20628, 41, '河南新野县蔬菜批发交易市场'),
(2547851, 41, '河南信阳市平桥区豫信花生制品有限公司'),
(20728, 43, '湖南常德甘露寺蔬菜批发市场'),
(20704, 43, '湖南长沙红星农副产品大市场'),
(20615, 13, '河北邯郸(魏县)天仙果品农贸批发交易市场'),
(20654, 13, '河北衡水市东明蔬菜批发市场'),
(20938, 23, '黑龙江牡丹江市蔬菜批发市场'),
(20929, 23, '齐齐哈尔中心批发市场'),
(20777, 36, '江西赣州南北蔬菜大市场'),
(45528, 36, '江西九江市浔阳蔬菜批发大市场'),
(45651, 22, '吉林长春果品中心批发市场'),
(20698, 42, '湖北潜江市江汉农产品大市场'),
(20673, 42, '湖北省鄂州市蟠龙蔬菜批发交易市场'),
(20582, 41, '河南郑州毛庄蔬菜批发市场'),
(20584, 41, '河南郑州市农产品物流配送中心'),
(37576569, 32, '大丰市丰收大地农产品价格信息中心'),
(20958, 32, '江苏常州宣塘桥水产品交易市场'),
(2543746, 43, '湖南长沙马王堆蔬菜批发市场'),
(20716, 43, '湖南衡阳西园蔬菜批发市场'),
(20599, 13, '河北乐亭县冀东果蔬批发市场'),
(20613, 13, '河北秦皇岛(昌黎)农副产品批发市场'),
(20779, 15, '呼和浩特市东瓦窑批发市场'),
(2543558, 15, '内蒙古包头市友谊蔬菜批发市场'),
(20784, 36, '江西乐平市蔬菜开发总公司'),
(20792, 36, '江西南昌农产品中心批发市场'),
(20765, 36, '江西上饶市赣东北农产品批发大市场'),
(20899, 22, '吉林长春江山绿特优农产品储运批发市场'),
(20909, 22, '吉林辽源市物流园区仙城水果批发市场'),
(20664, 42, '湖北省黄石市农副产品批发交易公司'),
(20668, 42, '湖北十堰市堰中蔬菜批发市场'),
(20661, 42, '湖北武汉白沙洲农副产品大市场'),
(2547980, 41, '豫南阳果品批发交易中心'),
(20962, 32, '江苏丰县南关农贸市场'),
(20966, 32, '江苏淮海蔬菜批发市场'),
(20869, 21, '大连双兴批发市场'),
(20876, 21, '辽宁鞍山宁远农产品批发市场'),
(20719, 43, '湖南邵阳市江北农产品大市场'),
(20736, 43, '湖南省吉首市蔬菜果品批发大市场'),
(20733, 43, '湖南益阳市团洲蔬菜批发市场'),
(20610, 13, '河北秦皇岛海阳农副产品批发市场'),
(20660, 13, '河北饶阳县瓜菜果品交易市场'),
(20651, 13, '河北三河市建兴农副产品批发市场'),
(45134, 63, '青海省西宁市海湖路蔬菜瓜果综合批发市场'),
(20801, 15, '内蒙古赤峰西城蔬菜批发市场'),
(45527, 36, '江西永丰县蔬菜中心批发市场'),
(15060112, 36, '南方粮食交易市场'),
(45646, 22, '吉林松原市三井子杂粮杂豆产地批发市场'),
(2550029, 42, '湖北孝感市南大批发市场'),
(21051, 64, '宁夏银川市北环批发市场'),
(21045, 64, '吴忠市鑫鲜农副产品市场有限公司'),
(45591, 32, '江苏建湖水产批发市场'),
(20959, 32, '江苏凌家塘农副产品批发市场'),
(20969, 32, '江苏无锡朝阳市场'),
(8763807, 21, '辽宁阜新市瑞轩蔬菜农副产品综合批发市场'),
(2576573, 21, '辽宁省朝阳果菜批发市场'),
(20723, 43, '湖南岳阳花板桥批发市场'),
(45276, 13, '河北省邯郸市(馆陶)金凤禽蛋农贸批发市场'),
(45328, 13, '河北省怀来县京西果菜批发市场'),
(2550347, 14, '晋城绿盛农业技术开发有限公司'),
(2576593, 14, '晋新绛蔬菜批发市场'),
(45117, 63, '青海省西宁市仁杰粮油批发市场'),
(2576564, 15, '内蒙古美通食品批发市场'),
(20670, 42, '湖北宜昌金桥蔬菜果品批发市场'),
(20690, 42, '湖北浠水市城北农产品批发大市场'),
(20756, 37, '济南七里堡蔬菜综合批发市场'),
(20747, 37, '青岛抚顺路蔬菜副食品批发市场'),
(2576431, 32, '江苏无锡天鹏集团公司'),
(20965, 32, '江苏徐州七里沟农副产品中心'),
(49319130, 21, '中国北方杂粮加工物流中心'),
(45807, 13, '河北省威县瓜菜批发市场'),
(2576544, 13, '河北省永年县南大堡市场'),
(20576, 13, '石家庄桥西蔬菜中心批发市场'),
(20547, 31, '上海农产品中心批发市场有限公司'),
(2576584, 14, '晋运城果品中心市场'),
(45065, 14, '山西长治市金鑫瓜果批发市场'),
(20653, 42, '武汉市皇经堂批发市场'),
(21041, 61, '陕西汉中过街楼蔬菜批发市场'),
(45669, 61, '陕西西安朱雀农产品交易中心'),
(22346051, 37, '青岛黄河路农产品批发市场'),
(20652, 37, '山东滨州市鲁北无公害蔬菜批发市场'),
(45612, 32, '江苏扬州联谊农副产品批发市场'),
(20968, 32, '江苏宜兴蔬菜副食品批发市场'),
(8763836, 12, '天津范庄子蔬菜批发市场'),
(20542, 31, '上海市江桥批发市场'),
(20707, 14, '山西长治市紫坊农副产品综合交易市场'),
(21053, 61, '陕西咸阳市新阳光农副产品批发市场'),
(45432, 37, '山东德州黑马农产品批发市场'),
(21010, 51, '四川成都龙泉聚和果蔬菜交易中心'),
(8755899, 32, '南京高淳县水产批发市场有限公司'),
(22346058, 32, '南京农副产品物流中心'),
(9348188, 99, '新疆兵团农二师库尔勒市孔雀农副产品综合批发市场'),
(20553, 12, '天津何庄子批发市场'),
(20556, 12, '天津市东丽区金钟蔬菜市场'),
(20741, 14, '山西汾阳市晋阳农副产品批发市场'),
(20712, 14, '山西晋城绿欣农产品批发市场'),
(20697, 14, '山西省大同市南郊区振华蔬菜批发市场'),
(21048, 61, '陕西泾阳县云阳蔬菜批发市场'),
(32902062, 61, '西部欣桥农产品物流中心市场'),
(20674, 37, '山东肥城蔬菜批发市场'),
(20639, 37, '山东冠县社庄江北第一蔬菜批发市场'),
(2604461, 37, '山东济南市堤口果品批发市场'),
(21006, 51, '四川成都西部禽蛋批发市场'),
(8757132, 51, '四川广安邻水县农产品交易中心'),
(20972, 32, '南京紫金山批发市场'),
(20956, 32, '苏州市南环桥农副产品批发市场'),
(45195, 53, '云南省呈贡县龙城蔬菜批发市场'),
(32904608, 53, '云南省元谋县蔬菜批发市场'),
(8755761, 12, '天津市韩家墅农产品批发市场'),
(20555, 12, '天津市武清区大沙河蔬菜批发市场'),
(9513388, 14, '山西省汇隆商城'),
(20766, 14, '山西省临汾市襄汾县农副产品批发市场'),
(21015, 65, '新疆博乐市农五师三和市场'),
(20689, 37, '山东金乡县蔬菜批发市场'),
(19982077, 37, '山东匡山农产品综合交易市场'),
(45218, 51, '四川汉源县九襄农产品批发市场'),
(21036, 51, '四川凉山州会东县堵格乡牲畜交易市场'),
(21081, 53, '云南通海金山蔬菜批发市场'),
(20571, 12, '天津市西青区当城蔬菜批发市场'),
(20570, 12, '天津市西青区红旗农贸批发市场'),
(20762, 14, '山西省临汾市尧丰农副产品批发市场'),
(8763884, 14, '山西省吕梁离石马茂庄农贸批发市场'),
(45088, 65, '新疆米泉通汇农产品批发市场'),
(20985, 65, '新疆石河子西部绿珠果蔬菜批发市场'),
(20633, 37, '山东临邑县临南蔬菜大市场'),
(20700, 37, '山东龙口果蔬批发市场'),
(20662, 37, '山东宁津县东崔蔬菜市场合作社'),
(45569, 33, '杭州农副产品物流中心'),
(20885, 33, '嘉兴水果市场'),
(15002168, 51, '四川凉山州西昌市广平农副土特产品市场'),
(21019, 51, '四川绵阳市高水蔬菜批发市场'),
(20717, 14, '山西省朔州市朔城区大运蔬菜批发市场'),
(20731, 14, '山西朔州市应县南河种蔬菜批发市场'),
(21028, 65, '新疆吐鲁番盛达葡萄干市场'),
(2576419, 65, '新疆维吾尔自治区克拉玛依农副产品批发市场'),
(20677, 37, '山东宁阳县白马蔬菜批发市场'),
(20734, 37, '山东青岛城阳蔬菜水产品批发市场'),
(19639279, 50, '新大兴·国际农副产品交易中心'),
(45217, 50, '重庆观农贸批发市场'),
(15001796, 33, '宁波江北名特优农副产品批发交易市场'),
(20880, 33, '浙江嘉善浙北果蔬菜批发交易'),
(2549825, 51, '四川南充川北农产品批发市场'),
(45233, 51, '四川省成都市农产品批发中心'),
(20693, 14, '山西太原市城东利民果菜批发市场'),
(20746, 14, '山西孝义蔬菜批发交易市场'),
(8763855, 65, '新疆乌尔禾蔬菜批发市场'),
(21035, 65, '新疆乌鲁木齐北园春批发市场'),
(21033, 65, '新疆乌鲁木齐市凌庆蔬菜果品有限公司'),
(20743, 37, '山东青岛莱西东庄头蔬菜批发'),
(20732, 37, '山东青岛平度市南村蔬菜批发市场'),
(70810114, 50, '重庆双福国际农贸城'),
(20884, 33, '浙江嘉兴蔬菜批发交易市场'),
(45586, 33, '浙江宁波市蔬菜副食品批发交易市场'),
(8757171, 51, '四川省江油仔猪批发市场'),
(21014, 51, '四川泸州仔猪批发市场'),
(20735, 14, '山西忻州市五台县东冶镇蔬菜瓜果批发市场'),
(20702, 14, '山西阳泉蔬菜瓜果批发市场'),
(45078, 65, '新疆焉耆县光明农副产品综合批发市场'),
(20995, 65, '新疆伊犁哈萨克族自治州霍城县界梁子66团农贸市场'),
(20740, 37, '山东青岛市沧口蔬菜副食品批发市场'),
(20667, 37, '山东省威海市农副产品批发市场'),
(20904, 33, '浙江农都农副产品批发市场'),
(20877, 33, '浙江绍兴蔬菜果品批发交易中心'),
(20721, 14, '山西右玉玉羊批发市场'),
(20726, 14, '山西运城市蔬菜批发市场'),
(2550411, 14, '太原市河西农副产品市场'),
(20663, 37, '山东省威海市水产品批发市场'),
(20722, 37, '山东省淄博市鲁中果品批发市场'),
(20907, 33, '浙江省杭州笕桥蔬菜批发交易市场'),
(45578, 33, '浙江省金华农产品批发市场'),
(20895, 33, '浙江温州菜篮子集团'),
(20696, 37, '山东寿光农产品物流园'),
(20749, 37, '山东章丘刁镇蔬菜批发市场'),
(20871, 33, '浙江义乌农贸城'),
(20715, 37, '山东滕州蔬菜批发市场');
/*!40000 ALTER TABLE `market` ENABLE KEYS */;
-- 导出 表 mofcom.product 结构
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`product_id`,`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='产品';
-- 正在导出表 mofcom.product 的数据:0 rows
/*!40000 ALTER TABLE `product` DISABLE KEYS */;
INSERT INTO `product` (`product_id`, `category_id`, `name`) VALUES
(13245, 13079, '鸡蛋'),
(13233, 13079, '猪肉(白条猪)'),
(16027054, 13079, '内三元母猪'),
(8754711, 13080, '活草鱼'),
(8754710, 13080, '白鲢活鱼'),
(13103, 13076, '香蕉'),
(13097, 13076, '富士苹果'),
(16027050, 13079, '内三元生猪'),
(16027052, 13079, '内三元仔猪'),
(8754722, 13080, '活鲫鱼'),
(8754705, 13080, '活鲤鱼'),
(13095, 13073, '面粉'),
(13106, 13076, '西瓜'),
(13107, 13076, '哈密瓜'),
(13235, 13079, '牛肉'),
(16027055, 13079, '外三元母猪'),
(13137, 13080, '黄鳝'),
(13144, 13080, '武昌鱼'),
(13096, 13073, '绿豆'),
(13119, 13073, '色拉油'),
(20410, 13075, '黄瓜'),
(20414, 13075, '西红柿'),
(13105, 13076, '菠萝'),
(15002880, 13076, '伽师瓜'),
(16027051, 13079, '外三元生猪'),
(16027053, 13079, '外三元仔猪'),
(13237, 13079, '羊肉'),
(13118, 13080, '带鱼'),
(13134, 13080, '黑鱼'),
(13151, 13080, '鲈鱼'),
(13087, 13073, '大豆'),
(8754698, 13073, '一级豆油(散装)'),
(20409, 13075, '大白菜'),
(20413, 13075, '土豆'),
(20411, 13075, '芹菜'),
(13139, 13076, '巨峰葡萄'),
(13098, 13076, '蜜桔'),
(13240, 13079, '白条鸡'),
(13248, 13079, '鸭蛋'),
(13135, 13080, '泥鳅'),
(15011220, 13080, '小黄鱼'),
(13099, 13073, '红小豆'),
(13811, 13075, '青椒'),
(13515, 13075, '韭菜'),
(13102, 13076, '鸭梨'),
(13201, 13076, '猕猴桃'),
(13243, 13079, '活鸡'),
(13257, 13079, '乌鸡'),
(15052322, 13080, '章鱼'),
(15002873, 13080, '沼虾'),
(8754673, 13073, '粳米(普通)'),
(8754689, 13073, '菜油(散装)'),
(13104, 13073, '标准粉'),
(13509, 13075, '茄子'),
(15637, 13075, '大葱'),
(15052348, 13076, '白桃'),
(15060784, 13076, '红马奶葡萄干'),
(13310, 13079, '猪心'),
(15060767, 13079, '基础母牛(500斤左右)'),
(13124, 13080, '大带鱼'),
(13179, 13080, '人工甲鱼'),
(15060703, 13073, 'S33(油葵)'),
(15052308, 13073, '高粱'),
(15060735, 13073, '黑中片籽瓜子'),
(13520, 13075, '大蒜'),
(20408, 13075, '白萝卜'),
(15641, 13075, '生姜'),
(15052307, 13076, '金丝枣'),
(15060639, 13076, '菱角'),
(15058263, 13079, '麻花公鸡'),
(13312, 13079, '猪肝'),
(13313, 13079, '猪肚'),
(13140, 13080, '养殖鲶鱼'),
(13129, 13080, '大黄鱼'),
(15052298, 13080, '马鲅鱼'),
(15060369, 13073, '西葫芦白瓜籽(炒货)'),
(13086, 13073, '玉米'),
(15060184, 13073, '芸豆'),
(15638, 13075, '葱头'),
(8753469, 13075, '菜苔'),
(13514, 13075, '菜花'),
(15059625, 13076, '龙眼(储良)'),
(15059632, 13076, '龙眼(石硖)'),
(13296, 13079, '猪后腿肌肉'),
(15092423, 13079, '三黄公鸡'),
(13328, 13079, '三黄鸡'),
(13127, 13080, '小带鱼'),
(13713, 13080, '小黄花鱼'),
(13168, 13080, '牛蛙'),
(13084, 13073, '大米'),
(13094, 13073, '花生油'),
(13113, 13073, '香油'),
(13512, 13075, '胡萝卜'),
(13504, 13075, '香菜'),
(15060783, 13076, '绿马奶葡萄干'),
(15052357, 13076, '芒果(红象牙9号)'),
(13261, 13079, '活鸭'),
(13298, 13079, '肥膘'),
(13189, 13080, '基围虾'),
(13093, 13080, '草鱼'),
(13117, 13080, '鲫鱼'),
(13108, 13073, '特一粉'),
(13125, 13073, '花生仁'),
(15643, 13075, '冬瓜'),
(13510, 13075, '豆角'),
(13508, 13075, '菠菜'),
(15052363, 13076, '芒果(农院3号)'),
(15052367, 13076, '芒果(台农一号)'),
(13293, 13079, '猪前腿肌肉'),
(13314, 13079, '猪肺'),
(13089, 13080, '鲢鱼'),
(13146, 13080, '罗非鱼'),
(13091, 13080, '鲤鱼'),
(8754660, 13073, '籼米(晚籼米)'),
(13122, 13073, '花生'),
(13517, 13075, '蒜薹'),
(20416, 13075, '油菜'),
(13511, 13075, '洋白菜'),
(13197, 13076, '柚'),
(13150, 13076, '脐橙'),
(13294, 13079, '猪大排肌肉'),
(13317, 13079, '猪大肠'),
(13289, 13079, '猪颈背肌肉'),
(13131, 13080, '大平鱼'),
(13147, 13080, '活鳜鱼'),
(13115, 13073, '棕榈油'),
(13090, 13073, '豆油'),
(13088, 13073, '菜油'),
(13366, 13075, '西葫芦'),
(13495, 13075, '生菜'),
(13133, 13076, '香梨'),
(13244, 13076, '红提子'),
(13316, 13079, '猪肾'),
(13329, 13079, '老母鸡'),
(13132, 13080, '小平鱼'),
(13156, 13080, '白鳝鱼'),
(13111, 13073, '特二粉'),
(13085, 13073, '粳米'),
(13503, 13075, '莲藕'),
(15642, 13075, '莴笋'),
(15640, 13075, '绿尖椒'),
(13228, 13076, '芒果'),
(13226, 13076, '龙眼(桂圆)'),
(8754641, 13079, '活鹅'),
(13253, 13079, '仔猪'),
(13121, 13080, '对虾'),
(13191, 13080, '草虾'),
(8754700, 13073, '糯米'),
(13083, 13073, '籼米'),
(8756521, 13073, '葵花籽'),
(13499, 13075, '苦瓜'),
(13519, 13075, '南瓜'),
(13206, 13076, '桃子'),
(13167, 13076, '草莓'),
(13266, 13079, '活兔'),
(13250, 13079, '毛猪'),
(13175, 13080, '梭子蟹'),
(13149, 13080, '虹鳟鱼'),
(8756539, 13073, '黑大片葵花籽'),
(9060839, 13073, '晚籼稻'),
(15060812, 13075, '条形辣椒干(二荆条)'),
(15060815, 13075, '条形辣椒干(小米椒)'),
(15060819, 13075, '圆形辣椒干(草莓椒)'),
(13224, 13076, '甘蔗'),
(13259, 13079, '柴鸡'),
(13165, 13080, '扇贝'),
(9060841, 13073, '早籼稻'),
(9060826, 13073, '芝麻(白芝麻)'),
(15060821, 13075, '圆形辣椒干(子弹头)'),
(13365, 13075, '香菇'),
(13155, 13076, '椪柑'),
(15002905, 13076, '广柑'),
(13153, 13076, '芦柑'),
(13304, 13079, '黄牛'),
(13255, 13079, '肥猪'),
(13204, 13080, '蛏子'),
(13200, 13080, '蛤蜊'),
(16007828, 13073, '白芝麻'),
(13370, 13075, '小白菜'),
(13217, 13075, '平菇'),
(13498, 13075, '丝瓜'),
(15092406, 13076, '金龙芒'),
(15092392, 13076, '芒果(农院5号)'),
(15092420, 13079, '黄花母鸡'),
(15060257, 13079, '蛇'),
(13196, 13080, '澳洲龙虾'),
(13182, 13080, '野生甲鱼'),
(13159, 13080, '海参'),
(13497, 13075, '西兰花'),
(13214, 13075, '山药'),
(13123, 13076, '雪梨'),
(13185, 13076, '红枣'),
(13319, 13079, '猪小肠'),
(13268, 13079, '山羊'),
(13152, 13080, '石斑鱼'),
(13177, 13080, '青蟹'),
(13141, 13080, '野生鲶鱼'),
(13225, 13075, '茼蒿'),
(13374, 13075, '西洋芹'),
(13164, 13076, '香瓜'),
(13260, 13076, '山竹'),
(13263, 13079, '红皮鸡蛋'),
(8754625, 13079, '猪皮'),
(13160, 13080, '海鳗'),
(8754743, 13080, '花鲢活鱼'),
(13518, 13075, '蒜苗'),
(13367, 13075, '小葱'),
(13130, 13076, '酥梨'),
(13176, 13076, '核桃'),
(13192, 13076, '柿子'),
(13264, 13079, '白皮鸡蛋'),
(13308, 13079, '绵羊'),
(13172, 13080, '江蟹'),
(13202, 13080, '海蛎'),
(13491, 13075, '芋头'),
(13496, 13075, '油麦菜'),
(13236, 13076, '蛇果'),
(13215, 13076, '油桃'),
(13307, 13079, '育肥牛'),
(13306, 13079, '水牛'),
(13186, 13080, '鲍鱼'),
(13183, 13080, '乌龟'),
(13223, 13075, '红椒'),
(13368, 13075, '豇豆'),
(13246, 13076, '柠檬'),
(15060243, 13076, '黄河蜜'),
(13239, 13079, '驴肉'),
(13351, 13079, '肉羊'),
(13170, 13080, '田鸡'),
(13154, 13080, '加吉鱼'),
(8754735, 13080, '鲅鱼'),
(13208, 13075, '红萝卜'),
(13494, 13075, '空心菜'),
(13230, 13076, '石榴'),
(13143, 13076, '玫瑰香葡萄'),
(13349, 13079, '肉牛'),
(13343, 13079, '活驴'),
(13171, 13080, '肉蟹'),
(13209, 13080, '紫菜'),
(13486, 13075, '荷兰豆'),
(13218, 13075, '金针菇'),
(13158, 13076, '伊丽沙白瓜'),
(13100, 13076, '甜橙'),
(13337, 13079, '肉马'),
(13326, 13079, '肉鸡苗(只)'),
(13198, 13080, '美洲龙虾'),
(13212, 13080, '鲨鱼'),
(13516, 13075, '韭黄'),
(13092, 13076, '国光苹果'),
(13241, 13076, '青提子'),
(13332, 13079, '骡子'),
(13193, 13080, '土虾'),
(13203, 13080, '淡菜(鲜)'),
(15639, 13075, '茴香'),
(13231, 13075, '黄豆芽'),
(13145, 13076, '马奶葡萄'),
(13194, 13076, '荔枝'),
(13333, 13079, '耕骡'),
(13339, 13079, '耕马'),
(13711, 13080, '野生大黄鱼'),
(13207, 13080, '鳗鱼干'),
(13487, 13075, '长茄子'),
(13493, 13075, '毛豆'),
(15002887, 13076, '荔枝(白腊)'),
(15002889, 13076, '荔枝(桂味)'),
(13344, 13079, '耕驴'),
(13712, 13080, '深水网箱大黄鱼'),
(13163, 13080, '真鲷'),
(13242, 13075, '绿豆芽'),
(13489, 13075, '尖椒'),
(13490, 13075, '红尖椒'),
(15002886, 13076, '荔枝(黑叶)'),
(8754866, 13076, '荔枝(妃子笑)'),
(13173, 13076, '山楂'),
(13303, 13079, '鸡苗(只)'),
(13353, 13079, '黄花公鸡(只)'),
(13157, 13080, '鮸鱼'),
(16007643, 13080, '大黄花鱼'),
(13501, 13075, '茭白'),
(13488, 13075, '圆茄子'),
(13180, 13076, '板栗'),
(13169, 13076, '樱桃'),
(13249, 13076, '红毛丹'),
(13320, 13079, '猪皮(张)'),
(13336, 13079, '役马'),
(13347, 13079, '驴板肠'),
(16026950, 13080, '鳊鱼'),
(13222, 13075, '瓠子'),
(13211, 13075, '佛手瓜'),
(13220, 13076, '杏子'),
(13238, 13076, '青苹果'),
(13270, 13079, '山羯羊'),
(13286, 13079, '山母羊'),
(13513, 13075, '木耳菜'),
(20415, 13075, '樱桃西红柿'),
(13114, 13076, '黄元帅苹果'),
(13258, 13076, '布朗'),
(13221, 13076, '李子'),
(13345, 13079, '驴皮(张)'),
(13301, 13079, '鸭苗(只)'),
(13229, 13075, '苋菜'),
(13484, 13075, '青冬瓜'),
(13256, 13076, '人参果'),
(13252, 13076, '杨桃'),
(13372, 13075, '韭苔'),
(13120, 13076, '苹果梨'),
(15092411, 13076, '大枣'),
(13371, 13075, '韭菜花'),
(13184, 13075, '鸡腿菇'),
(13373, 13075, '芥菜'),
(13138, 13076, '丰水梨'),
(15002896, 13076, '乔纳金苹果'),
(13109, 13076, '红星苹果'),
(15644, 13075, '青笋'),
(20412, 13075, '水萝卜'),
(13500, 13075, '菜瓜'),
(13112, 13076, '黄香蕉苹果'),
(13188, 13076, '椰子'),
(13483, 13075, '香椿'),
(13502, 13075, '荸荠'),
(13219, 13075, '慈菇'),
(13210, 13076, '蟠桃'),
(22216, 13076, '冬枣'),
(13174, 13075, '黑木耳'),
(18501, 13075, '玉米棒'),
(8754795, 13076, '葡萄干(通货)'),
(8754813, 13076, '麒麟西瓜'),
(20419, 13075, '良薯'),
(13187, 13075, '茶树菇'),
(13128, 13076, '白梨'),
(13136, 13076, '杨梅'),
(13199, 13075, '草菇'),
(13485, 13075, '光皮黄瓜'),
(15646, 13075, '冬笋'),
(13110, 13076, '秦冠苹果'),
(13267, 13076, '枇杷'),
(13227, 13075, '辣椒干'),
(13162, 13075, '银耳'),
(8754804, 13076, '特小凤西瓜'),
(8754833, 13076, '黑美人西瓜'),
(13195, 13075, '杏鲍菇'),
(15645, 13075, '竹笋'),
(8754773, 13076, '网纹瓜'),
(13116, 13076, '常山胡柚'),
(13181, 13075, '白灵菇'),
(8754028, 13075, '豌豆'),
(20421, 13076, '沙田柚'),
(8754842, 13076, '嘎拉苹果'),
(8754761, 13076, '红香蕉苹果'),
(13178, 13075, '凤尾菇'),
(8753869, 13075, '豌豆尖'),
(8754856, 13076, '甜瓜'),
(8754776, 13076, '早春红玉瓜'),
(15060236, 13075, '莲蓬'),
(8753866, 13075, '折耳根'),
(13142, 13076, '龙眼葡萄'),
(8754784, 13076, '雪莲果'),
(13492, 13075, '福鼎芋'),
(13190, 13075, '猴头菇'),
(8754822, 13076, '京欣西瓜'),
(8754791, 13076, '葡萄干(特级)'),
(13166, 13075, '毛木耳'),
(13364, 13075, '菜用仙人掌'),
(13148, 13076, '象牙芒'),
(8756564, 13076, '砂糖橘'),
(13205, 13075, '枸杞二级'),
(20420, 13075, '菜薹'),
(13161, 13076, '华兰氏瓜'),
(8754770, 13076, '黄金瓜'),
(8756566, 13076, '年桔'),
(8754211, 13075, '白蒜5.0公分'),
(8754197, 13075, '红蒜5.0公分'),
(8754876, 13076, '芒果(金煌芒)'),
(8754846, 13076, '白糖罐甜瓜'),
(16027048, 13075, '蘑菇'),
(8754222, 13075, '白蒜6.0公分'),
(13126, 13076, '红肖梨'),
(13262, 13076, '芒果(象芽22号)'),
(16026976, 13075, '马蹄'),
(9060807, 13075, '红蒜6.0公分'),
(13234, 13076, '石榴(大籽石榴)'),
(20427, 13076, '芒果(红象芽9号)'),
(22219, 13076, '干枣'),
(16007742, 13075, '心里美萝卜'),
(20428, 13075, '萝卜丝'),
(22215, 13076, '鲜枣'),
(9060834, 13076, '葡萄干(二级)'),
(9060853, 13075, '枸杞一级'),
(9060833, 13076, '葡萄干(一级)'),
(16007932, 13076, '海棠果'),
(16026921, 13076, '花盖梨'),
(16007602, 13076, '菱枣'),
(16007628, 13076, '木瓜'),
(16007712, 13076, '葡萄'),
(16007579, 13076, '青枣'),
(16007912, 13076, '香水梨');
/*!40000 ALTER TABLE `product` ENABLE KEYS */;
-- 导出 表 mofcom.product_price_history 结构
CREATE TABLE IF NOT EXISTS `product_price_history` (
`date` date DEFAULT NULL,
`product` varchar(50) DEFAULT NULL,
`price` varchar(50) DEFAULT NULL,
`market` varchar(50) DEFAULT NULL,
UNIQUE KEY `date_product_market` (`date`,`product`,`market`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='价格历史';
-- 正在导出表 mofcom.product_price_history 的数据:0 rows
/*!40000 ALTER TABLE `product_price_history` DISABLE KEYS */;
/*!40000 ALTER TABLE `product_price_history` ENABLE KEYS */;
-- 导出 表 mofcom.region 结构
CREATE TABLE IF NOT EXISTS `region` (
`region_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`region_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='地区';
-- 正在导出表 mofcom.region 的数据:0 rows
/*!40000 ALTER TABLE `region` DISABLE KEYS */;
INSERT INTO `region` (`region_id`, `name`) VALUES
(34, '安徽省'),
(11, '北京市'),
(35, '福建省'),
(62, '甘肃省'),
(44, '广东省'),
(45, '广西壮族自治区'),
(52, '贵州省'),
(46, '海南省'),
(13, '河北省'),
(41, '河南省'),
(23, '黑龙江省'),
(42, '湖北省'),
(43, '湖南省'),
(22, '吉林省'),
(32, '江苏省'),
(36, '江西省'),
(21, '辽宁省'),
(15, '内蒙古自治区'),
(64, '宁夏回族自治区'),
(63, '青海省'),
(37, '山东省'),
(14, '山西省'),
(61, '陕西省'),
(31, '上海市'),
(51, '四川省'),
(12, '天津市'),
(54, '西藏自治区'),
(99, '新疆建设兵团'),
(65, '新疆维吾尔自治区'),
(53, '云南省'),
(33, '浙江省'),
(50, '重庆市');
/*!40000 ALTER TABLE `region` ENABLE KEYS */;
-- 导出 表 mofcom.reptile 结构
CREATE TABLE IF NOT EXISTS `reptile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`spider_name` varchar(50) NOT NULL DEFAULT '0',
`url` varchar(200) NOT NULL,
`code` varchar(50) NOT NULL,
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=39 DEFAULT CHARSET=utf8 COMMENT='地址';
-- 正在导出表 mofcom.reptile 的数据:0 rows
/*!40000 ALTER TABLE `reptile` DISABLE KEYS */;
INSERT INTO `reptile` (`id`, `spider_name`, `url`, `code`, `create_time`) VALUES
(1, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml', '200', '2019-05-20 21:44:09'),
(2, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=13079', '200', '2019-05-20 21:44:11'),
(3, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=13080', '200', '2019-05-20 21:44:14'),
(4, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=13076', '200', '2019-05-20 21:44:16'),
(5, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=13073', '200', '2019-05-20 21:44:18'),
(6, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_craft_index=13075', '200', '2019-05-20 21:44:21'),
(7, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=11', '200', '2019-05-20 21:44:24'),
(8, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=34', '200', '2019-05-20 21:44:28'),
(9, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=62', '200', '2019-05-20 21:44:31'),
(10, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=35', '200', '2019-05-20 21:44:34'),
(11, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=45', '200', '2019-05-20 21:44:37'),
(12, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=44', '200', '2019-05-20 21:44:41'),
(13, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=46', '200', '2019-05-20 21:44:43'),
(14, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=52', '200', '2019-05-20 21:44:46'),
(15, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=41', '200', '2019-05-20 21:44:48'),
(16, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=13', '200', '2019-05-20 21:44:50'),
(17, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=42', '200', '2019-05-20 21:44:54'),
(18, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=23', '200', '2019-05-20 21:44:57'),
(19, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=22', '200', '2019-05-20 21:45:01'),
(20, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=43', '200', '2019-05-20 21:45:04'),
(21, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=36', '200', '2019-05-20 21:45:08'),
(22, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=32', '200', '2019-05-20 21:45:10'),
(23, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=15', '200', '2019-05-20 21:45:14'),
(24, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=21', '200', '2019-05-20 21:45:17'),
(25, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=63', '200', '2019-05-20 21:45:20'),
(26, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=64', '200', '2019-05-20 21:45:22'),
(27, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=14', '200', '2019-05-20 21:45:25'),
(28, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=37', '200', '2019-05-20 21:45:27'),
(29, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=31', '200', '2019-05-20 21:45:30'),
(30, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=61', '200', '2019-05-20 21:45:34'),
(31, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=12', '200', '2019-05-20 21:45:37'),
(32, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=51', '200', '2019-05-20 21:45:39'),
(33, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=99', '200', '2019-05-20 21:45:42'),
(34, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=54', '200', '2019-05-20 21:45:44'),
(35, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=53', '200', '2019-05-20 21:45:48'),
(36, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=65', '200', '2019-05-20 21:45:51'),
(37, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=33', '200', '2019-05-20 21:45:55'),
(38, 'product_screen', 'http://nc.mofcom.gov.cn/channel/jghq2017/price_list.shtml?par_p_index=50', '200', '2019-05-20 21:45:59');
/*!40000 ALTER TABLE `reptile` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
5df5876435d4db5281af980d0ff9c2d1bc1d3715
|
[
"SQL",
"Python"
] | 38 |
Python
|
zheng-sun/scrapy
|
9655b82df46cf7d350386d913d657148bf7086a6
|
db19eca15fba1ae2c0b8bacecc9eb8413260c59d
|
refs/heads/master
|
<file_sep>package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import me.joba.pathtracercluster.pathtracer.material.DiffuseColoredMaterial;
/**
*
* @author balsfull
*/
public class DiffuseColoredMaterialSerializer extends Serializer<DiffuseColoredMaterial>{
@Override
public void write(Kryo kryo, Output output, DiffuseColoredMaterial t) {
output.writeDouble(t.getGrayScale());
output.writeDouble(t.getWavelength());
output.writeDouble(t.getDeviation());
}
@Override
public DiffuseColoredMaterial read(Kryo kryo, Input input, Class<? extends DiffuseColoredMaterial> type) {
double gray = input.readDouble();
double wav = input.readDouble();
double dev = input.readDouble();
return new DiffuseColoredMaterial(gray, wav, dev);
}
}<file_sep>package me.joba.pathtracercluster.client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import com.esotericsoftware.kryonet.util.TcpIdleSender;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import me.joba.pathtracercluster.NetworkRegistration;
import me.joba.pathtracercluster.Task;
import me.joba.pathtracercluster.packets.*;
import me.joba.pathtracercluster.pathtracer.PathTracer;
import me.joba.pathtracercluster.pathtracer.Scene;
import me.joba.pathtracercluster.pathtracer.Vector3;
import me.joba.pathtracercluster.pathtracer.render.Plotter;
import me.joba.pathtracercluster.pathtracer.render.ToneMapper;
/**
*
* @author balsfull
*/
public class NetworkListener extends Listener {
private final Server server;
private final PathTracer tracer;
private final Map<UUID, BlockingQueue<PacketServer02SendTask>> taskPacketQueue;
private final Map<UUID, BlockingQueue<PacketClient05TaskCompleted>> resultPacketQueue;
public NetworkListener(int port, PathTracer tracer) throws IOException {
server = new Server(16384, 16384) {
@Override
protected Connection newConnection () {
return new PathTracerConnection();
}
};
server.start();
server.bind(port);
NetworkRegistration.register(server);
server.addListener(this);
this.tracer = tracer;
this.taskPacketQueue = new ConcurrentHashMap<>();
this.resultPacketQueue = new ConcurrentHashMap<>();
}
public void sendCompletion(Task task) {
int size = 100;
int offset = 0;
List<PacketClient05TaskCompleted> taskFragments = new ArrayList<>();
Vector3[] cieVector = task.getPlotter().getCIEVector();
while(offset < cieVector.length) {
Vector3[] fragment = new Vector3[Math.min(size, cieVector.length - offset)];
System.arraycopy(cieVector, offset, fragment, 0, fragment.length);
taskFragments.add(new PacketClient05TaskCompleted(fragment, offset));
offset += fragment.length;
}
Connection connection = null;
for(Connection con : server.getConnections()) {
PathTracerConnection ptc = (PathTracerConnection)con;
if(ptc.isConnected() && ptc.serverId == task.getServerId()) {
connection = con;
break;
}
}
if(connection != null) {
Iterator<PacketClient05TaskCompleted> iter = taskFragments.iterator();
connection.addListener(new TcpIdleSender() {
@Override
protected Object next() {
if(!iter.hasNext()) return null;
return iter.next();
}
});
return;
}
BlockingQueue<PacketClient05TaskCompleted> queue = new LinkedBlockingQueue<>();
BlockingQueue<PacketClient05TaskCompleted> tmp = resultPacketQueue.putIfAbsent(task.getServerId(), queue);
if(tmp != null) {
queue = tmp;
}
queue.addAll(taskFragments);
}
public void sendInfo(int queueSize, int rayCount) {
server.sendToAllTCP(new PacketClient06Info(queueSize, rayCount));
}
static class PathTracerConnection extends Connection {
public UUID serverId;
}
private void queuePacket(PacketServer02SendTask packet) {
BlockingQueue<PacketServer02SendTask> queue = new LinkedBlockingQueue<>();
BlockingQueue<PacketServer02SendTask> tmp = taskPacketQueue.putIfAbsent(packet.getSceneId(), queue);
if(tmp != null) {
queue = tmp;
}
queue.add(packet);
}
@Override
public void connected(Connection c) {
System.out.println("Connected with " + c.getRemoteAddressTCP());
c.sendTCP(new PacketServer01Hello(null));
}
@Override
public void received(Connection c, Object o) {
PathTracerConnection ptc = (PathTracerConnection)c;
if(o instanceof PacketServer01Hello) {
PacketServer01Hello packet = (PacketServer01Hello)o;
if(ptc.serverId != null) {
c.close();
return;
}
ptc.serverId = packet.getServerId();
System.out.println("Received hello " + c.getRemoteAddressTCP() + ". UUID: " + ptc.serverId);
drainResultPacketQueue(ptc.serverId, c);
}
if(ptc.serverId == null) {
c.close();
return;
}
if(o instanceof PacketServer02SendTask) {
System.out.println("Received task " + c.getRemoteAddressTCP());
PacketServer02SendTask packet = (PacketServer02SendTask)o;
Scene scene = tracer.getScene(packet.getSceneId());
if(scene != null) {
Plotter plotter = new Plotter(scene.getWidth(), scene.getHeight());
Task task = new Task(scene, plotter, ptc.serverId, this, packet);
tracer.queueTask(task);
}
else {
queuePacket(packet);
c.sendTCP(new PacketClient03GetScene(packet.getSceneId()));
}
}
else if(o instanceof PacketServer04SendScene) {
System.out.println("Received scene " + c.getRemoteAddressTCP());
PacketServer04SendScene packet = (PacketServer04SendScene)o;
tracer.registerScene(packet.getSceneId(), packet.getScene());
drainTaskPacketQueue(packet.getSceneId(), ptc.serverId, packet.getScene());
}
}
private void drainResultPacketQueue(UUID serverId, Connection connection) {
Queue<PacketClient05TaskCompleted> queue = resultPacketQueue.get(serverId);
if(queue == null) return;
Iterator<PacketClient05TaskCompleted> iter = queue.iterator();
connection.addListener(new TcpIdleSender() {
@Override
protected Object next() {
if(!iter.hasNext()) return null;
return iter.next();
}
});
}
private void drainTaskPacketQueue(UUID sceneId, UUID serverId, Scene scene) {
Queue<PacketServer02SendTask> queue = taskPacketQueue.get(sceneId);
if(queue == null) return;
for(PacketServer02SendTask packet : queue) {
Plotter plotter = new Plotter(scene.getWidth(), scene.getHeight());
Task task = new Task(scene, plotter, serverId, this, packet);
tracer.queueTask(task);
}
}
}
<file_sep>package pathtracer;
import pathtracer.master.PathTracerMaster;
import pathtracer.slave.PathTracerSlave;
import pathtracer.standalone.PathTracerStandalone;
import pathtracer.material.BlackBodyRadiator;
import pathtracer.material.ColoredGlassMaterial;
import pathtracer.material.DiffuseColoredMaterial;
import pathtracer.material.DiffuseGrayMaterial;
import pathtracer.material.GlossyMaterial;
import pathtracer.material.Material;
import pathtracer.material.Radiator;
import pathtracer.render.Tracer;
import pathtracer.surface.Plane;
import pathtracer.surface.Sphere;
/**
*
* @author balsfull
*/
public class PathTracer {
public static int WIDTH = 512, HEIGHT = 512, THREADS = Runtime.getRuntime().availableProcessors();
public static void main(String[] args) throws Exception {
int mode = 0;
String[] sshList = new String[0];
for (int i = 0; i < args.length; i++) {
String key = args[i];
switch(key) {
case "--threads": {
THREADS = Integer.parseInt(args[i + 1]);
i++;
break;
}
case "--width":
case "-w": {
WIDTH = Integer.parseInt(args[i + 1]);
i++;
break;
}
case "--height":
case "-h": {
HEIGHT = Integer.parseInt(args[i + 1]);
i++;
break;
}
case "--batchsize": {
Tracer.PHOTON_COUNT = Integer.parseInt(args[i + 1]);
i++;
break;
}
case "--standalone": {
mode = 0; break;
}
case "--slave": {
mode = 1; break;
}
case "--master": {
mode = 2; break;
}
case "--sshList": {
sshList = args[i + 1].split(";");
i++;
break;
}
}
}
Scene scene = new Scene();
populateScene(scene);
scene.setCamera(createCamera());
scene.setTime(0);
switch (mode) {
case 0:
PathTracerStandalone.render(scene);
break;
case 1:
PathTracerSlave.start(scene);
break;
case 2:
PathTracerMaster.start(sshList);
break;
default:
break;
}
}
public static Camera createCamera() {
Vector3 position = new Vector3(0, -9, 0);
Quaternion orientation = new Quaternion(0, 10, 3, 0);
return new Camera(
position,
orientation,
Math.PI * 0.35,
4,
Double.MAX_VALUE,
0.01
);
}
public static void populateScene(Scene scene) {
Plane top = new Plane(new Vector3(0, 0, -10), new Vector3(0, 0, 1));
Plane bottom = new Plane(new Vector3(0, 0, 10), new Vector3(0, 0, 1));
Plane front = new Plane(new Vector3(0, -10, 0), new Vector3(0, 1, 0));
Plane back = new Plane(new Vector3(0, 10, 0), new Vector3(0, 1, 0));
Plane left = new Plane(new Vector3(10, 0, 0), new Vector3(1, 0, 0));
Plane right = new Plane(new Vector3(-10, 0, 0), new Vector3(1, 0, 0));
Material color1 = new DiffuseColoredMaterial(1, 400, 20);
Material color2 = new DiffuseColoredMaterial(1, 600, 40);
Material color3 = new DiffuseColoredMaterial(1, 500, 10);
Material diffuseFloor = new DiffuseGrayMaterial(0.8);
Material mirror = new GlossyMaterial(new DiffuseGrayMaterial(1), 0);
Material glossy = new GlossyMaterial(new DiffuseGrayMaterial(1), 0.8);
scene.addElement(new Element(top, mirror));
scene.addElement(new Element(bottom, diffuseFloor));
scene.addElement(new Element(front, color3));
scene.addElement(new Element(back, glossy));
scene.addElement(new Element(left, color1));
scene.addElement(new Element(right, color2));
//radiators
Sphere sunOne = new Sphere(new Vector3(0, 0, 0), 1);
Sphere sunTwo = new Sphere(new Vector3(7,5, -8), 2);
Radiator radiatorOne = new BlackBodyRadiator(6800, 8);
Radiator radiatorTwo = new BlackBodyRadiator(3000, 5);
scene.addElement(new Element(sunOne, radiatorOne));
scene.addElement(new Element(sunTwo, radiatorTwo));
//glass
Sphere glassOne = new Sphere(new Vector3(3, 9, 5), 0.5);
Sphere glassTwo = new Sphere(new Vector3(-2, 7, 4), 1.5);
Material glassGreen = new ColoredGlassMaterial(540, 40);
Material glassYellow = new ColoredGlassMaterial(570, 50);
scene.addElement(new Element(glassOne, glassGreen));
scene.addElement(new Element(glassTwo, glassYellow));
//mirrors
Sphere mirrorOne = new Sphere(new Vector3(-8, -4, -7), 0.8);
Sphere mirrorTwo = new Sphere(new Vector3(5, 3, -5), 3);
scene.addElement(new Element(mirrorOne, mirror));
scene.addElement(new Element(mirrorTwo, glossy));
//diffuse
Sphere diffuseOne = new Sphere(new Vector3(2, 0,-5), 2.5);
Material cyanDiffuse = new DiffuseColoredMaterial(1, 500, 30);
scene.addElement(new Element(diffuseOne, cyanDiffuse));
}
}
<file_sep>package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import me.joba.pathtracercluster.pathtracer.Quaternion;
/**
*
* @author balsfull
*/
public class QuaternionSerializer extends Serializer<Quaternion> {
@Override
public void write(Kryo kryo, Output output, Quaternion t) {
output.writeDouble(t.x);
output.writeDouble(t.y);
output.writeDouble(t.z);
output.writeDouble(t.w);
}
@Override
public Quaternion read(Kryo kryo, Input input, Class<? extends Quaternion> type) {
double x = input.readDouble();
double y = input.readDouble();
double z = input.readDouble();
double w = input.readDouble();
return new Quaternion(x, y, z, w);
}
}
<file_sep>package me.joba.pathtracercluster;
import me.joba.pathtracercluster.client.ClientMain;
import me.joba.pathtracercluster.server.ServerMain;
/**
*
* @author balsfull
*/
public class Main {
public static void main(String[] args) throws Exception {
if(args.length >= 1 && args[0].equals("--server")) {
ServerMain.main(args);
}
else {
ClientMain.main(args);
}
}
}
<file_sep>package pathtracer;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
import java.util.function.DoubleFunction;
import java.util.stream.Collectors;
/**
*
* @author balsfull
*/
public class Scene {
private Element[] elements;
private Camera camera;
private final Map<UUID, DoubleFunction<Optional<Element>>> elementSupplier;
public Scene() {
this.elementSupplier = new HashMap<>();
}
public Optional<Entry<Element, Intersection>> intersect(Ray ray) {
Entry<Element, Intersection> result = null;
double distance = Double.POSITIVE_INFINITY;
for(Element e : elements) {
Optional<Intersection> inter = e.getSurface().intersect(ray);
if(inter.isPresent()) {
double d = inter.get().getDistance();
if(d < distance) {
result = new SimpleEntry(e, inter.get());
distance = d;
}
}
}
return Optional.ofNullable(result);
}
public void setCamera(Camera camera) {
this.camera = camera;
}
public Camera getCamera() {
return camera;
}
public void setTime(double time) {
elements = elementSupplier.values()
.stream()
.map(f -> f.apply(time))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList()).toArray(new Element[0]);
}
public UUID addElement(Element element) {
return addElement((d) -> Optional.of(element));
}
public UUID addElement(DoubleFunction<Optional<Element>> function) {
UUID uuid = UUID.randomUUID();
elementSupplier.put(uuid, function);
return uuid;
}
public DoubleFunction<Optional<Element>> removeElement(UUID uuid) {
return elementSupplier.remove(uuid);
}
}
<file_sep>package me.joba.pathtracercluster.packets;
import java.util.UUID;
/**
*
* @author balsfull
*/
public class PacketServer02SendTask {
private UUID sceneId;
private double minX = -1, maxX = 1;
private double minY = -1, maxY = 1;
private int rayCount = 1000;
private int priority = 0; //Higher value <=> Higher priority
public PacketServer02SendTask() {
}
public PacketServer02SendTask(UUID sceneId) {
this.sceneId = sceneId;
}
public void setSceneId(UUID sceneId) {
this.sceneId = sceneId;
}
public void setMinX(double minX) {
this.minX = minX;
}
public void setMaxX(double maxX) {
this.maxX = maxX;
}
public void setMinY(double minZ) {
this.minY = minZ;
}
public void setMaxY(double maxZ) {
this.maxY = maxZ;
}
public void setRayCount(int rayCount) {
this.rayCount = rayCount;
}
public void setPriority(int priority) {
this.priority = priority;
}
public UUID getSceneId() {
return sceneId;
}
public double getMinX() {
return minX;
}
public double getMaxX() {
return maxX;
}
public double getMinY() {
return minY;
}
public double getMaxY() {
return maxY;
}
public int getRayCount() {
return rayCount;
}
public int getPriority() {
return priority;
}
}
<file_sep><?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>me.joba</groupId>
<artifactId>PathTracerCluster</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>me.joba.pathtracercluster.Main</mainClass>
<packageName>me.joba.pathtracercluster</packageName>
</manifest>
<manifestEntries>
<mode>development</mode>
<url>${pom.url}</url>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedClassifierName>shaded</shadedClassifierName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>clojars</id>
<url>http://clojars.org/repo/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>kryonet</groupId>
<artifactId>kryonet</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>5.0.0-RC1</version>
</dependency>
<dependency>
<groupId>com.martiansoftware</groupId>
<artifactId>jsap</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project><file_sep>package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import me.joba.pathtracercluster.pathtracer.material.BlackBodyRadiator;
/**
*
* @author balsfull
*/
public class BlackBodyRadiatorSerializer extends Serializer<BlackBodyRadiator>{
@Override
public void write(Kryo kryo, Output output, BlackBodyRadiator t) {
output.writeDouble(t.getTemperature());
output.writeDouble(t.getNormalizationFactor());
}
@Override
public BlackBodyRadiator read(Kryo kryo, Input input, Class<? extends BlackBodyRadiator> type) {
double temp = input.readDouble();
double norm = input.readDouble();
return new BlackBodyRadiator(temp, norm);
}
}
<file_sep>package pathtracer.material;
import pathtracer.Intersection;
import pathtracer.PTRandom;
import pathtracer.Ray;
import pathtracer.Vector3;
/**
*
* @author balsfull
*/
public class DiffuseGrayMaterial implements Material {
private final double grayScale;
public DiffuseGrayMaterial(double grayScale) {
if(grayScale < 0 || grayScale > 1) throw new AssertionError("GrayScale outside of range [0,1]. Found: " + grayScale);
this.grayScale = grayScale;
}
@Override
public Ray getNextRay(Ray incoming, Intersection intersection) {
Vector3 hemi = PTRandom.getHemisphereVector();
Vector3 normal;
if(incoming.getDirection().dot(intersection.getNormal()) < 0) {
normal = intersection.getNormal();
}
else {
normal = intersection.getNormal().scale(-1);
}
Vector3 direction = hemi.rotateTowards(normal);
return new Ray(intersection.getPosition(), direction, incoming.getWavelength(), grayScale);
}
}
<file_sep>package me.joba.pathtracercluster.pathtracer.surface;
import me.joba.pathtracercluster.pathtracer.Vector3;
/**
*
* @author balsfull
*/
public interface Volume {
boolean isInside(Vector3 position);
}
<file_sep>package pathtracer.material;
/**
*
* @author balsfull
*/
public interface Radiator {
double getIntensity(double wavelength);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import me.joba.pathtracercluster.pathtracer.Vector3;
import me.joba.pathtracercluster.pathtracer.surface.Triangle;
/**
*
* @author jonas
*/
public class TriangleSerializer extends Serializer<Triangle> {
@Override
public void write(Kryo kryo, Output output, Triangle t) {
kryo.writeObject(output, t.getP0());
kryo.writeObject(output, t.getP1());
kryo.writeObject(output, t.getP2());
}
@Override
public Triangle read(Kryo kryo, Input input, Class<? extends Triangle> type) {
Vector3 p0 = kryo.readObject(input, Vector3.class);
Vector3 p1 = kryo.readObject(input, Vector3.class);
Vector3 p2 = kryo.readObject(input, Vector3.class);
return new Triangle(p0, p1, p2);
}
}
<file_sep>package pathtracer.standalone;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import pathtracer.PathTracer;
import pathtracer.ProgressTracker;
import pathtracer.Scene;
import static pathtracer.PathTracer.HEIGHT;
import static pathtracer.PathTracer.WIDTH;
import pathtracer.render.Plotter;
import pathtracer.render.ToneMapper;
import pathtracer.render.Tracer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jonas
*/
public class PathTracerStandalone {
public static void render(Scene scene) throws Exception {
int threadCount = 10;
RenderThread[] rt = new RenderThread[threadCount];
Tracer[] tracers = new Tracer[threadCount];
Plotter plotter = new Plotter(WIDTH, HEIGHT);
for (int i = 0; i < rt.length; i++) {
Tracer tracer = new Tracer(WIDTH, HEIGHT);
tracers[i] = tracer;
rt[i] = new RenderThread(scene, tracer, plotter);
}
ProgressTracker progressThread = new ProgressTracker(tracers);
progressThread.setPriority(10);
progressThread.start();
for (RenderThread r : rt) {
r.start();
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void start() {
try {
for(RenderThread t : rt) {
t.signalEnd();
}
progressThread.signalEnd();
for(RenderThread t : rt) {
t.join();
}
ToneMapper mapper = new ToneMapper(WIDTH, HEIGHT);
mapper.tonemap(plotter.getCIEVector());
int[] rgb = mapper.getRGB();
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
bi.setRGB(0, 0, WIDTH, HEIGHT, rgb, 0, WIDTH);
ImageIO.write(bi, "png", new File("rendered.png"));
} catch (Exception ex) {
Logger.getLogger(PathTracer.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
<file_sep>package me.joba.pathtracercluster.pathtracer;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Optional;
/**
*
* @author balsfull
*/
public class Scene {
private final int width, height;
private Element[] elements;
private Camera camera;
public Scene(int width, int height) {
this.width = width;
this.height = height;
this.elements = new Element[0];
}
public Scene(int width, int height, Camera camera, Element[] elements) {
this(width, height);
this.camera = camera;
this.elements = elements;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Element[] getElements() {
return elements;
}
public Optional<Entry<Element, Intersection>> intersect(Ray ray) {
Entry<Element, Intersection> result = null;
double distance = Double.POSITIVE_INFINITY;
for(Element e : elements) {
Optional<Intersection> inter = e.getSurface().intersect(ray);
if(inter.isPresent()) {
double d = inter.get().getDistance();
if(d < distance) {
result = new SimpleEntry(e, inter.get());
distance = d;
}
}
}
return Optional.ofNullable(result);
}
public void setCamera(Camera camera) {
this.camera = camera;
}
public Camera getCamera() {
return camera;
}
public void addElement(Element element) {
ArrayList<Element> list = new ArrayList<>(Arrays.asList(elements));
list.add(element);
elements = list.toArray(new Element[0]);
}
}
<file_sep>package me.joba.pathtracercluster.packets;
import java.util.UUID;
import me.joba.pathtracercluster.pathtracer.Scene;
/**
*
* @author balsfull
*/
public class PacketServer04SendScene {
private UUID sceneId;
private Scene scene;
public PacketServer04SendScene() {
}
public PacketServer04SendScene(UUID sceneId, Scene scene) {
this.sceneId = sceneId;
this.scene = scene;
}
public UUID getSceneId() {
return sceneId;
}
public Scene getScene() {
return scene;
}
}
<file_sep>package me.joba.pathtracercluster.server;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import me.joba.pathtracercluster.NetworkRegistration;
import me.joba.pathtracercluster.packets.PacketClient03GetScene;
import me.joba.pathtracercluster.packets.PacketClient05TaskCompleted;
import me.joba.pathtracercluster.packets.PacketClient06Info;
import me.joba.pathtracercluster.packets.PacketServer01Hello;
import me.joba.pathtracercluster.packets.PacketServer04SendScene;
import me.joba.pathtracercluster.pathtracer.Scene;
/**
*
* @author balsfull
*/
public class NetworkListener extends Listener {
private final Map<Connection, ConnectionData> clients;
private final UUID serverId;
private final UUID sceneId;
private final Scene scene;
private final TaskScheduler scheduler;
public NetworkListener(Scene scene, UUID serverId, UUID sceneId, TaskScheduler scheduler, InetAddress[] servers) throws IOException {
this.scene = scene;
this.sceneId = sceneId;
this.serverId = serverId;
this.scheduler = scheduler;
clients = new ConcurrentHashMap<>();
for (int i = 0; i < servers.length; i++) {
Client client = new Client(16384, 16384);
client.start();
NetworkRegistration.register(client);
client.addListener(this);
client.connect(10000, servers[i], NetworkRegistration.DEFAULT_PORT);
}
}
static class PathTracerConnection extends Connection {
}
@Override
public void connected(Connection c) {
System.out.println("Connected to " + c.getRemoteAddressTCP());
c.sendTCP(new PacketServer01Hello(serverId));
ConnectionData cdata = new ConnectionData(c);
clients.put(c, cdata);
scheduler.addConnection(cdata);
}
@Override
public void disconnected(Connection c) {
scheduler.removeConnection(clients.remove(c));
}
@Override
public void received(Connection c, Object o) {
if(o instanceof PacketClient03GetScene) {
System.out.println("Get scene " + c.getRemoteAddressTCP());
if(((PacketClient03GetScene) o).getSceneId().equals(sceneId)) {
c.sendTCP(new PacketServer04SendScene(sceneId, scene));
}
}
else if(o instanceof PacketClient05TaskCompleted) {
PacketClient05TaskCompleted packet = (PacketClient05TaskCompleted)o;
scheduler.acceptPlotterData(packet.getCIEVector(), packet.getOffset());
}
else if(o instanceof PacketClient06Info) {
PacketClient06Info packet = (PacketClient06Info)o;
ConnectionData data = clients.get(c);
data.setQueueSize(packet.getQueueSize());
data.setTotalRayCount(packet.getTotalRayCount());
}
}
}
<file_sep>package me.joba.pathtracercluster;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import me.joba.pathtracercluster.client.NetworkListener;
import me.joba.pathtracercluster.packets.PacketServer02SendTask;
import me.joba.pathtracercluster.pathtracer.Scene;
import me.joba.pathtracercluster.pathtracer.render.Plotter;
/**
*
* @author balsfull
*/
public class Task implements Comparable<Task> {
private final Scene scene;
private final Plotter plotter;
private final double minX, maxX;
private final double minY, maxY;
private final int rayCount;
private final int priority; //Higher value <=> Higher priority
private final UUID serverId;
private final NetworkListener networkListener;
private AtomicInteger count = new AtomicInteger(1);
public Task(Scene scene, Plotter plotter, UUID serverId, NetworkListener networkListener, PacketServer02SendTask packet) {
this(scene, plotter, serverId, networkListener, packet.getMinX(), packet.getMaxX(), packet.getMinY(), packet.getMaxY(), packet.getRayCount(), packet.getPriority());
}
private Task(Scene scene, Plotter plotter, UUID serverId, NetworkListener networkListener, double minX, double maxX, double minY, double maxY, int rayCount, int priority) {
this.scene = scene;
this.plotter = plotter;
this.minX = minX;
this.maxX = maxX;
this.minY = minY;
this.maxY = maxY;
this.rayCount = rayCount;
this.priority = priority;
this.serverId = serverId;
this.networkListener = networkListener;
}
public Scene getScene() {
return scene;
}
public Plotter getPlotter() {
return plotter;
}
public double getMinX() {
return minX;
}
public double getMaxX() {
return maxX;
}
public double getMinY() {
return minY;
}
public double getMaxY() {
return maxY;
}
public int getRayCount() {
return rayCount;
}
public int getPriority() {
return priority;
}
public void signalDone() {
if(count.decrementAndGet() == 0) {
networkListener.sendCompletion(this);
}
}
public UUID getServerId() {
return serverId;
}
public Task[] split(int shards) {
count = null;
Task[] tasks = new Task[shards];
int raysPerShard = rayCount / shards;
AtomicInteger count = new AtomicInteger(shards);
for (int i = 0; i < shards - 1; i++) {
tasks[i] = new Task(scene, plotter, serverId, networkListener, minX, maxX, minY, maxY, raysPerShard, priority);
tasks[i].count = count;
}
tasks[shards - 1] = new Task(scene, plotter, serverId, networkListener, minX, maxX, minY, maxY, rayCount - raysPerShard * (shards - 1), priority);
tasks[shards - 1].count = count;
return tasks;
}
@Override
public int compareTo(Task o) {
return Integer.compare(priority, o.priority);
}
}
<file_sep>package me.joba.pathtracercluster.packets;
import java.util.UUID;
/**
*
* @author balsfull
*/
public class PacketClient03GetScene {
private UUID sceneId;
public PacketClient03GetScene() {
}
public PacketClient03GetScene(UUID sceneId) {
this.sceneId = sceneId;
}
public UUID getSceneId() {
return sceneId;
}
}
<file_sep>package me.joba.pathtracercluster.packets;
/**
*
* @author balsfull
*/
public class PacketClient06Info {
private int queueSize;
private int totalRayCount;
public PacketClient06Info() {
}
public PacketClient06Info(int queueSize, int totalRayCount) {
this.queueSize = queueSize;
this.totalRayCount = totalRayCount;
}
public int getTotalRayCount() {
return totalRayCount;
}
public int getQueueSize() {
return queueSize;
}
}
<file_sep>package me.joba.pathtracercluster.server;
import java.net.InetAddress;
import java.util.UUID;
import me.joba.pathtracercluster.pathtracer.Scene;
import me.joba.pathtracercluster.pathtracer.render.Plotter;
/**
*
* @author balsfull
*/
public class ServerState {
public int port, height, width, autosave, writeImage;
public InetAddress[] servers;
public Scene scene;
public UUID sceneId, serverId;
public Plotter imageState;
}
<file_sep>package me.joba.pathtracercluster.pathtracer;
/**
*
* @author balsfull
*/
public class Ray {
private Vector3 position, direction;
private double wavelength, probability;
public Ray(Vector3 position, Vector3 direction, double wavelength) {
this.position = position;
this.direction = direction;
this.wavelength = wavelength;
this.probability = 1.0;
}
public Ray(Vector3 position, Vector3 direction, double wavelength, double probability) {
this.position = position;
this.direction = direction;
this.wavelength = wavelength;
this.probability = probability;
}
public Vector3 getPosition() {
return position;
}
public Vector3 getDirection() {
return direction;
}
public double getWavelength() {
return wavelength;
}
public double getProbability() {
return probability;
}
public void setPosition(Vector3 position) {
this.position = position;
}
public void setDirection(Vector3 direction) {
this.direction = direction;
}
public void setWavelength(double wavelength) {
this.wavelength = wavelength;
}
public void setProbability(double probability) {
this.probability = probability;
}
@Override
public String toString() {
return "Ray{" + "position=" + position + ", direction=" + direction + '}';
}
}
<file_sep>package pathtracer.surface;
import java.util.Optional;
import pathtracer.Intersection;
import pathtracer.Ray;
import pathtracer.Vector3;
/**
*
* @author balsfull
*/
public class Sphere implements Surface, Volume {
private final Vector3 position;
private final double radiusSquared;
public Sphere(Vector3 offset, double radius) {
this.position = offset;
this.radiusSquared = radius * radius;
}
@Override
public Optional<Intersection> intersect(Ray ray) {
double a = ray.getDirection().lengthSquared();
Vector3 coffset = ray.getPosition().subtract(position);
// System.out.println(coffset);
// System.out.println(a);
double b = 2.0 * ray.getDirection().dot(coffset);
// System.out.println(b);
double c = coffset.lengthSquared() - radiusSquared;
// System.out.println(c);
double discriminant = b * b - 4.0 * a * c;
// System.out.println(discriminant);
if(discriminant < 0) {
return Optional.empty();
}
double d = Math.sqrt(discriminant);
double t1 = 0.5 * (-b + d) / a;
double t2 = 0.5 * (-b - d) / a;
// System.out.println(t1);
// System.out.println(t2);
double t = Math.min(t1, t2);
if(t <= 0) {
return Optional.empty();
}
Vector3 position = ray.getPosition().add(ray.getDirection().scale(t));
Vector3 normal = (position.subtract(this.position)).normalize();
Vector3 tangent = new Vector3(0, 1, 0).cross(normal).normalize();
Intersection inter = new Intersection(position, normal, tangent, t);
return Optional.of(inter);
}
@Override
public boolean isInside(Vector3 position) {
return position.subtract(this.position).lengthSquared() < radiusSquared;
}
}
<file_sep>package pathtracer.surface;
import java.util.Optional;
import pathtracer.Intersection;
import pathtracer.Ray;
/**
*
* @author balsfull
*/
public interface Surface {
Optional<Intersection> intersect(Ray ray);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package me.joba.pathtracercluster.pathtracer.surface;
import java.util.Optional;
import me.joba.pathtracercluster.pathtracer.Intersection;
import me.joba.pathtracercluster.pathtracer.Ray;
import me.joba.pathtracercluster.pathtracer.Vector3;
/**
*
* @author jonas
*/
public class Triangle implements Surface {
private final Vector3 p0, p1, p2, normal, reverseNormal;
public Triangle(Vector3 p0, Vector3 p1, Vector3 p2) {
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
this.normal = p1.subtract(p0).cross(p2.subtract(p0)).normalize();
this.reverseNormal = normal.scale(-1);
}
public Vector3 getP0() {
return p0;
}
public Vector3 getP1() {
return p1;
}
public Vector3 getP2() {
return p2;
}
@Override
public Optional<Intersection> intersect(Ray ray) {
double epsilon = 1e-8;
Vector3 edge1 = p1.subtract(p0);
Vector3 edge2 = p2.subtract(p0);
Vector3 h = ray.getDirection().cross(edge2);
double a = edge1.dot(h);
if(a > -epsilon && a < epsilon) {
return Optional.empty();
}
double f = 1/a;
Vector3 s = ray.getPosition().subtract(p0);
double u = f * s.dot(h);
if(u < 0 || u > 1) {
return Optional.empty();
}
Vector3 q = s.cross(edge1);
double v = f * ray.getDirection().dot(q);
if(v < 0 || u + v > 1) {
return Optional.empty();
}
double t = f * edge2.dot(q);
if(t > epsilon) {
return Optional.of(new Intersection(ray.getPosition().add(ray.getDirection().scale(t)), a > 0 ? normal : reverseNormal, new Vector3(0, 0, 0), t));
}
else {
return Optional.empty();
}
}
}
<file_sep>package pathtracer.slave;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import pathtracer.Scene;
import static pathtracer.PathTracer.HEIGHT;
import static pathtracer.PathTracer.THREADS;
import static pathtracer.PathTracer.WIDTH;
import pathtracer.render.Tracer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jonas
*/
public class PathTracerSlave {
private static SlaveRenderThread[] slaveThreads;
public static void start(Scene scene) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
while(running) {
String command = scanner.nextLine();
if(command.startsWith("set")) {
setSetting(command.substring(4));
ok();
continue;
}
switch(command) {
case "terminate": {
ok();
System.exit(0);
break;
}
case "start": {
render(scene);
ok();
break;
}
case "stop": {
stop();
ok();
break;
}
}
}
}
private static void ok() {
System.out.println("ok");
}
private static void render(Scene scene) {
System.out.println("Thread count: " + THREADS);
slaveThreads = new SlaveRenderThread[THREADS];
for (int i = 0; i < THREADS; i++) {
Tracer tracer = new Tracer(WIDTH, HEIGHT);
slaveThreads[i] = new SlaveRenderThread(scene, tracer);
}
for (int i = 0; i < THREADS; i++) {
slaveThreads[i].start();
}
}
private static void stop() {
if(slaveThreads == null) return;
for (SlaveRenderThread srt : slaveThreads) {
srt.signalEnd();
}
for (SlaveRenderThread srt : slaveThreads) {
try {
srt.join();
} catch (InterruptedException ex) {
Logger.getLogger(PathTracerSlave.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void setSetting(String setting) {
String[] split = setting.split(" ");
switch(split[0]) {
case "threads": {
THREADS = Integer.parseInt(split[1]);
break;
}
case "width": {
WIDTH = Integer.parseInt(split[1]);
break;
}
case "height": {
HEIGHT = Integer.parseInt(split[1]);
break;
}
case "batchsize": {
Tracer.PHOTON_COUNT = Integer.parseInt(split[1]);
break;
}
}
}
}
<file_sep>package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import me.joba.pathtracercluster.pathtracer.Vector3;
import me.joba.pathtracercluster.pathtracer.surface.Plane;
/**
*
* @author balsfull
*/
public class PlaneSerializer extends Serializer<Plane> {
@Override
public void write(Kryo kryo, Output output, Plane t) {
kryo.writeObject(output, t.getNormal());
kryo.writeObject(output, t.getOffset());
}
@Override
public Plane read(Kryo kryo, Input input, Class<? extends Plane> type) {
Vector3 norm = kryo.readObject(input, Vector3.class);
Vector3 off = kryo.readObject(input, Vector3.class);
return new Plane(off, norm);
}
}
<file_sep>package me.joba.pathtracercluster.pathtracer.surface;
import java.util.Optional;
import me.joba.pathtracercluster.pathtracer.Intersection;
import me.joba.pathtracercluster.pathtracer.Ray;
/**
*
* @author balsfull
*/
public interface Surface {
Optional<Intersection> intersect(Ray ray);
}
<file_sep>package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import me.joba.pathtracercluster.pathtracer.material.DiffuseGrayMaterial;
/**
*
* @author balsfull
*/
public class DiffuseGrayMaterialSerializer extends Serializer<DiffuseGrayMaterial>{
@Override
public void write(Kryo kryo, Output output, DiffuseGrayMaterial t) {
output.writeDouble(t.getGrayScale());
}
@Override
public DiffuseGrayMaterial read(Kryo kryo, Input input, Class<? extends DiffuseGrayMaterial> type) {
double gray = input.readDouble();
return new DiffuseGrayMaterial(gray);
}
}<file_sep>package me.joba.pathtracercluster.client;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Parameter;
import com.martiansoftware.jsap.SimpleJSAP;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import me.joba.pathtracercluster.NetworkRegistration;
import me.joba.pathtracercluster.pathtracer.PathTracer;
/**
*
* @author balsfull
*/
public class ClientMain {
public static void main(String[] args) throws JSAPException, IOException {
SimpleJSAP jsap = new SimpleJSAP(
"PathTracer",
"Realistic rendering",
new Parameter[]{
new FlaggedOption("rays", JSAP.INTEGER_PARSER, "100000", JSAP.NOT_REQUIRED, JSAP.NO_SHORTFLAG, "rays", "Minimal ray count per shard"),
new FlaggedOption("threads", JSAP.INTEGER_PARSER, Integer.toString(Runtime.getRuntime().availableProcessors()), JSAP.NOT_REQUIRED, JSAP.NO_SHORTFLAG, "threads", "Thread count")
}
);
JSAPResult config = jsap.parse(args);
if (!config.success()) {
System.err.println(" " + jsap.getUsage());
System.exit(1);
}
System.out.println("Starting Client with:");
System.out.println("Threads: " + config.getInt("threads"));
System.out.println("MinRays: " + config.getInt("rays"));
PathTracer tracer = new PathTracer(config.getInt("rays"), config.getInt("threads"));
NetworkListener network = new NetworkListener(NetworkRegistration.DEFAULT_PORT, tracer);
new Thread() {
@Override
public void run() {
long lastStatus = 0;
while(true) {
if(lastStatus < System.currentTimeMillis() - 5000) {
tracer.printStats();
lastStatus = System.currentTimeMillis();
}
network.sendInfo(tracer.getQueueSize(), 0);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(ClientMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}.start();
tracer.start();
}
}
<file_sep>package pathtracer.surface;
import pathtracer.Vector3;
/**
*
* @author balsfull
*/
public interface Volume {
boolean isInside(Vector3 position);
}
<file_sep>package pathtracer;
/**
*
* @author balsfull
*/
public class Vector3 {
public final double x, y, z;
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector3Mutable mutable() {
return new Vector3Mutable(x, y, z);
}
public Vector3 add(Vector3 v) {
return new Vector3(x + v.x, y + v.y, z + v.z);
}
public Vector3 subtract(Vector3 v) {
return new Vector3(x - v.x, y - v.y, z - v.z);
}
public Vector3 scale(double d) {
return new Vector3(x * d, y * d, z * d);
}
public double length() {
return Math.sqrt(lengthSquared());
}
public double lengthSquared() {
return x*x + y*y + z*z;
}
public Vector3 normalize() {
return scale(1 / length());
}
public double dot(Vector3 v) {
return x * v.x + y * v.y + z * v.z;
}
public Vector3 cross(Vector3 b) {
return new Vector3(
y * b.z - z * b.y,
z * b.x - x * b.z,
x * b.y - y * b.x
);
}
public Vector3 rotateTowards(Vector3 v) {
double dot = v.z;
if(dot > 0.9999) return this;
if(dot < -0.9999) return new Vector3(x, y, -z);
Vector3 a1 = new Vector3(0, 0, 1).cross(v).normalize();
Vector3 a2 = a1.cross(v).normalize();
return a1.scale(x).add(a2.scale(y)).add(v.scale(z));
}
public Vector3 rotate(Quaternion q) {
Quaternion p = new Quaternion(x, y, z, 0);
Quaternion r = q.multiply(p).multiply(q.conjugate());
return new Vector3(r.x, r.y, r.z);
}
public Vector3 reflect(Vector3 n) {
return subtract(n.scale(n.dot(this) * 2));
}
@Override
public String toString() {
return "Vector3{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
}
}
<file_sep>package me.joba.pathtracercluster.server;
import com.esotericsoftware.kryonet.Connection;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* @author balsfull
*/
public class ConnectionData {
private AtomicInteger queueSize = new AtomicInteger(0);
private AtomicInteger totalRayCount = new AtomicInteger(0);
private final Connection connection;
public ConnectionData(Connection connection) {
this.connection = connection;
}
public Connection getConnection() {
return connection;
}
public void setTotalRayCount(int v) {
totalRayCount.updateAndGet(i -> i < v ? v : i);
}
public void incrementQueueSize(int delta) {
queueSize.addAndGet(delta);
}
public void setQueueSize(int size) {
queueSize.set(size);
}
public int getQueueSize() {
return queueSize.get();
}
public int getTotalRayCount() {
return totalRayCount.get();
}
}
<file_sep>package pathtracer.material;
import pathtracer.Intersection;
import pathtracer.Ray;
/**
*
* @author balsfull
*/
public class ColoredGlassMaterial extends GlassMaterial {
private final double wavelength, deviation;
public ColoredGlassMaterial(double wavelength, double deviation) {
this.wavelength = wavelength;
this.deviation = deviation;
}
@Override
public Ray getNextRay(Ray incoming, Intersection intersection) {
Ray ray = super.getNextRay(incoming, intersection);
double p = (wavelength - ray.getWavelength()) / deviation;
double q = Math.exp(-0.5 * p * p);
ray.setProbability(ray.getProbability() * q);
return ray;
}
}
<file_sep>package me.joba.pathtracercluster.pathtracer.render;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import me.joba.pathtracercluster.pathtracer.Camera;
import me.joba.pathtracercluster.pathtracer.Element;
import me.joba.pathtracercluster.pathtracer.Intersection;
import me.joba.pathtracercluster.pathtracer.PTRandom;
import me.joba.pathtracercluster.pathtracer.Ray;
import me.joba.pathtracercluster.pathtracer.Scene;
/**
*
* @author balsfull
*/
public class Tracer {
public class Photon {
public double x, y;
public double probability;
public double wavelength;
}
private final ArrayList<Photon> photons;
private AtomicInteger rayCount = new AtomicInteger(0);
public Tracer() {
this.photons = new ArrayList<>();
}
public List<Photon> getPhotons() {
return photons;
}
private double renderRay(Scene scene, Ray ray) {
double continueChance = 1;
double intensity = 1;
while(true) {
Optional<Entry<Element, Intersection>> e = scene.intersect(ray);
if(!e.isPresent()) {
return 0;
}
Element element = e.get().getKey();
Intersection inter = e.get().getValue();
if(element.isRadiator()) {
return intensity * element.getRadiator().getIntensity(ray.getWavelength());
}
else {
ray = element.getMaterial().getNextRay(ray, inter);
intensity = intensity * ray.getProbability();
}
ray.setPosition(ray.getPosition().add(ray.getDirection().scale(0.0001)));
continueChance *= 0.96;
if(PTRandom.getUnit() * 0.85 > continueChance * (1 - Math.exp(intensity * -20))) {
break;
}
}
return 0;
}
private double renderCameraRay(Scene scene, double x, double y, double wavelength) {
Camera camera = scene.getCamera();
return renderRay(scene, camera.getRay(x, y, wavelength));
}
public void render(Scene scene, int photonCount) {
render(scene, -1, 1, -1, 1, photonCount);
}
public void render(Scene scene, double minX, double maxX, double minY, double maxY, int photonCount) {
rayCount.set(0);
photons.clear();
photons.ensureCapacity(photonCount);
for (int i = 0; i < photonCount; i++) {
double wavelength = PTRandom.getWavelength();
double x = PTRandom.getUnit() * (maxX - minX) + minX;
double y = PTRandom.getUnit() * (maxY - minY) + minY;
Photon photon = new Photon();
photon.wavelength = wavelength;
photon.x = x;
photon.y = y;
photon.probability = renderCameraRay(scene, x, y, wavelength);
photons.add(photon);
rayCount.incrementAndGet();
}
}
public int getCurrentRayCount() {
return rayCount.intValue();
}
}
<file_sep>package me.joba.pathtracercluster.pathtracer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.PriorityBlockingQueue;
import me.joba.pathtracercluster.Task;
import me.joba.pathtracercluster.pathtracer.RenderThread.RenderState;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author jonas
*/
public class PathTracer {
private final Map<UUID, Scene> sceneMap;
private final int minRayCount;
private final PriorityBlockingQueue<Task> taskQueue;
private final RenderThread[] threads;
public PathTracer(int minRayCount, int threadCount) {
this.sceneMap = new HashMap<>();
this.minRayCount = minRayCount;
this.taskQueue = new PriorityBlockingQueue<>();
threads = new RenderThread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new RenderThread(taskQueue);
threads[i].setName("RenderThread #" + i);
}
}
public int getQueueSize() {
int size = taskQueue.size();
if(size == 0) {
return -(int)Arrays
.stream(threads)
.filter(rt -> rt.getRenderState() == RenderState.IDLE)
.count();
}
return size;
}
public void registerScene(UUID uuid, Scene scene) {
sceneMap.put(uuid, scene);
}
public Scene getScene(UUID uuid) {
return sceneMap.get(uuid);
}
public void queueTask(Task task) {
if(minRayCount < 0) {
taskQueue.add(task);
return;
}
int shardCount = Math.max(1, Math.min(threads.length, task.getRayCount() / minRayCount));
if(shardCount == 1) {
taskQueue.add(task);
return;
}
Task[] shards = task.split(shardCount);
for (Task shard : shards) {
taskQueue.add(shard);
}
}
public void start() {
for(RenderThread rt : threads) {
rt.start();
}
}
public void stop() throws InterruptedException {
for(RenderThread rt : threads) {
rt.signalEnd();
}
for(RenderThread rt : threads) {
rt.join();
}
}
public void printStats() {
int blocks = 20;
System.out.println("[======== INFO ========]");
System.out.println("Queue size: " + taskQueue.size());
for (int i = 0; i < threads.length; i++) {
RenderState state = threads[i].getRenderState();
System.out.print(threads[i].getName() + ": ");
if(state == RenderState.TRACING) {
int cRays = threads[i].getCurrentRayCount();
int tRays = threads[i].getTotalRayCount();
float percentage = (float)cRays / (float)tRays;
int filledBlocks = (int)Math.floor(percentage * blocks);
char[] bar = new char[blocks];
Arrays.fill(bar, 0, filledBlocks, '#');
Arrays.fill(bar, filledBlocks, blocks, ' ');
System.out.print("[" + new String(bar) + "] " + (int)Math.floor(percentage * 100) + "%");
System.out.print("(" + cRays + "/" + tRays + ")");
}
else if(state == RenderState.PLOTTING) {
System.out.print("Plotting...");
}
else if(state == RenderState.IDLE) {
System.out.print("Idle");
}
System.out.println();
}
}
}
<file_sep># Pathtracer

<file_sep>package me.joba.pathtracercluster.packets;
import java.util.UUID;
/**
*
* @author balsfull
*/
public class PacketServer01Hello {
private UUID serverId;
public PacketServer01Hello() {
}
public PacketServer01Hello(UUID serverId) {
this.serverId = serverId;
}
public UUID getServerId() {
return serverId;
}
}
<file_sep>package me.joba.pathtracercluster.serializers;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.UUID;
import me.joba.pathtracercluster.pathtracer.Scene;
import me.joba.pathtracercluster.pathtracer.render.Plotter;
import me.joba.pathtracercluster.server.ServerState;
/**
*
* @author balsfull
*/
public class ServerStateSerializer extends Serializer<ServerState>{
@Override
public void write(Kryo kryo, Output output, ServerState t) {
output.writeInt(t.width);
output.writeInt(t.height);
output.writeInt(t.port);
output.writeInt(t.autosave);
output.writeInt(t.writeImage);
kryo.writeObject(output, t.serverId);
kryo.writeObject(output, t.sceneId);
kryo.writeObject(output, t.scene);
kryo.writeObject(output, t.servers);
kryo.writeObject(output, t.imageState);
}
@Override
public ServerState read(Kryo kryo, Input input, Class<? extends ServerState> type) {
ServerState ss = new ServerState();
ss.width = input.readInt();
ss.height = input.readInt();
ss.port = input.readInt();
ss.autosave = input.readInt();
ss.writeImage = input.readInt();
ss.serverId = kryo.readObject(input, UUID.class);
ss.sceneId = kryo.readObject(input, UUID.class);
ss.scene = kryo.readObject(input, Scene.class);
ss.servers = kryo.readObject(input, InetAddress[].class);
ss.imageState = kryo.readObject(input, Plotter.class);
return ss;
}
}
|
e6290bcad1ea416b7fafeb03fb83c1adbe2243d1
|
[
"Markdown",
"Java",
"Maven POM"
] | 39 |
Java
|
JoBa97/pathtracer
|
d1953f2bbda05328cea82421d634c35c5a7cdd67
|
de684d15c2d2be51f8b0610123a6028659f2b1d6
|
refs/heads/master
|
<repo_name>saszaz/camera_pose<file_sep>/README.txt
MARKER-BASED CAMERA POSE ESTIMATION
Georgia Institute of Technology
2015-12-15
This code was used as part of the Boeing Visual Tracking Project. It was designed for data collection of camera poses with respect to a checkerboard target. To be used with PointGrey Cameras (but can be modified to accomodate other camera drivers).
Requirements:
Ubuntu 12.04
Flycapture v2.7.3.13
OpenCV v2.4.7
ROS Hydro (**tf dependency**)
## Note: The listed versions are those that were used for original compilation. Other versions may be compatible, but have not been tested.
Installation:
$ mkdir build; cd build
$ cmake ..
$ make
Set-up:
A camera calibration file must be generated using OpenCV (see instructions online: <http://docs.opencv.org/2.4/doc/tutorials/calib3d/camera_calibration/camera_calibration.html> ).
Other calibration software can be used, but calibration files must be converted into OpenCV format.
Verify that parameters for get_param() in checkerboard_pose.cpp are set correctly, including file paths for data and calibration files.
To run:
$ ./checkerboard_pose
Press 'p' to grab frame and find pose
If pose is found, press 's' to save data and images
To quit, press 'q'
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(boeing_test)
#set(CMAKE_CXX_FLAGS "-std=c++0x")
find_package(OpenCV REQUIRED)
include_directories(
${OpenCV_INCLUDE_DIRS}
)
include_directories("/usr/include/flycapture")
include_directories("/opt/ros/hydro/include/tf")
link_directories(/opt/ros/hydro/lib)
add_executable(checkerboard_pose checkerboard_pose.cpp)
target_link_libraries(checkerboard_pose ${OpenCV_LIBS} -lflycapture -ltf -ltf_conversions)
<file_sep>/checkerboard_pose.cpp
#include <tf/transform_listener.h>
#include <FlyCapture2.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>
#define MAX_DATE 24
using namespace std;
using namespace FlyCapture2;
Error err;
char key=0;
bool mutex=false;
int frame_no=0;
bool win_start;
bool init=true;
bool use_calib;
int cam_mode;
int cam_serial;
const char * calib_file;
const char * save_dir;
char data_filename[100];
char data_filename_q[100];
int rows, cols;
double width;
int win_size_sp;
int max_iter_sp;
double eps_sp;
bool use_init_pnp;
int max_iter_pnp;
double err_pnp;
double min_inl_pnp;
/* Enumerate pose labels - used for naming saved images */
int pose_list[] = {01, 02, 03, 04, 05, 06, 07};
cv::Mat cameraMat, distCoeffs, projectionMat;
FlyCapture2::Camera pt_grey;
cv::Mat imgMain;
IplImage *img;
// Forward declaration;
void get_pose(cv::Mat *img);
int init_cam_capture ( FlyCapture2::Camera &camera, PGRGuid guid)
{
CameraInfo camInfo;
// Connect the camera
err = camera.Connect( &guid );
if ( err != PGRERROR_OK )
{
std::cout << "Failed to connect to camera" << std::endl;
return false;
}
// Get the camera info and print it out
err = camera.GetCameraInfo( &camInfo );
if ( err != PGRERROR_OK )
{
std::cout << "Failed to get camera info from camera" << std::endl;
return false;
}
std::cout << camInfo.vendorName << " "
<< camInfo.modelName << " "
<< camInfo.serialNumber << std::endl;
err = camera.StartCapture();
if ( err == PGRERROR_ISOCH_BANDWIDTH_EXCEEDED )
{
std::cout << "Bandwidth exceeded" << std::endl;
return false;
}
else if ( err != PGRERROR_OK )
{
std::cout << "Failed to start image capture" << std::endl;
return false;
}
}
int set_cam_param ( FlyCapture2::Camera &camera)
{
Property prop;
prop.type = SHUTTER;
//Ensure the property is on.
prop.onOff = true;
//Ensure auto-adjust mode is off.
prop.autoManualMode = false;
//Ensure the property is set up to use absolute value control.
prop.absControl = true;
//Set the absolute value of shutter to 20 ms.
// prop.absValue = 39.3;
//Set the property.
err = camera.SetProperty( &prop );
prop.type = AUTO_EXPOSURE;
prop.onOff = true;
prop.autoManualMode = true;
prop.absControl = true;
prop.absValue = 2.0;
err = camera.SetProperty( &prop );
// Enable metadata
FlyCapture2::EmbeddedImageInfo info;
info.timestamp.onOff = true;
err = camera.SetEmbeddedImageInfo(&info);
if ( err == PGRERROR_PROPERTY_FAILED )
{
std::cout << "Property failed " << std::endl;
return false;
}
else if ( err == PGRERROR_PROPERTY_NOT_PRESENT )
{
std::cout << "Property not present" << std::endl;
return false;
}
else if (err != PGRERROR_OK)
{
std::cout << "Properties not set" << std::endl;
return false;
}
}
int load_calib_param()
{
// Read calibration matrices
std::cout << "calib_file: " << calib_file << std::endl;
cv::FileStorage fs( calib_file, cv::FileStorage::READ);
if (!fs.isOpened()){
std::cerr << "Failed to open calib params" << calib_file << std::endl;
return 1;
}
fs["Distortion_Coefficients"] >> distCoeffs;
fs["Camera_Matrix"] >> cameraMat;
fs["Projection_Matrix"] >> projectionMat;
fs.release();
return 0;
}
void get_pose(cv::Mat *img)
{
cv::Mat grayMat;
// Convert it to gray
cv::cvtColor( *img, grayMat, CV_BGR2GRAY );
cv::Size boardSize(rows,cols);
std::vector<cv::Point2f> corners;
std::vector<cv::Point3f> boardPoints;
for (int j=0; j<cols; j++){
for (int i=0; i<rows; i++){
boardPoints.push_back(cv::Point3f((float)(i*width),(float)(j*width),(float) 0.0));
}
}
std::cout << "Finding corners..." << std::endl;
bool found = cv::findChessboardCorners( grayMat, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH);
if (found && use_calib) {
std::cout << "FOUND corners" << std::endl;
cv::cornerSubPix(grayMat, corners, cv::Size( win_size_sp, win_size_sp), cv::Size(-1, -1),
cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, max_iter_sp, eps_sp));
cv::Mat corner_img;
img->copyTo(corner_img);
cv::Mat raw_img;
img->copyTo(raw_img);
cv::drawChessboardCorners(corner_img, boardSize, corners, found);
std::cout << "Finding target pose ..." << std::endl;
/* Find rotation and translation vectors */
cv::Vec<double,3> rvec, tvec;
std::vector<int> inliers;
/* Initial guess */
tvec[0] = 0.0; tvec[1] = 0.0; tvec[2] = 4.200;
rvec[0] = 0.0; rvec[1] = 0.0; rvec[2] = 0.0;
int min_inliers = (int)(min_inl_pnp*rows*cols);
cv::solvePnPRansac(boardPoints, corners, cameraMat, distCoeffs, rvec, tvec, use_init_pnp, max_iter_pnp, err_pnp, min_inliers, inliers);
if (inliers.size() > 0) {
float theta = norm(rvec);
printf("translation vector: %0.5f, %0.5f, %0.5f \n", tvec[0], tvec[1], tvec[2]);
printf("rotation vector: %0.5f, %0.5f, %0.5f \n", rvec[0], rvec[1], rvec[2]);
/* TO-DO: Replace tf dependency with Eigen */
tf::Quaternion board_quat(tf::Vector3(rvec[0],rvec[1],rvec[2]), theta);
board_quat.normalize();
tf::Matrix3x3 board_rot(board_quat);
double roll, pitch, yaw;
board_rot.getEulerYPR(yaw, pitch, roll);
tf::Vector3 q_axis = board_quat.getAxis();
double q_angle = board_quat.getAngle();
double q_w = board_quat.getW();
printf("Frame : %i \n", frame_no);
printf("Point : %02d \n", pose_list[frame_no]);
printf("x: %0.5f, y: %0.5f, z: %0.5f \n", tvec[0], tvec[1], tvec[2]);
printf("roll: %0.5f, pitch: %0.5f, yaw: %0.5f \n", roll, pitch, yaw);
printf("\n");
printf("rotation vector: %0.5f, %0.5f, %0.5f \n", rvec[0], rvec[1], rvec[2]);
printf("rotation angle : %0.5f \n", theta);
printf("\n");
/* Project 3D points to image plane */
std::vector<cv::Point3f> axes;
axes.push_back(cv::Point3f(3*width, 0.0, 0.0));
axes.push_back(cv::Point3f(0.0, 3*width, 0.0));
axes.push_back(cv::Point3f(0.0, 0.0, -3*width));
std::vector<cv::Point2f> framePoints;
std::vector<cv::Point2f> cornerPoints;
cv::projectPoints(axes, rvec, tvec, cameraMat, distCoeffs, framePoints);
cv::projectPoints(boardPoints, rvec, tvec, cameraMat, distCoeffs, cornerPoints);
for (int i=0; i<cornerPoints.size(); i++){
cv::circle(*img, cornerPoints[i],4,CV_RGB(255,0,0),1,CV_AA);
cv::line(*img, cornerPoints[i],cornerPoints[i],CV_RGB(255,0,0),1);
}
/* Draw axes on image */
cv::line(*img,cornerPoints[0],framePoints[0],cv::Scalar(255,0,0),3);
cv::line(*img,cornerPoints[0],framePoints[1],cv::Scalar(0,255,0),3);
cv::line(*img,cornerPoints[0],framePoints[2],cv::Scalar(0,0,255),3);
printf("Press 's' key to save frame ... \n");
cv::imshow("camera",*img);
key = cv::waitKey(0);
if (key == 's') {
printf("Saving frame ...\n");
printf("\n");
FILE* fp = std::fopen(data_filename, "a");
if (fp == 0) {
printf("Failed to open datafile\n");
}
else {
fprintf(fp, "%02d, %0.8f, %0.8f, %0.8f, %0.8f, %0.8f, %0.8f \n", pose_list[frame_no], tvec[0], tvec[1], tvec[2], roll, pitch, yaw);
}
fclose(fp);
char img_name[100];
sprintf (img_name, "%s/image_%03d.png", save_dir, pose_list[frame_no]);
std::cout << "Writing to " << img_name << std::endl;
cv::imwrite(img_name, raw_img);
char img_corner_name[100];
sprintf (img_corner_name, "%s/corners_%03d.png", save_dir, pose_list[frame_no]);
std::cout << "Writing to " << img_corner_name << std::endl;
cv::imwrite(img_corner_name, corner_img);
char img_frame_name[100];
sprintf (img_frame_name, "%s/frame_%03d.png", save_dir, pose_list[frame_no]);
std::cout << "Writing to " << img_frame_name << std::endl;
cv::imwrite(img_frame_name, *img);
std::cout << "Done writing. " << std::endl;
printf("\n");
frame_no++;
}
else {
printf("Continuing...\n");
printf("\n");
}
}
else {
printf("FAILED to find pose.\n");
printf("\n");
}
}
else if (found) {
std::cout << "FOUND CORNERS" << std::endl;
cv::drawChessboardCorners(*img, boardSize, corners, found);
printf("Press any key to continue ... \n");
cv::imshow("camera",*img);
cv::waitKey(0);
frame_no++;
}
else {
printf("FAILED to find corners.\n");
printf("\n");
}
}
void imageCallback(FlyCapture2::Camera *camera) {
cv::Mat image;
cv::namedWindow("camera", CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO);
cvMoveWindow("camera", 500, 10);
cvResizeWindow("camera",1500, 1000);
while(key != 'q')
{
Image rawImage;
err = camera->RetrieveBuffer( &rawImage );
// convert to rgb
Image rgbImage;
rawImage.Convert( FlyCapture2::PIXEL_FORMAT_BGR, &rgbImage );
// convert to OpenCV Mat
unsigned int rowBytes = (double)
rgbImage.GetReceivedDataSize()/(double)rgbImage.GetRows();
image = cv::Mat(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3, rgbImage.GetData(),rowBytes);
if (use_calib) {
// Undistort image
cv::Mat rview, map1, map2;
cv::Size imageSize = image.size();
double alpha = 1; // 0 = zoomed-in, all valid pixels; 1 = invalid pixels are blacked-out
/* Using projection matrix from calibration results in different image */
initUndistortRectifyMap(cameraMat, distCoeffs, cv::Mat(),
getOptimalNewCameraMatrix(cameraMat, distCoeffs, imageSize, alpha, imageSize, 0),
imageSize, CV_16SC2, map1, map2);
remap(image, rview, map1, map2, cv::INTER_LINEAR);
cv::imshow("camera",rview);
key=cv::waitKey(50);
if (key == 'p') {
std::cout << "key-press = " << key << std::endl;
get_pose(&rview);
key=0;
}
}
else {
cv::imshow("camera",image);
key=cv::waitKey(50);
if (key == 'p'){
std::cout << "key-press = " << key << std::endl;
get_pose(&image);
key=0;
}
}
}
}
void get_param(){
/*TO-DO: Place params in config.xml file for run-time read. */
/* Camera serial number */
cam_serial = 14481155;
/* Calibration */
use_calib = true;
rows = 10; // checkerboard dimensions
cols = 10;
width = 0.0254;
calib_file="/home/calib/ptgrey_calib.xml";
/* OpenCV params */
win_size_sp = 11;
max_iter_sp = 100;
eps_sp = 0.001;
use_init_pnp = true;
max_iter_pnp = 1000;
err_pnp = 4.0;
min_inl_pnp = 1.0;
/* Data save directory */
save_dir="/home/data/";
}
std::string get_timestamp(void)
{
struct tm *local_time;
time_t now;
char timestamp[MAX_DATE];
timestamp[0] = '\0';
time (&now);
local_time = localtime(&now);
strftime(timestamp, MAX_DATE, "%X_%m_%d_%Y", local_time);
return std::string(timestamp);
}
int main(int argc, char *argv[])
{
get_param();
std::string t_stamp = get_timestamp();
sprintf (data_filename, "%s/data_%s.out", save_dir, t_stamp.c_str());
std::cout << "data_filename: " << data_filename << std::endl;
FlyCapture2::BusManager busMgr;
PGRGuid guid;
err = busMgr.GetCameraFromSerialNumber(cam_serial, &guid);
if (err != PGRERROR_OK) {
std::cout << "Index error" << std::endl;
return false;
}
// Point Grey cam init
init_cam_capture(pt_grey, guid);
if (use_calib)
load_calib_param();
imageCallback(&pt_grey);
printf("Stopping...\n");
err = pt_grey.StopCapture();
if ( err != PGRERROR_OK )
{
// This may fail when the camera was removed, so don't show
// an error message
}
pt_grey.Disconnect();
}
|
70d4bff99bc0a95c5b5049c1ada719e9f5d3937d
|
[
"Text",
"CMake",
"C++"
] | 3 |
Text
|
saszaz/camera_pose
|
a5576ed0f5e1250a0401068dc23f987c688b2c43
|
ea6bfbf2beb09122f0e7466f5bf62f1549c6c26a
|
refs/heads/master
|
<file_sep><?php
$dir = './';
require_once("common/php/header.php"); ?>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div id="top-content">
<img src="" alt="" />
</div><!-- top-content END -->
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div class="entry-top">
遊びたい新着記事
</div><!-- top-content END -->
</div>
<div class="col-xs-12">
<div class="content-box">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div class="intro-text">
<p>このクソ暑い中、サバゲーに行ってきました。<br />さすがにこの時期になると野外フィールドは忍耐力との勝負になりますね</p>
<p>このクソ暑い中、サバゲーに行ってきました。<br />さすがにこの時期になると野外フィールドは忍耐力との勝負になりますね</p>
</div>
</div>
<div class="col-xs-5 column-main-img">
<img src="common/img/blog01.jpg" alt="今週の遊んできた【Part1】" />
</div>
<div class="col-xs-7">
<div class="num-day">
2015/07/25
</div>
<div class="column-ttl">
<a href="">今週の遊んできた【Part1】</a>
</div>
</div>
<div class="col-xs-12">
<div class="user-info-box">
<div class="category-info">
<i class="fa fa-folder-open"></i>サバゲー
</div>
<div class="comment-info">
<i class="fa fa-comment"></i>コメント:4件
</div>
</div>
<div class="tags-info-box">
<div class="tags-style">
今週の遊んできた
</div>
<div class="tags-style">
アウトドア
</div>
<div class="tags-style">
季節:夏
</div>
</div><!-- tags-info-box -->
</div>
</div>
</div>
</div><!-- column-box END -->
</div><!-- col-xs-12 END -->
<div class="col-xs-12">
<div class="content-box">
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div class="intro-text">
<p>このクソ暑い中、サバゲーに行ってきました。<br />さすがにこの時期になると野外フィールドは忍耐力との勝負になりますね</p>
</div>
</div>
<div class="col-xs-5 column-main-img">
<img src="common/img/blog01.jpg" alt="今週の遊んできた【Part1】" />
</div>
<div class="col-xs-7">
<div class="num-day">
2015/07/25
</div>
<div class="column-ttl">
<a href="">今週の遊んできた【Part1】</a>
</div>
</div>
<div class="col-xs-12">
<div class="user-info-box">
<div class="category-info">
<i class="fa fa-folder-open"></i>サバゲー
</div>
<div class="comment-info">
<i class="fa fa-comment"></i>コメント:4件
</div>
</div>
<div class="tags-info-box">
<div class="tags-style">
今週の遊んできた
</div>
<div class="tags-style">
アウトドア
</div>
<div class="tags-style">
季節:夏
</div>
</div><!-- tags-info-box -->
</div>
</div>
</div>
</div><!-- column-box END -->
</div><!-- col-xs-12 END -->
<div class="col-xs-12">
<div id="more-column">
新着記事を一覧表示<i class="fa fa-arrow-circle-right"></i>
</div>
</div>
<!-- コラム END -->
<div class="col-xs-12">
<div class="entry-top">
カテゴリー検索
</div><!-- top-content END -->
</div>
<div class="col-xs-12">
<div class="content-box">
<div class="panel-body">
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="InputEmail">メール・アドレス</label>
<input type="email" class="form-control" id="InputEmail" placeholder="メール・アドレス">
</div>
<div class="form-group">
<label class="sr-only" for="InputSelect">カテゴリー選択</label>
<select class="form-control" id="InputSelect">
<option>交遊会</option>
<option>サバゲー</option>
<option>TVゲーム</option>
<option>飲食</option>
</select>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxA"> A
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<button type="submit" class="btn btn-default">検索</button>
</form>
</div>
</div>
</div>
<div class="col-xs-12">
<div class="entry-top">
ニュース一覧
</div><!-- top-content END -->
</div>
<div class="col-xs-12">
<div class="content-box">
<ul id="feed"></ul>
</div>
</div>
</div>
</div>
<!-- ↓固定コンテンツ footer -->
<?php require_once("common/php/footer.php"); ?>
<file_sep>
google.load("feeds", "1");
function initialize() {
var feedurl = "http://www.saba-navi.com/feed/";
var feed = new google.feeds.Feed(feedurl);
feed.setNumEntries(10);
feed.load(function (result){
if (!result.error){
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var title = '<li><h3><a href="' + entry.link + '">' + entry.title + '</a></h3></li>';
var conte = '<li>' + entry.contentSnippet + '</li>';
var dates = '<li>' + entry.publishedDate + '</li>';
$('ul#feed').append('<li class="post"><ul>' + title + dates + '</ul></li>');
}
}
});
}
google.setOnLoadCallback(initialize);
<file_sep>$(function(){
//最初にテキスト範囲に追加
$("div.text:first").addClass("tgt");
// ここで文字を<span></span>で囲む
$('.tgt').children().andSelf().contents().each(function() {
if (this.nodeType == 3) {
$(this).replaceWith($(this).text().replace(/(\S)/g, '<span>$1</span>'));
}
});
// 一文字ずつフェードインさせる
$('.tgt:first').css({'opacity':1});
for (var i = 0; i <= $('.tgt:first').children().size(); i++) {
$('.tgt').children('span:eq('+i+')').delay(50*i).animate({'opacity':1},50);
console.log('firstText:'+i);
};
//テキスト範囲をクリック 一回目以降、テキスト
$(".text_area").on("click",function () {
secondName = $("div.chara_name:first").html();
secondText = $("div.text:first").html();
nextText = $('.tgt:first').children();
console.log('nextText:'+i);
//バックログ移動 chara_name
$("div.text_area_after").append(secondName);
$("div.chara_name:first").remove();
//バックログ移動 text
$("div.text_area_after").append(secondText);
$("div.text:first").remove();
//次のテキスト準備
$("div.text_hidden:first").removeClass("text_hidden");
$("div.chara_name:first").addClass("dis_on");
$("div.text:first").addClass("tgt");
// ここで文字を<span></span>で囲む
$('.tgt').children().andSelf().contents().each(function() {
if (this.nodeType == 3) {
$(this).replaceWith($(this).text().replace(/(\S)/g, '<span>$1</span>'));
}
});
// 一文字ずつフェードインさせる
$('.tgt:first').css({'opacity':1});
for (var i = 0; i <= $(nextText).size(); i++) {
$('.tgt:first').children('span:eq('+i+')').delay(50*i).animate({'opacity':1},50);
};
});
//テキスト内確認
$(".text").each(function(i, elem) {
console.log(i + ': ' + $(elem).text());
});
//バックログ
$('.content_after_btn').on("click",function(){
$(".content_after").toggle("dis_on");
});
});
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>無題ドキュメント</title>
<link href="<?= $dir ?>common/css/reset.css" rel="stylesheet">
<link href="<?= $dir ?>common/css/bootstrap.min.css" rel="stylesheet">
<link href="<?= $dir ?>common/css/font-awesome.min.css" rel="stylesheet">
<link href="<?= $dir ?>common/css/common.css" rel="stylesheet">
<link href="<?= $dir ?>common/css/general.css" rel="stylesheet">
<link href="style/css/local.css" rel="stylesheet">
<script src="<?= $dir ?>common/js/jquery-1.11.3.min.js"></script>
<script src="<?= $dir ?>common/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="<?= $dir ?>common/js/rss.js"></script>
</head>
<body onload="initialize()">
<header>
<div id="sp-header" class="cf">
<div id="sp-header-text">
<p>初心者のための初心者による趣味応援サイト</p>
</div>
<div id="sp-header-logo">
<h1>
<img src="<?= $dir ?>common/img/logo.png" alt="遊びたい Life is Enjoy" />
</h1>
</div>
<div class="sp-menu-btn">
<i class="fa fa-bars"></i>
</div>
</div><!-- sp-header END -->
<!-- <ul id="sp-header-navi" class="cf">
<li>カテゴリ</li>
<li>タグ別</li>
<li>ABOUT</li>
</ul> -->
</header>
<div class="pankuz-box">
<ul class="cf">
<li class="pankuz-style"><i class="fa fa-home"></i>ホーム</li>
</ul>
</div>
<!-- ↑固定コンテンツ header --> <file_sep><?php
$dir = '../';
require_once("../common/php/header.php"); ?>
<div class="container-fluid">
<div class="row">
<div class="col-xs-1 paging-style-box">
<i class="fa fa-angle-double-left"></i>
</div>
<div class="paging-style-box col-xs-5">
<a href="">今週の遊んできた【Part1】</a>
</div>
<div class="paging-style-box col-xs-5">
<a href="">今週の遊んできた【Part1】</a>
</div>
<div class="col-xs-1 paging-style-box">
<i class="fa fa-angle-double-right"></i>
</div>
</div>
</div>
<div class="container-fluid column-detail-box">
<div class="row">
<div class="col-xs-12">
<div class="entry-top">
今週の遊んできた【Part1】
</div><!-- top-content END -->
<div class="user-info-box">
<div class="category-info">
<i class="fa fa-folder-open"></i>サバゲー
</div>
<div class="comment-info">
<i class="fa fa-comment"></i>コメント:4件
</div>
</div>
<div class="tags-info-box">
<div class="tags-style">
今週の遊んできた
</div>
<div class="tags-style">
アウトドア
</div>
<div class="tags-style">
季節:夏
</div>
</div><!-- tags-info-box -->
<div class="column-main-img">
<img src="./style/img/column-main.jpg" alt="" />
</div>
</div>
<div class="col-xs-12">
<ol class="column-index">
<li>初の夏サバゲー</li>
<li>襲い来る熱波</li>
<li>削れゆく集中</li>
<li>休息のアイス(笑)</li>
</ol>
</div>
<div class="col-xs-12">
<h3 class="column-ttl">初の夏サバゲー</h3>
<div class="column-txt">
<p>矢嶋です。そろそろ、学生の皆さんは夏休みが近くなってきて、ウズウズしているのではないでしょうか?笑</p>
<p>私もいつも通り仕事よりも遊びに体力を振り分け、遊んでおります。という訳で今週の遊んできたは、サバゲーです。<br>
サバゲフィールド「CIMAX」での定例会に参加をしてきました。</p>
</div>
</div>
<div class="col-xs-12">
<h3 class="column-ttl">襲い来る熱波</h3>
<div class="column-txt">
<p>矢嶋です。そろそろ、学生の皆さんは夏休みが近くなってきて、ウズウズしているのではないでしょうか?笑</p>
<p>私もいつも通り仕事よりも遊びに体力を振り分け、遊んでおります。という訳で今週の遊んできたは、サバゲーです。<br>
サバゲフィールド「CIMAX」での定例会に参加をしてきました。</p>
</div>
</div>
<div class="col-xs-12">
<h3 class="column-ttl">削れゆく集中力</h3>
<div class="column-txt">
<p>矢嶋です。そろそろ、学生の皆さんは夏休みが近くなってきて、ウズウズしているのではないでしょうか?笑</p>
<p>私もいつも通り仕事よりも遊びに体力を振り分け、遊んでおります。という訳で今週の遊んできたは、サバゲーです。<br>
サバゲフィールド「CIMAX」での定例会に参加をしてきました。</p>
</div>
</div>
<div class="col-xs-12">
<h3 class="column-ttl">休息のアイス</h3>
<div class="column-txt">
<p>矢嶋です。そろそろ、学生の皆さんは夏休みが近くなってきて、ウズウズしているのではないでしょうか?笑</p>
<p>私もいつも通り仕事よりも遊びに体力を振り分け、遊んでおります。という訳で今週の遊んできたは、サバゲーです。<br>
サバゲフィールド「CIMAX」での定例会に参加をしてきました。</p>
</div>
</div>
</div>
</div>
<!-- コラム END -->
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<div class="entry-top">
コメント一覧
</div><!-- top-content END -->
</div>
<div class="col-xs-12">
<div class="content-box">
</div>
</div>
<div class="col-xs-12">
<div class="entry-top">
記事を指定検索
</div><!-- top-content END -->
</div>
<div class="col-xs-12">
<div class="content-box">
<div class="panel-body">
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="InputEmail">ワードから検索</label>
<input type="email" class="form-control" id="InputEmail" placeholder="メール・アドレス">
</div>
<div class="form-group">
<label class="sr-only" for="InputSelect">カテゴリー選択</label>
<select class="form-control" id="InputSelect">
<option>交遊会</option>
<option>サバゲー</option>
<option>TVゲーム</option>
<option>飲食</option>
</select>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxA"> A
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<div class="checkbox checkbox-add">
<label>
<input type="checkbox" value="checkboxB"> B
</label>
</div>
<button type="submit" class="btn btn-default">検索</button>
</form>
</div>
</div>
</div>
<div class="col-xs-12">
<div class="entry-top">
関連ニュース一覧
</div><!-- top-content END -->
</div>
<div class="col-xs-12">
<div class="content-box">
<ul id="feed"></ul>
</div>
</div>
</div>
</div>
<!-- ↓固定コンテンツ footer -->
<?php require_once("../common/php/footer.php"); ?>
|
51213fc90729ad03438e87a65ae0516debd790b7
|
[
"JavaScript",
"PHP"
] | 5 |
PHP
|
kurona0519/test
|
cbc50e0e9be63a38f29286eadc4fee2750dfe7a2
|
e61e4760ef45e26a95347994f1b01309acf2b0d1
|
refs/heads/master
|
<file_sep>class AddExerciseIdToReviews < ActiveRecord::Migration
def change
add_column :reviews, :exercise_id, :integer
end
end
<file_sep># Reactant
React on Rails
<file_sep>Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root 'site#index'
namespace :api do
namespace :v1 do
resources :exercises
resources :reviews, only: [:new, :create]
end
end
end
<file_sep>class Api::V1::ExercisesController < Api::V1::BaseController
def index
respond_with Exercise.all
end
def create
respond_with :api, :v1, Exercise.create(exercise_params)
end
def update
exercise = Exercise.find(params[:id])
exercise.update_attributes(exercise_params)
respond_with exercise, json: exercise
end
def destroy
respond_with Exercise.destroy(params[:id])
end
private
def exercise_params
params.require(:exercise).permit(:category, :name, :description, :rating)
end
end<file_sep>var AllExercises = React.createClass({
handleDelete(id) {
this.props.handleDelete(id);
},
onUpdate(exercise) {
this.props.onUpdate(exercise);
},
render() {
var exercises = this.props.exercises.map((exercise) => {
return (
<div key={exercise.id} >
<Exercise exercise={exercise}
handleDelete={this.handleDelete.bind(this, exercise.id)}
onUpdate={this.onUpdate} />
</div>
);
});
return (
<div>
<h2>All Exercises</h2>
{ exercises }
</div>
)
}
});<file_sep>var Body = React.createClass({
getInitialState() {
return { exercises: [] }
},
componentDidMount() {
$.getJSON('/api/v1/exercises.json', (response) => { this.setState({ exercises: response }) });
},
handleExerciseSubmit(exercise) {
var newState = this.state.exercises.concat(exercise);
this.setState({ exercises: newState });
},
handleExerciseDelete(id) {
$.ajax({
url: `/api/v1/exercises/${id}`,
type: 'DELETE',
success: () => {
this.removeExerciseById(id);
}
});
},
handleExerciseUpdate(exercise) {
$.ajax({
url: `/api/v1/exercises/${exercise.id}`,
type: 'PUT',
data: { exercise: exercise },
success: () => {
this.updateExercises(exercise);
}
});
},
updateExercises(exercise) {
var exercises = this.state.exercises.filter((i) => {
return i.id != exercise.id
});
exercises.push(exercise);
this.setState({exercises: exercises});
},
removeExerciseById(id) {
var newState = this.state.exercises.filter((exercise) => {
return exercise.id != id;
});
this.setState({ exercises: newState });
},
render() {
return (
<div>
<NewExercise handleSubmit={this.handleExerciseSubmit} />
<AllExercises exercises={this.state.exercises} handleDelete={this.handleExerciseDelete} onUpdate={this.handleExerciseUpdate} />
</div>
)
}
});<file_sep>var NewExercise = React.createClass({
handleClick() {
var name = this.refs.name.value;
var description = this.refs.description.value;
$.ajax({
url: '/api/v1/exercises',
type: 'POST',
data: { exercise: { name: name, description: description } },
success: (exercise) => {
this.props.handleSubmit(exercise);
}
})
},
render() {
return (
<div>
<input ref='name' placeholder='Exercise name' />
<input ref='description' placeholder='Description' />
<button onClick={this.handleClick}>Submit</button>
</div>
)
}
})<file_sep>var Header = React.createClass({
render() {
return (
<header>
<a class="home_link">Reactant!</a>
</header>
)
}
});<file_sep>class Exercise < ActiveRecord::Base
has_many :reviews, dependent: :destroy
CATEGORIES = ['weights', 'cardio', 'flexibility', 'coordination', 'bodyweight']
end<file_sep>class Api::V1::ReviewsController < Api::V1::BaseController
def new
@exercise = Exercise.find(params[:exercise_id])
@review = Review.new
end
def create
@review = Review.create(review_params)
if @review.save
redirect_to exercises_path
else
flash[:alert] = "Review couldn't be saved"
end
end
private
def review_params
params.require(:review).permit(:name, :comments, :rating, :exercise_id)
end
end
|
44ae13f7955ef3bb3429f1299d6fe3942ddabb29
|
[
"Markdown",
"JavaScript",
"Ruby"
] | 10 |
Ruby
|
glredig/reactant
|
6569664d4241a3b5c55aa23409059c1d7eb3fde3
|
f57c59960eb0f10c32b3c4b480e308c15e649cff
|
refs/heads/master
|
<file_sep>import { ArtistDao } from './src/main/dao/artist-dao';
let artistDao = new ArtistDao();
artistDao.getAllArtist().then(artArray => console.log(artArray));
// console.log("Hey World!");<file_sep>export const chuckNorrisTypes = {
BUY_JOKE: 'CHUCK_NORRIS_BUY_JOKE'
}
export const buyJoke = () => async (dispatch) => {
try {
const resp = await fetch('http://api.icndb.com/jokes/random?limitTo=[nerdy]');
const body = await resp.json();
const joke = body.value.joke;
dispatch({
payload: {
joke
},
type: chuckNorrisTypes.BUY_JOKE
})
} catch (err) {
console.log(err);
}
}<file_sep>import express from 'express';
import bodyParser = require('body-parser');
import { userRouter } from './routers/users.router';
import session from 'express-session';
import { authRouter } from './routers/auth.router';
const app = express();
// Setup body-parser
app.use(bodyParser.json());
// logging middleware
app.use((req, res, next) => {
console.log(`request was made with url: ${req.path};
and method: ${req.method}`);
console.log(req.headers);
next();
});
// Setup express to attach sessions
const sess = {
secret: 'potato',
cookie: { secure: false},
resave: false,
saveUninitialized: false
};
// prior to this req.session is nothing after this req.session is an object
app.use(session(sess));
// Connects authRouter.ts to the url /auth
app.use('/auth', authRouter);
app.use('/users', userRouter);
/*app.get('/users', (req, res) => {
res.send('Here are your users');
})*/
/*app.post('/users', (req, res) => {
const user = req.body;
console.log(user);
res.sendStatus(201);
})*/
/*
app.get('/pokemon', (req, res) => {
res.send('Here are your pokemon');
})
app.get('/pokemon-moves', (req, res) => {
res.send('Here are all the available pokemon moves');
})
*/
app.listen(3000);
console.log('Application running on port 3000');<file_sep>// See his verion of num 11
let arr = [];<file_sep>import { IClickerState } from ".";
import { clickerTypes } from "../actions/clicker/clicker.actions";
import { chuckNorrisTypes } from "../actions/chuck-norris/ChuckNorris.actions";
const initialState: IClickerState = {
clicks: 1500
}
export const clickerReducer = (state = initialState, action: any) => {
switch (action.type) {
case clickerTypes.INCREMENT:
return {
...state,
clicks: action.payload.amount + state.clicks
}
case chuckNorrisTypes.BUY_JOKE:
return {
...state,
clicks: state.clicks - 1000
}
}
return state;
}<file_sep>// Normally you would have your interface in a seperate file.
interface Plant{
color: string,
grow: (resource: any) => void
}
class VenusFlyTrap implements Plant{
color = '';
lifecycle = 'yearly';
grow = () => {
console.log(`Plant is growing and color is ${this.color}`);
}
constructor(color: string){
this.color = color;
}
}
let myPlant: Plant = new VenusFlyTrap('green');
console.log(myPlant);
myPlant.grow('');
myPlant = {
color: `blue`,
grow: (resource) =>{
}
}
// Object literals will not allow the JS feature of dynamically adding fields
// TS will enforce the rules basedon the class/interface structure
// myPlant.newField = 'whatever';<file_sep>import { User } from './user';
import { PokemonMove } from './pokemon-move';
export class Pokemon {
id: number;
name: string;
level: number;
type: string[];
moves: PokemonMove[];
trainer: User;
constructor(id = 0, name = '', lvl = 0, type: string[] = [], moves: PokemonMove[], trainer?: User) {
this.name = name;
this.level = lvl;
this.type = type;
this.moves = moves;
this.trainer = trainer;
}
}<file_sep>function bubble(event, id) {
console.log(id);
}
/*document.getElementById("one-c").addEventListener('click', () => {
console.log(1);
},
true // Set to capturing
);*/
document.getElementById("two-c").addEventListener('click', () => {
//console.log(2);
event.stopPropagation();
});<file_sep>export class PokemonMove {
id: number;
name: string;
type: string;
powerPoints: number;
damage: number;
constructor(id = 0, name = '', type = '', powerPoints = 0, damage = 0) {
this.id = id;
this.type = type;
this.powerPoints = powerPoints;
this.damage = damage;
}
}<file_sep>let arr = [5, 25, 'Hello', {a: 'object'}, true];
console.log(arr);
let index3 = arr[3];
console.log(index);
arr.push('potato');
console.log(arr);
arr.unshift('egg');
console.log(arr)
arr.splice(2, 0, "sweet potato");
console.log(arr);
for (let i = 0; i < arr.length; i++) {
console.log(`Index = ${i}, Element = ${arr[i]}`);
}
// Enhanced For Loop, For Each Loop
for (const element of arr){
console.log(element);
}<file_sep>export function authMiddleware(req, res, next) {
const user = req.session.user;
if (user && user.role === 'admin') {
next();
} else {
res.sendStatus(401);
}
}<file_sep>import { IClickerState, IChuckNorrisState } from ".";
import { clickerTypes } from "../actions/clicker/clicker.actions";
import { chuckNorrisTypes } from "../actions/chuck-norris/ChuckNorris.actions";
const initialState: IChuckNorrisState = {
joke: 'A snake bit chuck norris after 5 painful days the snake died'
}
export const chuckNorrisReducer = (state = initialState, action: any) => {
switch (action.type) {
case chuckNorrisTypes.BUY_JOKE:
return {
...state,
joke: action.payload.joke
}
}
return state;
}<file_sep>import {add, multiply} from './calculator';
export function doMath(one, two, three){
return add(multiply(one, two), three);
}<file_sep>import { combineReducers } from 'redux';
import { clickerReducer } from "./Clicker.reducer";
import { chuckNorrisReducer } from "./ChuckNorris.reducer";
export interface IClickerState {
clicks: number
}
export interface IChuckNorrisState {
joke: string
}
export interface IState {
clicker: IClickerState,
chuckNorris: IChuckNorrisState
}
export const state = combineReducers<IState>({
clicker: clickerReducer,
chuckNorris: chuckNorrisReducer
})<file_sep>/**
* In ES6 JS introduced classes.
*/
class Bike {
constructor(frontGears, backGears, material){
this.frontGears = frontGears;
this.backGears = backGears;
this.material = material;
// there is a difference when the function is included in the constructor - explore this
}
ride() {
console.log('Woohoo, you\'re riding the bike!');
}
}
let myBike = new Bike(3, 7, 'carbon');
console.log(myBike);<file_sep>select name from track where trackid in
(select trackid from playlisttrack where playlistid in
(select playlistid from playlisttrack where trackid in
(select trackid from track where albumid in
(select albumid from album where artistid =
(select artistid from artist where name = 'AC/DC')
)
)
)
) and trackid not in (select trackid from track where albumid in
(select albumid from album where artistid =
(select artistid from artist where name = 'AC/DC')));<file_sep>// We can control the flow of code through various means
// If statements
let a = true;
if(a){
console.log('a is true');
} else{
console('a is false.');
}
let b = false;
if(a && b){
console.log('a and b are both true');
} else if (a && !b){
console.log('a is true and b is false.')
}else{
console.log('This is the default statement');
}
let w = true;
let x = 1;
while(w){
console.log('Inside while loop ' + x);
const random = Math.floor(Math.random() * 5);
x++;
if(random === 3){
w = false;
}
}
let doW = false;
do{
console.log('Do ... while');
const random = Math.floor(Math.random() * 5);
x++;
if(random === 3){
doW = false;
}else{
doW = true;
}
}while(doW);
for(let i =0; i < 5; i++){
console.log(`For Loop: ${i}`);
}
console.log('For Loop Over');
let switchCase = 'hello';
switch (switchCase) {
case 'hello':
console.log('world');
break;
case 5:
console.log('number');
break;
default:
break;
}
// Terniary if true do b4 colon (if else statement with return statements)
// Get complicated quickly
let result = ( 5 < 25) ? 't' : false;
console.log(result);<file_sep>/**
* In a boolean context if we have a noon-boolean type JS will use a set of rules to determine if it
* should be true or false.
* 0, '', null, undefined, NaN, false evaluate to false everything else evaluates to true.
* @param {*} val
*/
function truthyFalsy(val){
console.log(`The value ${val} is of type ${typeof(val)} and has a truthy value of ${!!val}`);
}
truthyFalsy(0);
truthyFalsy('0');
truthyFalsy('Hello');
truthyFalsy(truthyFalsy);
truthyFalsy('');
truthyFalsy(true);
truthyFalsy(undefined);
truthyFalsy(null);
truthyFalsy({});
truthyFalsy(NaN);
truthyFalsy('false');
truthyFalsy(-1);
// Prove it
if('hello'){
console.log('Hello is truthy');
}<file_sep>// a can contain a number or a string
let a: number | string = 5;
a = 'Hello';
console.log(a);
function add(one: number, two: number): number{
return one + two;
}
a = add(5, 25);
console.log(a);<file_sep>import React, { Component } from "react";
import { relativeTimeRounding } from 'moment';
class AuthComponent extends Component {
constructor() {
super();
this.state = {
username: '',
password: ''
}
}
login(event){
event.preventDefault();
}
updateVisitor(attr, event) {
console.log(attr + " == " + event.target.value);
}
render() {
return (
<div className="container">
<h1>Login Form</h1>
<form>
<label id="usernameLabel">Username</label>
<input onChange={this.updateVisitor.bind(this, 'username')} className="form-control" type="text" id="usernameInput" required />
<label>Password</label>
<input onChange={this.updateVisitor.bind(this, 'password')} className="form-control" type="password" id="passwordInput" required />
<button onClick={this.login.bind(this)}>Login</button>
</form>
</div>
)
}
}
export default AuthComponent;<file_sep>function testEquality(first, second){
console.log(`One is type: ${typeof(first)} and Value: ${first}
Two is type: ${typeof(second)} and Value: ${second}
One == Two returns ${first == second}
One === Two returns ${first === second}`);
}
testEquality(0, '0');<file_sep>class tester {
constructor(x, y){
this.x = x;
this.y = y;
}
}
let arr = ['x','y'];
let z = new tester(15, 'killinem');
console.log(`The x version: ${z[arr[0]]}`);<file_sep>import AuthComponent from './AuthComponent';
export {
AuthComponent
}<file_sep>Date.prototype.getUnixTime = function () { return this.getTime() / 1000 | 0 };
if (!Date.now) Date.now = function () { return new Date(); }
Date.time = function () { return Date.now().getUnixTime(); }
let today = new Date;
console.log("Date today, basic object", today);
console.log("Date today, get time/1000", Math.round(today.getTime()));
console.log("Date in millisesonds: ", today.getMilliseconds());<file_sep>import express from 'express';
import bodyParser from 'body-parser';
import { connectURL } from './connect';
const app = express();
app.use(bodyParser.json());
// Connection to db
const pg = require('pg');
// databaseName://userName:password@endpoint
const connection = connectURL();
const client = new pg.Client(connection);
client.connect();
app.post('/login', (req, res) => {
console.log('POST REQUEST');
client.query(`SELECT user_id FROM users WHERE username='${req.body['username']}' AND user_pass='${req.body['user_pass']}';`, (err, response) => {
if (err) {
console.log(`Error: ${err.stack}`);
} else {
console.log(`Response:\nuser_id: ${response.rows[0]['user_id']}`);
res.json(response.rows);
}
})
});
app.listen(3000);
console.log('Application is running on port 3000');
<file_sep>// Understanding the foreach and how to manipulate the array by id
// Also looking into the ternary operator
function bubbleSort(numArray) {
let finished;
do {
finished = true;
numArray.forEach((element, i, numArray) => {
//DEBUG console.log(`Index: ${i}, Value: ${element}, Next Value: ${numArray[i + 1]}`);
// Can not use ternary operator here since if statement does not return anything
if(element > numArray[i + 1]){
let temp = numArray[i + 1];
numArray[i + 1] = element;
numArray[i] = temp;
//DEBUG console.log(`Current Element: ${element}`);
finished = false;
}
});
} while (!finished);
return numArray;
}
let arr = [45, 61, 22, 13, 199, 65, 172, 11];
console.log(bubbleSort(arr));<file_sep>import express from 'express';
import { Pool } from 'pg';
import bodyParser from 'body-parser';
import bcrypt from 'bcrypt';
// const app = express();
// app.use(bodyParser.json());
let username = 'lolo';
let password = '<PASSWORD>';
// Connect to db
async function connectDB(username, password) {
const creds = {
database: 'postgres',
host: 'project0.c5jn9s8xhixw.us-east-2.rds.amazonaws.com',
user: 'admin1',
password: '<PASSWORD>',
port: 5433
};
// Hash password and store to db
bcrypt.hash(password, 10, async function(err, hash) {
console.log('Inside the bcrypt function');
let result;
try {
const pool = await new Pool(creds);
let client = await pool.connect();
console.log('Connected to the db');
result = await client.query(
`Update users set password=$1 where user_id=3 RETURNING *;`,
[hash]
);
console.log('Got response from query');
await client.release();
console.log('The result from all this is:\n', result.rows);
// return result;
} catch (error) {
console.log('Error, shit fucked up.\n', error);
}
console.log('Y it wont end:\n', result.rows);
return result;
});
}
async function response(usr, pswd) {
console.log('In 1st funct');
let resp = await connectDB(username, password);
console.log(resp);
}
async function convertHash(username, password) {
// Typically you would need to get the hashed password from the db
// but i'm lazy sooo I'll just hard code it
const hash = '$2b$10$/F.TEWeQPzcS/sq2xMBps.lqfg4p6KsHCHtfA3VdI/jEFLudMlvkK';
console.log('wtf');
await bcrypt.compare(
password,
hash,
await function(err, res) {
if (res) {
console.log('User is validated', res);
} else {
console.log(err);
}
}
);
}
async function doInNormalOrder(username, password) {
await response(username, password);
await convertHash(username, password);
}
doInNormalOrder(username, password);
/* app.post('', (req, res) => {
}); */
<file_sep>let string = "Hello"; // Double Quotes
let str = 'World'; // Single Quotes ** default
let num = 75;
let templateLiteral = `
template literals were introduced with ES6
and allow for multi line strings they also
allow for string interpolation for instance
string = ${string}
str = ${str}
num = ${num}
25 * 3241234 = ${25 * 3241234}`;
console.log(templateLiteral);<file_sep>const a = true;
const b = 'Hello';
// If a = truthy return a; If a = falsey return b;
// Not really about being true
const result = a || b;
console.log(result);<file_sep>import express from 'express';
import { User } from '../models/user';
import { findAll } from '../dao/user.dao';
// import { authMiddleware } from '../middleware/auth.middleware';
// User data - it is NOT persistant.
const peter = new User(1, 'peter', 'whatup', 'Peter');
const kyle = new User(2, 'kylekills', 'kpassword', 'Kyle');
const users = [kyle, peter];
// We will assume all routes defined with this router start with '/users
export const userRouter = express.Router();
// /users - find all
userRouter.get('', [
// authMiddleware,
async (req, res) => {
// res.json(users);
try {
const users = await findAll();
res.json(users);
} catch (error) {
res.sendStatus(500);
}
}]);
// /users - find by id
userRouter.get('/:id', (req, res) => {
console.log(req.params.id);
const idParam = +req.params.id;
const user = users.find(ele => ele.id === +req.params.id);
res.json(user);
});
// /users - add new user
userRouter.post('', (req, res) => {
users.push(req.body);
res.sendStatus(201);
});<file_sep>"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var _react = require("react");
var React = _interopRequire(_react);
var Component = _react.Component;
var relativeTimeRounding = require("moment").relativeTimeRounding;
var AuthComponent = (function (Component) {
function AuthComponent() {
_classCallCheck(this, AuthComponent);
if (Component != null) {
Component.apply(this, arguments);
}
}
_inherits(AuthComponent, Component);
_prototypeProperties(AuthComponent, null, {
render: {
value: function render() {
return React.createElement(
"div",
{ className: "container" },
React.createElement(
"h1",
null,
"Login Form"
),
React.createElement(
"form",
null,
React.createElement(
"label",
{ id: "usernameLabel" },
"Username"
),
React.createElement("input", { className: "form-control", type: "text", id: "usernameInput", required: true }),
React.createElement(
"label",
null,
"<PASSWORD>"
),
React.createElement("input", { className: "form-control", type: "password", id: "passwordInput", required: true }),
React.createElement(
"button",
null,
"Login"
)
)
);
},
writable: true,
configurable: true
}
});
return AuthComponent;
})(Component);
module.exports = AuthComponent;<file_sep>// In JS you can have default val if a param is not provided
function defaultValues(one, two = 10, three = 15){
console.log('one = ' + one, 'two = ' + two, three = 15);
}
defaultValues(2);
defaultValues();
defaultValues(5, 2);
defaultValues(5, undefined, 2);<file_sep>/*
* Vars in JS are Loosely Typed and can be changed by simply assign
* the object to the variable
*/
let a = 5;
console.log(a);
a = 'Hello';
console.log(a);<file_sep>// Tradiitonally this is how people created classes in JS
function Bike(frontGears, backGears, material){
this.frontGears = frontGears;
this.backGears = backGears;
this.material = material;
this.ride = () => {
console.log('Woohoo, you\'re riding the bike!');
}
}
let myBike = new Bike(3, 7, 'carbon');
let otherBike = new Bike(1, 3, 'aluminum');
console.log(myBike);
console.log('Other Bike: ', otherBike);
myBike.ride();<file_sep>// This will handle all possible accessing the db for the artist table
// Grab all artists
import { Artist } from '../models/artist';
import { SessionFactory } from '../util/session-factory';
export class ArtistDao {
// The async ... Promise - the promise is saying you will get something eventually
// and it will be an array of Artist
public async getAllArtist(): Promise<Artist[]> {
let pool = SessionFactory.getConnectionPool();
// Don't know when the connection will be made, so we make a promise
// The await allow us to wait until the connection is made in order to proceed
const client = await pool.connect();
const result = await client.query('SELECT * FROM artist');
return result.rows;
}
}
<file_sep>import express from 'express';
import { resolvePtr } from 'dns';
export const authRouter = express.Router();
authRouter.post('/login', (req, res) => {
if (req.body.username === 'lolo' && req.body.password === '<PASSWORD>') {
const user = {
username: req.body.username,
role: 'admin'
};
req.session.user = user;
res.json(user);
} else if (req.body.username === 'hank' && req.body.password === '<PASSWORD>') {
req.session.role = 'associate';
res.json({
username: req.body.username,
role: 'associate'
});
} else {
res.sendStatus(401);
}
});<file_sep>import { User } from '../models/user';
import { connectionPool } from '../util/connection-util';
export async function findAll(): Promise<User[]> {
const client = await connectionPool.connect();
try {
const result = await client.query('SELECT * FROM users');
return result.rows.map(sql_user => {
console.log(`sql_user`);
return {
id: sql_user.user_id,
username: sql_user.username,
password: '<PASSWORD>',
name: sql_user.name
};
});
} finally {
client.release();
}
}<file_sep>let contents = [{
category: 'fruit',
item: {
name: 'mango',
rating: 8,
price: 1
}},
{category: 'fruit',
item: {
name: 'grapes',
rating: 7,
price: 1.99
}},
{category: 'electronics',
item: {
name: 'Bluetooth Headphones',
rating: 5,
price: 49.99
}},
{category: 'electronics',
item: {
name: 'Stereo',
rating: 7,
price: 79.99
}},
{category: 'furniture',
item: {
name: 'Desk Chair',
rating: 9,
price: 170
}},
{category: 'furniture',
item: {
name: 'Coffee Table',
rating: 4,
price: 74.99
}},
{category: 'fruit',
item: {
name: 'apples',
rating: 4,
price: 1.99
}},
{category: 'fruit',
item: {
name: 'bananas',
rating: 2,
price: 1
}},
{category: 'fruit',
item: {
name: 'avacados',
rating: 3,
price: 2
}},
{category: 'electronics',
item: {
name: 'Laptop',
rating: 7,
price: 799.99
}},
];
let fruits = contents.filter((element) => {
return element.category === 'fruit';
}).map((element) => {
return element.item;
});
console.log(`Original: `, contents);
console.log(fruits);<file_sep>// Declare function and parameters
function add(one , two){
// A function without a return statement will return undefined
return one + two;
}
// Invoke function
let result = add(16, 2);
console.log(result);
// Use arrow notation to create functions
let arrowAdd = (one, two) => {
return one + two;
}
let arrowResult = arrowAdd(25, 2);<file_sep>package com.revature.services;
import java.util.List;
import java.util.Set;
import com.revature.model.Bear;
public interface BearService {
Bear save(Bear b); // add a bear
Bear update(Bear b);
Bear delete(Bear b);
List<Bear> findAll();
Bear findById(int id);
List<Bear> findByCaveId(int caveId);
List<Bear> findByLegs(int legs);
List<Bear> findByColor(String color);
List<Bear> findByBreed(String breed);
List<Bear> findByCaveCaveType(String caveType);
}
<file_sep>// Var, Let Const
// If a variable is outside of all code it will act as a global variable
var g = 10;
let h = "hello";
const c = 'world';
// c = '5'; We will get an error
/*
// Will not allow it to be declared twice. (With var it will not error due to hoisting)
let x = "bitch";
let x = "bitch";*/
function scope(){
if(true){
// Var is scoped to the nearest function keyword and declaration is pulled to the top of its scope
var a = 5;
// Let and Const are scoped by the block they are in.
let b = 10;
}
console.log(a);
console.log(b);
}<file_sep>create table users(
user_id int primary key,
username varchar not null,
user_pass varchar not null
);
insert into users(user_id, username, user_pass)
values (1, 'lolo', 'ask'), (2, 'blake', '<PASSWORD>'), (3, '<PASSWORD>', '<PASSWORD>');<file_sep>var a = "Hello";
let b = " ";
let c = 'World';
console.log(a + b + c);<file_sep>import express from 'express';
import { pokemon } from '../data';
export const pokemonRouter = express.Router();
// Retrieve all pokemon
pokemonRouter.get('', (req, res) => {
res.json(pokemon);
});
// Retrieve all pokemon of a specified type
pokemonRouter.get('/type/:type', (req, res) => {
const pokemonByType = pokemon.filter(poke => poke.type === req.params);
res.json(pokemonByType);
});
pokemonRouter.post('', (req, res) => {
pokemon.push(req.body);
res.status(201);
res.send('Successfully Created Pokemon');
});<file_sep>import { connect } from "react-redux";
import { ChuckNorrisComponent } from "./ChuckNorris.component";
import { IState } from "../../reducers";
import { buyJoke } from "../../actions/chuck-norris/ChuckNorris.actions";
const mapStateToProps = (state: IState) => {
return {
clicks: state.clicker.clicks,
chuckNorris: state.chuckNorris
}
}
const mapDispatchToProps = {
buyJoke
}
export default connect(mapStateToProps, mapDispatchToProps)(ChuckNorrisComponent);<file_sep>import { Pokemon } from './models/pokemon';
import { User } from './models/user';
import { PokemonMove } from './models/pokemon-move';
const peter = new User(1, 'peter', 'whatup', 'Peter');
const kyle = new User(2, 'kylekills', 'kpassword', 'Kyle');
const slash = new PokemonMove(1, 'slash', 'normal', 25, 10);
const hyperBeam = new PokemonMove(2, 'hyper beam', 'normal', 10, 100);
const blastBurn = new PokemonMove(3, 'blast burn', 'fire', 10, 30);
const surf = new PokemonMove(4, 'surf', 'water', 20, 75);
export let pokemon: Pokemon[] = [
new Pokemon(4, 'Charmander', 5, ['fire'], [slash, blastBurn], peter),
new Pokemon(7, 'Squirtle', 5, ['water'], [hyperBeam, surf], kyle)
];
console.log(pokemon[0]);<file_sep>const obj = {
a: 1,
b: 'hello',
c: 'c'
}
const obj2 = {
... obj,
a: 55,
added: 'added'
}
console.log(obj2);
console.log(obj);
// Arrays
const arr = [1, 22, 2];
const arr2 = [13, ...arr, 4];
console.log(arr);
console.log(arr2);
|
32582ab625cdf3635a48ecad9a74d9024567531a
|
[
"JavaScript",
"SQL",
"TypeScript",
"Java"
] | 47 |
TypeScript
|
loloangela/rev-demo
|
3c4073b2306ef2ef8d5bcdea9b3a30ad6b0d24a5
|
91cbedf6ddf51aa0b44bc50f6fa7d6c2ad52647f
|
refs/heads/master
|
<repo_name>Tofiq-Dawod/page<file_sep>/page 1/Application State.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace page_1
{
public partial class Application_State : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblVisitors.Text = "Number Visitros : "+Application["Visitors"].ToString();
}
protected void btnSend_Click(object sender, EventArgs e)
{
Application["FirstName"] = txt1.Text;
Application["LastName"] = txt2.Text;
Response.Redirect("~/Session.aspx");
}
}
}<file_sep>/page 1/MoveText.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace page_1
{
public partial class page_1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie Cookie = Request.Cookies["PhoneEmail"];
if (Cookie!=null)
{
lblPhone.Text = "NumberPhone : "+Cookie["Phone"];
lblEmail.Text = "Email : "+Cookie["Email"];
}
lblVisitors.Text = "Number Visitros : " + Application["Visitors"].ToString();
if (!IsPostBack)
{
HiddenField1.Value = "Hello : " + Application["FirstName"] + " " + Application["LastName"];
if (Session["Location"] != null && Session["Number"] != null)
{
lblName1.Text = "Location : " + Session["Location"].ToString();
lblAge1.Text = "Your Age :" + Session["Number"].ToString();
}
string name = Request.QueryString.Get("name");
txt1.Text = name;
if (Application["FirstName"] != null && Application["LastName"] != null)
{
lblFirstName.Text = "Hello Mr. " + Application["FirstName"].ToString();
lblLastName.Text = "How Are You : " + Application["LastName"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
txt2.Text = txt1.Text;
txt1.Text = "";
}
}
}<file_sep>/page 1/Query String.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace page_1
{
public partial class Query_String : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblVisitors.Text = "Number Visitros : " + Application["Visitors"].ToString();
}
protected void btn1_Click(object sender, EventArgs e)
{
Response.Redirect("MoveText.aspx?name=" + txt3.Text);
}
}
}<file_sep>/page 1/ChangeCheck.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace page_1
{
public partial class page_2 : System.Web.UI.Page
{
static bool x = true;
protected void Page_Load(object sender, EventArgs e)
{
lblVisitors.Text ="Number Visitors : "+ Application["Visitors"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!chk1.Checked)
{
chk1.Checked = x;
x = false;
}
else {
chk1.Checked = x;
x = true;
}
Response.Write(Session.Timeout.ToString());
}
protected void btnset_Click(object sender, EventArgs e)
{
ViewState["FirstName"] = txt4.Text;
ViewState["LastName"] = txt5.Text;
txt4.Text = txt5.Text = "";
}
protected void btnrestore_Click(object sender, EventArgs e)
{
if (ViewState["FirstName"] != null && ViewState["LastName"] != null)
{
txt4.Text = ViewState["FirstName"].ToString();
txt5.Text = ViewState["LastName"].ToString();
}
}
}
}<file_sep>/page 1/Session.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace page_1
{
public partial class Session : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblVisitors.Text = "Number Visitros : " + Application["Visitors"].ToString();
}
protected void btnSessionTimeOut_Click(object sender, EventArgs e)
{
DisplaySessionTimeOut.Text = ": "+Session.Timeout.ToString()+ " Minutes ";
}
protected void btnSessionId_Click(object sender, EventArgs e)
{
DisplaySessionId.Text = "ID : " + Session.SessionID;
}
protected void btnSend_Click(object sender, EventArgs e)
{
Session["Location"] = txt5.Text;
Session["Number"] = txt6.Text;
Response.Redirect("~/MoveText.aspx");
}
}
}<file_sep>/page 1/Cookie.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace page_1
{
public partial class Cookie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
HttpCookie Cookie = new HttpCookie("PhoneEmail");
Cookie["Phone"] = txtphone.Text;
Cookie["Email"] = txtemail.Text;
Response.Cookies.Add(Cookie);
Response.Redirect("~/Application State.aspx");
}
}
}
|
eeda4b0714fdff69eb422464beb7b113dd2b6b45
|
[
"C#"
] | 6 |
C#
|
Tofiq-Dawod/page
|
b235232c77f63c79484dab908345f7022dea61e1
|
25adf6e66098416caeab1c698cd3184310cb8306
|
refs/heads/master
|
<repo_name>skoenig/roadblock<file_sep>/tasks/org/members.js
var util = require('../../util.js');
module.exports = async function(org, context, config) {
// Get all members in the org and save them
console.log(` ⬇️ Downloading ${org.login} members`);
var membersInOrg = await context.client.Member.getAll(
org.login,
util.barlogger()
);
console.log(` ✅ Saving ${membersInOrg.length} ${org.login} members`);
await context.client.Member.bulkCreate(membersInOrg, org);
util.timePassed(context.start);
return;
};
<file_sep>/tasks/repo/profiles.js
module.exports = async function(repo, context, config) {
await context.client.CommunityProfile.destroy(repo.id);
// Community Profile
var profiles = await context.client.CommunityProfile.getAll(
repo.owner,
repo.name,
config
);
await context.client.CommunityProfile.bulkCreate(
profiles,
context.externalValuesMap
);
return true;
};
<file_sep>/tasks/post/upstream.js
module.exports = async function(context, config) {
if (config.github.url === 'https://api.github.com') {
console.log(
' ⬇️ Downloading external contribution data from external repositories'
);
// Get all our external projects which we might contribute to
await context.client.ExternalContribution.getAndStore(
config.externalProjects
);
// Clean up external contributions so it is only those that fit our members
await context.client.ExternalContribution.removeContributionsWithoutMembers();
}
return true;
};
<file_sep>/tasks/repo/releases.js
module.exports = async function(repo, context, config) {
await context.client.Release.destroy(repo.id);
var releases = await context.client.Release.getAll(repo.owner, repo.name);
await context.client.Release.bulkCreate(releases, context.externalValuesMap);
return true;
};
<file_sep>/cli.js
#!/usr/bin/env node
const cliProgress = require('cli-progress');
const Bootstrap = require('./app/bootstrap.js');
var app;
async function init() {
var args = process.argv.slice(2);
app = new Bootstrap(process.cwd(), __dirname);
if (app.localConfigExists()) {
console.log(' ✅ roadblock.json found - starting roadblock...');
const config = app.config(args);
const context = await app.getContext(config);
return run(config, context);
} else {
return await app.setupDirectory();
}
}
async function run(config, context) {
await app.validateScopes(context);
// pre-process - setup calendar and orgs
// these tasks have no org or repo passed to them.
if (context.tasks.pre.length > 0) {
console.log(
` ℹ️ Running ${context.tasks.pre.length} pre-processing tasks`
);
for (const task of context.tasks.pre) {
var result = await task(context, config);
}
}
if (context.tasks.org.length > 0) {
// fetch all stored organisations to trigger tasks against...
var orgs = await context.client.Organisation.model.findAll();
console.log(
` ℹ️ Running ${context.tasks.org.length} organisation tasks on ${orgs.length} imported github organisations`
);
for (const org of orgs) {
for (const orgTaskFunc of context.tasks.org) {
var result = await orgTaskFunc(org, context, config);
}
}
}
if (context.tasks.repo.length > 0) {
// Collect all stored repositories to run tasks against
var repositories = await context.client.Repository.model.findAll({
where: {
fork: false
}
});
if (repositories.length > 0) {
console.log(
` ℹ️ Running ${context.tasks.repo.length} repository tasks on ${repositories.length} imported github repositories`
);
const repoProgress = new cliProgress.Bar(
{
format:
'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | {state}'
},
cliProgress.Presets.shades_classic
);
context.ui.bar = repoProgress;
repoProgress.start(repositories.length, 0);
// Do all reposiotory level tasks
for (const repository of repositories) {
var task_queue = [];
context.externalValuesMap = { repository_id: repository.id };
for (const repoTaskFunc of context.tasks.repo) {
task_queue.push(repoTaskFunc(repository, context, config));
}
await Promise.all(task_queue);
repoProgress.increment(1);
}
repoProgress.stop();
} else {
console.log(' ⚠️ No repositories downloaded');
}
}
// Do all post-process / export tasks
if (context.tasks.post.length > 0) {
console.log(
` ℹ️ Running ${context.tasks.post.length} post-processing tasks`
);
for (const task of context.tasks.post) {
await task(context, config);
}
}
if (context.tasks.metrics.length > 0) {
console.log(
` ℹ️ Running ${context.tasks.metrics.length} metrics-processing tasks`
);
for (const task of context.tasks.metrics) {
await task(context, config);
}
}
console.log(` ℹ️ Roadblock processing complete`);
}
init();
<file_sep>/tasks/repo/topics.js
module.exports = async function(repo, context, config) {
await context.client.Topic.destroy(repo.id);
var topics = await context.client.Topic.getAll(repo.owner, repo.name);
await context.client.Topic.bulkCreate(topics, repo);
return true;
};
<file_sep>/tasks/repo/commits.js
module.exports = async function(repo, context, config) {
context.ui.bar.increment(0, { state: "Running 'Commits on: " + repo.name });
await context.client.Commit.destroy(repo.id);
var commits = await context.client.Commit.getAll(repo.owner, repo.name);
await context.client.Commit.bulkCreate(commits, context.externalValuesMap);
return true;
};
<file_sep>/tasks/repo/blame.js
module.exports = async function(repo, context, config) {
context.ui.bar.increment(0, { state: "Running 'Blame on: " + repo.name });
await context.client.Blame.destroy(repo.id);
var blame = await context.client.Blame.getAll(repo.owner, repo.name, config);
await context.client.Blame.bulkCreate(blame, context.externalValuesMap);
return true;
};
<file_sep>/tasks/repo/contributions.js
module.exports = async function(repo, context, config) {
await context.client.Contribution.destroy(repo.id);
var contributions = await context.client.Contribution.getAll(
repo.owner,
repo.name
);
await context.client.Contribution.bulkCreate(
contributions,
context.externalValuesMap
);
return true;
};
<file_sep>/export/client.js
const Sequelize = require('sequelize');
const fs = require('fs');
function _getFileDate() {
// get the short version of todays date for naming files
var today = new Date();
return `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
}
function saveToFile(data, folder, filename) {
try {
fs.writeFileSync(
`${folder}${filename}.json`,
JSON.stringify(data, null, 2),
'utf8'
);
fs.writeFileSync(
`${folder}${filename}-${_getFileDate()}.json`,
JSON.stringify(data, null, 2),
'utf8'
);
} catch (ex) {
console.log(ex);
}
}
module.exports = class ExportClient {
constructor(database, config) {
this.database = database;
this.config = config;
}
async export() {
// create a repo file listing the 100 most active projects
var repos = await this.database.models.Repository.findAll({
limit: 100,
order: Sequelize.literal('(forks+stars+watchers) DESC')
});
repos = repos.map(x => {
return x.dataValues;
});
saveToFile(repos, this.config.storage, 'repositories');
// organisation stats
var orgs = await this.database.models.Organisation.findAll();
orgs = orgs.map(x => {
return x.dataValues;
});
saveToFile(orgs, this.config.storage, 'organisations');
// general statistics
var stats = {};
stats.stars = await this.database.models.Repository.sum('stars');
stats.projects = await this.database.models.Repository.count();
stats.languages = await this.database.models.Repository.count({
col: 'language',
distinct: true
});
stats.forks = await this.database.models.Repository.sum('forks');
stats.members = await this.database.models.Member.count();
stats.contributors = await this.database.models.Contribution.count({
col: 'user_id',
distinct: true
});
saveToFile(stats, this.config.storage, 'statistics');
}
};
<file_sep>/tasks/repo/issues.js
module.exports = async function(repo, context, config) {
await context.client.Issue.destroy(repo.id);
var issues = await context.client.Issue.getAll(repo.owner, repo.name);
await context.client.Issue.bulkCreate(issues, context.externalValuesMap);
return true;
};
<file_sep>/tasks/pre/calendar.js
module.exports = async function(context) {
var months = await context.client.Calendar.getAll(2014);
await context.client.Calendar.destroy(0, { truncate: true });
await context.client.Calendar.bulkCreate(months);
console.log(` ⬇️ Calendar Database data stored`);
return true;
};
<file_sep>/tasks/repo/pullrequests.js
module.exports = async function(repo, context, config) {
await context.client.PullRequest.destroy(repo.id);
var prs = await context.client.PullRequest.getAll(repo.owner, repo.name);
await context.client.PullRequest.bulkCreate(prs);
return true;
};
<file_sep>/tasks/repo/collaborators.js
module.exports = async function(repo, context, config) {
context.ui.bar.increment(0, {
state: "Running 'Collaborators on: " + repo.name
});
await context.client.Collaborator.destroy(repo.id);
var collaborators = await context.client.Collaborator.getAll(
repo.owner,
repo.name
);
await context.client.Collaborator.bulkCreate(
collaborators,
context.externalValuesMap
);
return true;
};
<file_sep>/client/blame.js
const Base = require('./base.js');
const Sequelize = require('sequelize');
const simpleGit = require('simple-git')();
const fs = require('fs');
const path = require('path');
const gitPromise = require('simple-git/promise');
const gitGuilt = require('git-guilt');
var mkdir = function(dir) {
// making directory without exception if exists
try {
fs.mkdirSync(dir, 0755);
} catch (e) {
if (e.code != 'EEXIST') {
throw e;
}
}
};
var rmdir = function(dir_path) {
if (fs.existsSync(dir_path)) {
fs.readdirSync(dir_path).forEach(function(entry) {
var entry_path = path.join(dir_path, entry);
if (fs.lstatSync(entry_path).isDirectory()) {
rmdir(entry_path);
} else {
fs.unlinkSync(entry_path);
}
});
fs.rmdirSync(dir_path);
}
};
module.exports = class Blame extends Base {
constructor(githubClient, databaseClient) {
super(githubClient, databaseClient);
this.schema = {
total: Sequelize.BIGINT,
login: Sequelize.STRING(200)
};
this.map = {
total: 'total',
login: 'login'
};
this.name = 'Blame';
}
sync(force) {
this.model.belongsTo(this.dbClient.models.Repository);
super.sync(force);
}
async getAll(orgName, repoName, config) {
var folder = __dirname + '/tmp-repo-data';
rmdir(folder);
mkdir(folder);
const remote = `${config.github.url.git}/${orgName}/${repoName}.git`;
const git = gitPromise(folder);
try {
await git.silent(true).clone(remote);
} catch (ex) {
console.log(orgName + '/' + repoName + ': ' + ex);
}
try {
var blame = await gitGuilt({ repoPath: folder + '/' + repoName });
rmdir(folder + '/' + repoName);
var sum = Object.values(blame).reduce((a, b) => a + b, 0);
return Object.keys(blame).map(x => {
var prct = blame[x];
if (prct > 0) {
prct = (prct / sum) * 100;
}
return { login: x, total: prct };
});
} catch (ex) {
console.log(orgName + '/' + repoName + ': ' + ex);
}
return [];
}
};
|
e765203482061b39cf83f27bf999f3f458201013
|
[
"JavaScript"
] | 15 |
JavaScript
|
skoenig/roadblock
|
9c6eadd69764eb2233d6138a9f25885b17919779
|
82e4a4389157b0172beb526ae204f82d242c918b
|
refs/heads/master
|
<file_sep>def solution(K, words):
answer=1
l=0
for i in range(len(words)):
l+=len(words[i])+1
if l>K+1:
answer+=1
l=len(words[i])+1
return answer
#https://programmers.co.kr/learn/courses/11133/lessons/71167
# 한 줄에 K자를 적을 수 있는 메모장에 영어 단어들을 적으려 합니다.
# 영어 단어는 정해진 순서로 적어야 하며, 단어와 단어 사이는 공백 하나로 구분합니다.
# 단, 한 줄의 끝에 단어 하나를 완전히 적지 못한다면, 그 줄의 나머지 부분을 모두 공백으로 채우고 다음 줄부터 다시 단어를 적습니다.
#
# 예를 들어 한 줄에 10자를 적을 수 있고, 주어진 단어가 순서대로 ["nice", "happy", "hello", "world", "hi"] 인 경우 각 줄에 다음과 같이 적을 수 있습니다.
# ('_'는 공백을 나타냅니다.)
#
# 첫째 줄 : "nice_happy"
# 둘째 줄 : "hello_____"
# 셋째 줄 : "world_hi"
# 이때, 둘째 줄에 "hello"를 적으면 단어를 적을 수 있는 남은 칸은 5칸이며, "world"를 이어서 적으려면 공백 하나를 포함하여 총 6칸이 필요합니다.
# 따라서 단어가 잘리게 되므로 남은 칸을 모두 공백으로 채운 후, 다음 줄에 "world"부터 다시 단어를 적어 나갑니다.
#
# 한 줄에 적을 수 있는 글자 수 K와 적을 단어가 순서대로 담긴 리스트 words가 매개변수로 주어질 때, 단어를 모두 적으면 몇 줄이 되는지 return 하도록 solution 함수를 완성해주세요.<file_sep>#codeUp 1
print("Hello")<file_sep>n,s=map(int,input().split())
arr=list(map(int,input().split()))
ans=[]
answer=0
def go(ans,start):
global answer
if ans and sum(ans) == s:
answer+=1
for i in range(start,n):
ans.append(arr[i])
go(ans,i+1)
ans.pop()
go(ans,0)
print(answer)
# o x 로 푸는 문제
def go(index,sum):
global ans
if index == n:
if sum == s:
ans += 1
return
go(index+1,sum+arr[index])
go(index+1,sum)
go(0,0)
if s == 0: #모두 선택하지 않는 경우 처리 ( 모든 것이 포함되지 않았을 때 ) -> 아무것도 선택하지 않아서 sum이 0이 될 수도 있기 때문에
ans -= 1
print(ans)
<file_sep>n,m=map(int,input().split())
c=[False]*(n+1) #방문했는지
a=[0]*m #숫자
def go(index,start,n,m):
if index == m:
print(' '.join(map(str,a)))
return
for i in range(start,n+1):
if c[i]:
continue
c[i]=True
a[index]=i
go(index+1,i+1,n,m)
c[i]=False
go(0,1,n,m)
<file_sep>a=int(input())
num_list=list(map(int,input().split()))
for i in range(0,a,1):
print(num_list[i])<file_sep>a,r,n = map(int,input().split())
for i in range(n-1):
a*=r
print(a)
<file_sep>from collections import deque
def solution(queue1, queue2):
answer = 0
sum1, sum2 = sum(queue1), sum(queue2)
q1, q2 = deque(queue1), deque(queue2)
for _ in range(2 * (len(queue1 + queue2))):
if sum1 < sum2:
if q2:
sum1 += q2[0]
sum2 -= q2[0]
q1.append(q2.popleft())
elif sum1 > sum2:
if q1:
sum1 -= q1[0]
sum2 += q1[0]
q2.append(q1.popleft())
else:
return answer
answer += 1
return -1<file_sep>def solution(numbers):
numbers = list(map(str,numbers))
numbers = sorted(numbers,key=lambda x:x*3,reverse=True)
return str(int(''.join(numbers)))<file_sep>a,b= map(int,input().split(" "))
print(a<<b) # 1(a)를 2의b승배 곱한다<file_sep>a = input()
unsigned32(a)
<file_sep>from itertools import permutations
def solution(k, dungeons):
l = len(dungeons)
maxx = 0
for turns in list(permutations([i for i in range(l)], l)):
temp = 0
K = k
for turn in turns:
least, spend = dungeons[turn]
if K < least:
continue
K -= spend
temp += 1
maxx = max(temp, maxx)
return maxx<file_sep>a=int(input())
def is_plus (num):
if(num>0):
print("plus")
else:
print("minus")
def is_even(num):
if num%2==0:
print("even")
else:
print("odd")
is_plus(a)
is_even(a)<file_sep>n,m,r=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(n)]
groups=[]
groupn=min(n,m)//2
for k in range(groupn):
group=[]
for j in range(k,m-k):
group.append(a[k][j])
for i in range(k+1,n-k-1):
group.append(a[i][m-k-1])
for j in range(m-k-1,k,-1):
group.append(a[n-k-1][j])
for i in range(n-k-1,k,-1):
group.append(a[i][k])
groups.append(group)
#테두리별로 1차원배열로 만드는 것
for k in range(groupn):
group=groups[k]
l=len(group)
index=r%l #배열 길이와 동일했던 인덱스는 0으로 바꿔주기 위해서
for j in range(k, m - k):
a[k][j]=group[index]
index = (index + 1) % l
for i in range(k+1, n - k-1):
a[i][m - k - 1]=group[index]
index = (index + 1) % l
for j in range(m - k - 1, k, -1):
a[n - k - 1][j]=group[index]
index = (index + 1) % l
for i in range(n - k - 1, k, -1):
a[i][k] = group[index]
index = (index + 1) % l
for row in range(n):
print(*a[row])
<file_sep>n,m = map(int,input().split())
graph=[]
result=0
for i in range(n):
graph.append(list(map(int,input())))
def dfs(x,y):
if x<0 or x>=n or y<0 or y>=m:
return False
if graph[x][y] == 0:
graph[x][y]=1
dfs(x-1,y)
dfs(x+1,y)
dfs(x,y-1)
dfs(x,y+1)
return True
return False
for i in range(n):
for j in range(m):
if dfs(i,j) == True:
result += 1
print(result)<file_sep>def solution(s, n):
answer = list(s)
for i in range(len(s)):
#몇 번째인지를 구하여 덧셈을 해줌 (소문자->대문자/대문자=>소문자 넘어가는 것 대비))
if answer[i].isupper():
answer[i]=chr((ord(answer[i])-ord('A')+n)%26+ord('A'))
elif answer[i].islower():
answer[i]=chr((ord(answer[i])-ord('a')+n)%26+ord('a'))
return ''.join(answer) <file_sep>from collections import deque
jq=deque()
mq=deque()
r,c = map(int,input().split())
jdist=[[-1 for _ in range(c)] for _ in range(r)]
mdist=[[-1 for _ in range(c)] for _ in range(r)]
m=[]
exist=False
for i in range(r):
inp=list(input())
if 'J' in inp:
jq.append((i,inp.index('J')))
jdist[i][inp.index('J')]=0
for index,j in enumerate(inp):
if j == 'F':
mq.append((i,index))
mdist[i][index]=0
exist=True
m.append(inp)
dx=[1,-1,0,0]
dy=[0,0,1,-1]
#1초당 네 지점에 불이 붙는다.
while mq:
x,y=mq.popleft()
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if 0 <= nx < r and 0 <= ny < c:
if m[nx][ny] == '.' and mdist[nx][ny] == -1:
mdist[nx][ny]=mdist[x][y]+1
mq.append((nx,ny))
while jq:
x,y=jq.popleft()
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
#외곽으로 탈출하는 것이기 때문에, 범위를 벗어나면 탈출을 한 것임.
if nx<0 or nx>=r or ny<0 or ny>=c:
print(jdist[x][y]+1)
exit(0)
if jdist[nx][ny] >= 0 or m[nx][ny] == '#':
continue
if mdist[nx][ny] != -1 and mdist[nx][ny] <= jdist[x][y]+1:
continue
jdist[nx][ny]=jdist[x][y]+1
jq.append((nx,ny))
print('IMPOSSIBLE')
#지훈이를 먼저 움직이는 게 아니라 불을 먼저 움직여야 하는 이유는
#같은 시간동안 불은 1초간 네 방향으로 퍼져 나가는데, 지훈이가 갈 길과 동일할 수 있기 때문<file_sep>def solution(numbers, hand):
answer = ''
answer=[]
x1=3
y1=0
x2=3
y2=2
keys=[1,2,3,4,5,6,7,8,9,'*',0,'#']
where=[]
#키패드 위치 삽입
for i in range(4):
for j in range(3):
where.append([i,j])
for num in numbers:
for k in range(len(keys)):
if keys[k] == num:
if num in [1,4,7] :
x1,y1=where[k]
answer.append('L')
elif num in [3,6,9]:
x2,y2=where[k]
answer.append('R')
else:
#왼쪽과 가까울 때
if abs(x1-where[k][0]) + abs(y1-where[k][1]) < abs(x2-where[k][0])+abs(y2-where[k][1]):
x1,y1=where[k]
answer.append('L')
#오른쪽과 가까울 때
elif abs(x1-where[k][0]) + abs(y1-where[k][1]) > abs(x2-where[k][0])+abs(y2-where[k][1]):
x2,y2=where[k]
answer.append('R')
else: # 거리가 같을 때
if(hand == 'left'):
x1,y1=where[k]
answer.append('L')
else:
x2,y2=where[k]
answer.append('R')
return ''.join(answer)
<file_sep>from collections import defaultdict
def solution(record):
answer = []
names=defaultdict(str)
for re in record:
if re.split()[0] != "Leave":
command,id,name=re.split()
names[id]=name
else:
command,id=re.split()
for re in record:
res = re.split()
if res[0] == "Enter":
n=names[res[1]]
answer.append(n+"님이 들어왔습니다.")
elif res[0] == "Leave":
n=names[res[1]]
answer.append(n+"님이 나갔습니다.")
return answer<file_sep>n=int(input())
arr=[list(map(int,input().split())) for _ in range(n)]
v=[0]*n
left=right=0
min=999
a=[]
all = [i for i in range(n)]
def ability(li):
l=len(li)
s=0
for i in li:
for j in li:
if i!=j:
s+= arr[i][j]
return s
def choose(start):
global min
if len(a)==n//2:
team2 = list(set(all) - set(a))
left=ability(a)
right=ability(team2)
if abs(left-right)<min:
min=abs(left-right)
return
for i in range(start,n):
if not v[i]:
v[i]=True
a.append(i)
choose(i+1)
a.pop()
v[i]=False
choose(0)
print(min)
<file_sep># #시간 초과
# a,b,c=map(int,input().split())
# e=s=m=0
# year=0
# while True:
# if e==a and s==b and m==c:
# print(year)
# break
# e=(e+1)%15
# s=(s+1)%28
# m=(m+1)%19
# year+=1
#나머지가 0일 때 처리를 해주지 않아서 무한 루프
#나머지가 0일 때의 조건을 하나하나 달아주는 것보다
#범위를 벗어날 시 1로 초기화 해주는 방식이 더 나아보여서 수정
a,b,c=map(int,input().split())
e=s=m=0
year=0
while True:
if e==a and s==b and m==c:
print(year)
break
e+=1
s+=1
m+=1
if e==16:
e=1
if s==29:
s=1
if m==20:
m=1
year+=1<file_sep>h,w= map(int,input().split())
n=int(input())
list=[]
for i in range(h+1):
list.append([])
for j in range(w+1):
list[i].append(0)
for i in range(n):
l,d,x,y=map(int,input().split())
for j in range(l):
if d==0 :
list[x-1][y-1]=1
y += 1
else:
list[x-1][y-1]=1
x += 1
for i in range(h):
for j in range(w):
print(list[i][j], end =' ')
print()<file_sep>from collections import defaultdict,deque
def solution(n, edge):
answer = 0
graph=defaultdict(list)
dist=[-1]*(n+1)
dist[1]=1
q=deque()
q.append(1)
for (start,end) in edge:
graph[start].append(end)
graph[end].append(start)
def bfs():
while q:
x=q.popleft()
for node in list(graph[x]):
if dist[node] == -1:
dist[node]=dist[x]+1
q.append(node)
bfs()
_max= max(dist)
answer=dist.count(_max)
return answer if answer>0 else 1<file_sep>def solution(n):
answer = 0
arr = [[0 for _ in range(n)] for _ in range(n)]
check_col = [False] * n
check_dig1 = [False] * (2 * n - 1)
check_dig2 = [False] * (2 * n - 1)
def possible(r, c):
if check_col[c]:
return False
if check_dig1[r + c]:
return False
if check_dig2[r - c + n - 1]:
return False
return True
def nqueen(r, cnt):
nonlocal answer
if r == n or cnt == n:
answer += 1
return
for c in range(n):
if arr[r][c] != 'Q' and possible(r, c):
check_col[c] = True
check_dig1[r + c] = True
check_dig2[r - c + n - 1] = True
arr[r][c] = 'Q'
cnt += 1
nqueen(r + 1, cnt)
check_col[c] = False
check_dig1[r + c] = False
check_dig2[r - c + n - 1] = False
arr[r][c] = ''
cnt -= 1
nqueen(0, 0)
return answer<file_sep>from collections import deque
def all(garden):
n = len(garden)
m = len(garden[0])
done = True
for i in range(n):
for j in range(m):
if garden[i][j] == 0:
done = False
return done
def solution(garden):
q = deque()
ans = []
n = len(garden)
m = len(garden[0])
dx = [1, -1, 0, 0]
dy = [0, 0, -1, 1]
dist = [[-1] * m for _ in range(n)]
if all(garden):
return 0
for i in range(n):
for j in range(m):
if garden[i][j] == 1:
q.append((i, j))
dist[i][j] = 0
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if dist[nx][ny] == -1:
dist[nx][ny] = dist[x][y] + 1
q.append((nx, ny))
ans.append(dist[nx][ny])
return ans[-1]
# 정사각형 크기 격자 모양 정원에 칸마다 핀 꽃 또는 피지 않은 꽃을 심었습니다. 이 정원의 꽃이 모두 피는 데 며칠이 걸리는지 알고 싶습니다.
# 핀 꽃은 하루가 지나면 앞, 뒤, 양옆 네 방향에 있는 꽃을 피웁니다.
# 현재 정원의 상태를 담은 2차원 리스트 garden이 주어졌을 때, 모든 꽃이 피는데 며칠이 걸리는지 return 하도록 solution 함수를 작성해주세요.
<file_sep>from collections import deque
t=int(input())
dx=[1,1,-1,-1,2,2,-2,-2]
dy=[2,-2,2,-2,1,-1,1,-1]
for i in range(t):
n = int(input())
dist = [[0] * n for _ in range(n)]
check = [[0] * n for _ in range(n)]
q=deque()
a,b=map(int,input().split())
q.append((a,b))
check[a][b]=True
dist[a][b]=0
x1,y1=map(int,input().split())
if a==x1 and b==y1:
print(0)
continue
def dfs(q,check,dist):
while q:
x,y=q.popleft()
for i in range(8):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < n:
if not check[nx][ny]:
q.append((nx,ny))
check[nx][ny]=True
dist[nx][ny]=dist[x][y] +1
if nx == x1 and ny == y1:
print(dist[nx][ny])
return
dfs(q,check,dist)<file_sep>a= int(input())
print(format(a,'x'))<file_sep>n = input()
row = int(n[1])
col = ord(n[0])-ord('a')+1
sum = 0
#0~7 * 0~7
steps = [(2,1),(2,-1),(-2,1),(2,-1),(1,2),(1,-2),(-1,2),(-1,-2)]
for step in steps:
next_row = row + step[0]
next_col = col + step[1]
if next_row >= 1 and next_row <= 8 and next_col >=1 and next_col<=8 :
sum += 1
print(sum)<file_sep>def solution(s):
answer = ''
min=len(s)
for i in range(1,len(s)//2+1): #반복 단위
repeat=s[0:i] #반복단위 초기화
count=1
last=len(s)-(len(s)%i)
answer=''
for j in range(i,last+1,i):
if s[j:j+i] == repeat:
count+=1
continue
else:
if count != 1:
answer+=str(count)+repeat
else:
answer+=repeat
repeat=s[j:j+i]
count=1
answer+=s[last-1:-1]
if min>len(answer):
min=len(answer) #더 짧은 문자열 길이로 갱신
print(answer)
return min
print(solution('ababcdcdababcdcd'))
#zip함수를 이용한 비교
def compress(word):
count=1
cur_word=word[0]
ans=[]
for a,b in zip(word,word[1:]+['']):
#[''] 를 추가함으로써 짝이 안맞더라도 끝까지 탐방함.
if a == b:
count+=1
else:
ans.append([count,cur_word])
cur_word=b
count=1
print(cur_word)
print(ans)
return sum(len(word)+(len(str(count)) if count>1 else 0) for count,word in ans)
def solution(s):
min=len(s)
word=[]
for unit in range(1,(len(s)//2)+1): #반복 단위
for i in range(0,len(s),unit):
word.append(s[i:i+unit])
ans=compress(word)
if ans<min: min=ans
word.clear()
return min
print(solution("aabbaccc"))<file_sep>a = str(input())
a= list(map(int,a))
num = 1
for i in range(len(a)-1,-1,-1):
a[i]=a[i]*num
num *=10
for j in a:
print("["+j+"]")<file_sep>def solution(n):
m=n+1
while True:
if bin(m)[2:].count('1') == bin(n)[2:].count('1'):
return m
m+=1<file_sep>n=int(input())
bu=list(input().split())
_max=''
_min=''
visited=[0]*10
def check(i,j,k):
if k=='<':
return i<j
else:
return i>j
#틀렸는지 아닌지 확인
def do(index,s):
global _max,_min
if index==n+1:
if not len(_min):
_min=s
else:
_max=s
return
for i in range(10):
if not visited[i]:
if not index or check(s[-1],str(i),bu[index-1]):
visited[i]=True
do(index+1,s+str(i))
visited[i]=False
do(0,'')
print(_max)
print(_min)<file_sep>a,b,c=map(int,input().split())
if a%2==0 : print(a)
if b%2==0 : print(a)
if c%2==0 : print(a)
<file_sep>from collections import defaultdict
import math
def solution(fees, records):
answer = []
inout = defaultdict(list)
for record in records:
time,car,status=record.split()
h,m=map(int,time.split(":"))
if status == "IN":
inout[car].append(time)
else:
last=inout[car].pop()
intime=60*h+m
h,m=map(int,last.split(":"))
time=60*h+m
inout[car].append(abs(intime-time))
inkeys=sorted(inout)
for car in inkeys:
alltime=0
time=inout[car]
for t in time:
if str(type(t))=="<class 'str'>":
h,m=map(int,t.split(":"))
alltime+=(23*60+59)-(60*h+m)
else:
alltime+=t
if alltime <= fees[0]:
answer.append(fees[1])
else:
overtime = math.ceil((alltime - fees[0])/fees[2])
answer.append(fees[1]+(overtime*fees[-1]))
return answer<file_sep>arr=[int(input()) for _ in range(9)]
arr.sort()
over=sum(arr)-100
for i,a in enumerate(arr):
if over-a in arr:
arr.pop(i)
arr.pop(arr.index(over-a))
break
for a in arr:
print(a)
<file_sep>def solution(n, k, cmd):
li1 = [i for i in range(n)]
li2 = ['O' for i in range(n)]
change=[]
for do in cmd:
if do[0] == 'D':
k+=int(do[2]) #포인터 변화량 저장
elif do[0] == 'U':
k-=int(do[2])
elif do == 'C':
z=li1.pop(k)
li2[z]='X'
change.append(z)
print(li1,li2)
print(change)
if k==(len(li1)-1):
k-=1
else:
a=change.pop()
li1.append(a)
li1.sort()
li2[a]='O'
print(change)
return ''.join(li2)
print(solution(8,2,["D 2","C","U 3","C","D 4","C","U 2","Z","Z"]))<file_sep>from collections import deque
n=int(input())
r1,c1,r2,c2=map(int,input().split())
dx=[-2,-2,2,2,0,0]
dy=[-1,1,-1,1,-2,2]
dist=[[-1 for _ in range(n)] for _ in range(n)]
q=deque()
q.append((r1,c1))
dist[r1][c1]=0
while q:
x,y=q.popleft()
for i in range(6):
nx=x+dx[i]
ny=y+dy[i]
if 0<=nx<n and 0<=ny<n and dist[nx][ny] == -1:
dist[nx][ny]=dist[x][y]+1
q.append((nx,ny))
print(dist[r2][c2])
<file_sep>a=int(input())
for i in range(a,0,-1):
print(a)
a-=1<file_sep>#내 풀이 (bfs도 아님 ㅋㅋ)
from collections import deque
import sys
n,k= map(int,sys.stdin.readline().split())
graph=[]
where=deque()
check =[[False]*n for _ in range(n)]
for i in range(n):
graph.append(list(map(int,sys.stdin.readline().split())))
s,x,y=map(int,sys.stdin.readline().split())
dx=[-1,0,1,0]
dy=[0,1,0,-1]
def bfs(virus,x,y):
check[x][y] = True
for i in range(4):
nx= x+dx[i]
ny= y+dy[i]
if nx>=0 and ny>=0 and nx<n and ny<n:
if graph[nx][ny] == 0 and check[nx][ny] == False:
graph[nx][ny] = virus
check[nx][ny] = True
if nx==x-1 and ny==y-1:
print(graph[x-1][y-1])
return
def find(virus):
for i in range(n):
for j in range(n):
if graph[i][j] == virus and check[i][j] == False:
where.append((i,j))
return
for sec in range(s):
for virus in range(1,k+1):
find(virus)
while where:
fx,fy=where.popleft()
bfs(virus,fx,fy)
print(graph[x-1][y-1])<file_sep>a,b,c=map(int,input().split())
def is_even(num):
if num%2==0:
print("even")
else:
print("odd")
is_even(a)
is_even(b)
is_even(c)<file_sep>from collections import deque
arr=[list(input()) for _ in range(5)]
pri=[]
ans=0
#인덱스들의 집합을 활용해서 인접한지 알아보기 위함.
#인덱스 리스트의 첫 번쨰 요소를 q에 담아주고 탐색 시작
#인덱스들을 모두 visited True로 만든 뒤 범위 내에 True이면 탐색
#False로 바꾸고 탐색 완료한 인덱스를 큐에 넣어줌
#depth 값이 곧 인덱스 리스트에 속한 원소이므로 depth == 7이 곧 인덱스 리스트의 원소들이 모두 인접하다는 뜻.
def check():
visited = [[False for _ in range(5)] for _ in range(5)]
for x,y in pri:
visited[x][y]=True
q = deque()
q.append((pri[0][0],pri[0][1]))
dir = [(-1, 0), (0, 1), (1, 0), (0, -1)]
depth = 0
visited[pri[0][0]][pri[0][1]] = False
while q:
x,y = q.popleft()
depth += 1
for dx, dy in dir:
nx,ny = dx + x,dy + y
if 0 <= nx < 5 and 0 <= ny < 5 and visited[nx][ny]:
visited[nx][ny] = False
q.append((nx,ny))
if depth == 7:
return True
else:
return False
def dfs(cnt,index,scnt,ycnt):
global ans
if cnt == 7 and scnt >= 4:
if check():
ans +=1
return
if cnt>7 or ycnt>=4 or index >= 25:
return
x=index//5
y=index%5
pri.append((x,y))
if arr[x][y] == 'S':
dfs(cnt + 1,index + 1,scnt + 1,ycnt)
else:
dfs(cnt + 1, index + 1, scnt, ycnt + 1)
pri.pop()
dfs(cnt, index + 1, scnt, ycnt)
dfs(0,0,0,0)
print(ans)<file_sep>a=int(input())
sum=0
for i in range(1,a+1):
if(i%2==0):
sum+=i
print(sum)<file_sep>def solution(n, lost, reserve):
a= set(lost) & set(reserve) #제한사항 5번 -> 여벌을 가지고 있었으나 도난 당한 학생
lost=list(set(lost)-a)
reserve = list(set(reserve)-a) #여벌이 없는 것이므로 reserve 배열에서 빼줌.
for i in reserve:
if i-1 in lost:
lost.remove(i-1)
elif i+1 in lost:
lost.remove(i+1)
return n-len(lost)<file_sep>import math
n,m=map(int,input().split())
gcd=math.gcd(n,m)
print(gcd)
print(n*m//gcd)
#lcm모듈을 사용하려 하였으나 파이썬 3.9에서 지원이 안됨<file_sep>SELECT ORDER_ID,PRODUCT_ID,DATE_FORMAT(OUT_DATE,'%Y-%m-%d') as 'OUT_DATE',
CASE
WHEN OUT_DATE IS NULL THEN '출고미정'
WHEN DATEDIFF(OUT_DATE,'2022-05-01') <= 0 THEN '출고완료'
ELSE '출고대기'
END AS '출고여부'
FROM FOOD_ORDER
ORDER BY ORDER_ID<file_sep>import sys
sys.setrecursionlimit(100000)
test=int(input())
def dfs(x,y):
if x<0 or x>=n or y<0 or y>=m:
return False
if graph[x][y] == 1:
graph[x][y]=0
dfs(x+1,y)
dfs(x-1,y)
dfs(x,y+1)
dfs(x,y-1)
return True
return False
for t in range(test):
m,n,k=map(int,input().split())
graph=[[0]*m for _ in range(n)]
result=0
for k in range(k):
i,j= map(int,input().split())
graph[j][i] = 1
for i in range(n):
for j in range(m):
if dfs(i,j) == True:
result += 1
print(result)
<file_sep>#include <iostream>
#include <string>
using namespace std;
int self(int n) {
string str = to_string(n);
int sum = n;
for (int i = 0; i < str.length(); i++)
sum += str[i]-48;
return sum;
}
int main() {
bool not_self_number[10001] = { false };
for (int i=1;i<10001;i++){
int res = self(i);
if (res < 10000)
not_self_number[res] = true;
}
for (int i = 1; i < 10000; i++) {
if (not_self_number[i] == false)
cout << i << endl;
}
}<file_sep>n=int(input())
g=[list(input()) for _ in range(n)]
max=0
#행
def row():
global max
for i in range(n):
again = 1
for j in range(1,n):
if g[j][i] == g[j-1][i]:
again+=1
else:
if max<again:
max=again
again=1
if max < again:
max = again
#한 줄이 내리 같을 때
return max
#열
def col():
global max
for i in range(n):
again = 1
for j in range(1,n):
if g[i][j] == g[i][j-1]:
again+=1
else:
if max<again:
max=again
again=1
if max < again:
max = again
return max
for i in range(n):
for j in range(1,n):
g[i][j],g[i][j-1] = g[i][j-1],g[i][j]
row()
col()
g[i][j], g[i][j - 1] = g[i][j - 1], g[i][j]
for i in range(n):
for j in range(1,n):
g[j][i],g[j-1][i] = g[j-1][i],g[j][i]
row()
col()
g[j][i],g[j-1][i] = g[j-1][i],g[j][i]
print(max)<file_sep>n=int(input())
stdnts=list(map(int,input().split()))
b,c=map(int,input().split())
num=0
for i,s in enumerate(stdnts):
if s>=b:
stdnts[i]=s-b
num+=1
else:
num+=1
stdnts[i]=-1
for s in stdnts:
if s != -1:
if s%c==0:
num+=(s//c)
else:
num+=(s//c)+1
print(num)<file_sep>def find(word, indexs):
for i in range(len(word), 0, -1):
spit = word[:i] # 가장 긴 문자열
if spit in indexs.keys():
return i
def LZW(word, indexs, ans):
if not len(word):
return ans
lIdx = find(word, indexs) # c
w = word[:lIdx]
wsIdx = indexs[w]
ans.append(wsIdx)
if lIdx != len(word):
indexs[w+word[lIdx]] = len(indexs) + 1 # 4번 조건
LZW(word[lIdx:], indexs, ans)
return ans
def solution(msg):
answer = []
indexs = {chr(e+64):e for e in range(1,27)}
answer = LZW(msg, indexs, answer)
return answer
<file_sep>def solution(s):
answer = []
li = s.split(" ")
for l in li:
if l != '':
if l[0].isalpha():
answer.append(l[0].upper() + l[1:].lower() + ' ')
else:
answer.append(l[0] + l[1:].lower() + ' ')
else:
answer.append(" ")
if s[-1] != ' ':
return ''.join(answer).rstrip(' ')
else:
answer.pop()
return ''.join(answer)<file_sep>def solution(A,B):
answer = 0
A.sort()
B.sort(reverse=True)
for a,b in zip(A,B):
answer+=a*b
return answer
#파이써닉하게 줄인다면?
def solution(A,B):
return sum(a*b for a,b in zip(sorted(A),sorted(B,reverse=True)))<file_sep>n = int(input())
s = [0]*n
w = [0]*n
for i in range(n):
s[i], w[i] = map(int, input().split())
ans = 0
def egg(idx, eggs):
global ans
if idx == n:
cnt = 0
for i in range(n):
if eggs[i] <= 0:
cnt +=1
ans=max(ans,cnt)
return
if eggs[idx] > 0:
for i in range(n):
flag = False
if eggs[i] > 0 and i != idx:
flag = True
tmp = eggs[:]
tmp[i] -= w[idx]
tmp[idx] -= w[i]
egg(idx+1, tmp)
if not flag:
egg(idx+1, eggs)
else:
egg(idx+1, eggs)
egg(0, s)
print(ans)
# if arr[idx][0] == -1 :
# egg(next_idx, next_idx + 1)
# return
#
# if arr[next][0] != -1:
# for next in range(idx,n):
# first_egg=arr[idx][0] - arr[next][1]
# second_egg=arr[next][0]-arr[idx][1]
#
# if first_egg<0:
# arr[idx][0]=-1 #깨졌다.
# egg(idx, next + 1)
#
# if second_egg<0:
# arr[next_idx][0]=-1 #깨졌다.
# egg(idx, next + 1)
<file_sep>from collections import deque
import sys
n,m,k,x=map(int,sys.stdin.readline().split())
graph=[[] for _ in range(n+1)]
length=[-1] * (n+1)
length
for i in range(m):
a,b=map(int,sys.stdin.readline().split())
graph[a].append(b)
length=[-1] * (n+1)
length[x]=0
queue=deque([x])
while queue:
v= queue.popleft()
for i in graph[v]:
if length[i] == -1:
length[i] = length[v] + 1
queue.append(i)
check = False
for i in range(1,n+1):
if length[i] == k:
print(i)
check = True
if check == False:
print(-1)<file_sep>from math import gcd
n= int(input())
for _ in range(n):
M,N,X,Y=map(int,input().split())
x=y=0
count=0
hop=0
while True:
count=((M*hop)+X)
if count>= (M*N // gcd(M,N)):
print(-1)
break
if (count%N) == 0:
y=N
else:
y=(count%N)
if Y == y:
print(count)
break
hop+=1<file_sep># scores = [[100,90,98,88,65],[50,45,99,85,77],[47,88,95,80,67],[61,57,100,80,65],[24,90,94,75,65]]
# scores = [[50,90],[50,87]]
scores = [[70,49,90],[68,50,38],[73,31,100]]
n=len(scores)
def grade(score):
if score>=90:
return 'A'
elif 80<=score<90:
return 'B'
elif 70 <= score < 80:
return 'C'
elif 50<=score<70:
return 'D'
else:
return 'F'
#행이 자기가 평가한 점수
#열이 내가 평가 받은 점수
ans=''
for i in range(n):
temp=[]
for j in range(n):
#최고점 또는 최저점 확인
temp.append(scores[j][i])
min_score=min(temp)
max_score=max(temp)
min_num=temp.count(min_score)
max_num = temp.count(max_score)
if (min_num == 1 and temp[i] == min_score) or (max_num == 1 and temp[i] == max_score):
temp.pop(i)
ans+=grade(sum(temp)/len(temp))
print(ans)<file_sep>#스도쿠 + 도미노 오엠지
from itertools import combinations
cnt=0
numbers=list(combinations([1,2,3,4,5,6,7,8,9],2))
placed=[[(0,0),(0,1)],[(0,0),(1,0)]]
dx=[1,0]
dy=[0,1]
while True:
cnt += 1
n=int(input())
if not n:
exit(0)
puzzle=[[0 for _ in range(9)] for _ in range(9)]
for _ in range(n):
U,LU,V, LV = input().split()
puzzle[ord(LU[0])-ord('A')][int(LU[1])-1]=int(U)
puzzle[ord(LV[0]) - ord('A')][int(LV[1]) - 1] = int(V)
fixed=list(input().split())
for i,p in enumerate(fixed):
puzzle[ord(p[0])-ord('A')][int(p[1])-1]=i+1
check_row=[[False for _ in range(10)] for _ in range(9)] #행은 무슨 행인지/ 열은 1-9까지의 숫자
check_col=[[False for _ in range(10)] for _ in range(9)]
check_checker=[[False for _ in range(10)] for _ in range(9)]
domino=[[False for _ in range(10)] for _ in range(10)]
checker_pos=[(0,0),(0,3),(0,6),(3,0),(3,3),(3,6),(6,0),(6,3),(6,6)]
for i in range(9):
for r in range(9):
num=puzzle[i][r]
if num:
check_row[i][num]=True
for i in range(9):
for c in range(9):
num=puzzle[c][i]
if num:
check_col[i][num] = True #puzzle[c][i]란 해당 열의 숫자
for turn,pos in enumerate(checker_pos):
x,y=pos
for i in range(3):
for j in range(3):
num=puzzle[i+x][j+y]
if num:
check_checker[turn][num]=True
def check(num,row,col,checker):
if check_row[row][num]: #row 행에 해당 num이 있는지
return False
if check_checker[checker][num]: #해당 체커 번호에 그 숫자가 있는지
return False
if check_col[col][num]: #해당 열에 그 숫자가 있는지
return False
return True
visited=[False for _ in range(8)]
def sdoku(z):
if z == 81: #바둑판 끝까지 도달했을 때
print('Puzzle', cnt)
for i in range(9):
for j in range(9):
print(puzzle[i][j],end='')
print()
return True
x=z//9
y=z%9
if(puzzle[x][y]):
return sdoku(z+1) # 왜 리턴으로 함수를 실행하는지
#함수를 리턴하는 것이 아니라, 함수를 실행한 후에 반환 값을 리턴함.
#
else:
for k in range(2):
nx = x + dx[k]
ny = y + dy[k]
checkerX = (x // 3) * 3 + (y // 3)
checkerNX = (nx // 3) * 3 + (ny // 3)
if nx<0 or nx>8 or ny<0 or ny>8:
continue
for i in range(1,10):
for j in range(1,10):
if i==j:
continue
if puzzle[nx][ny] or domino[i][j]:
continue
if check(i,nx,ny,checkerNX) and check(j,x,y,checkerX):
check_row[nx][i]=check_col[ny][i]=check_checker[checkerNX][i]=True
domino[i][j]=domino[j][i]=True
check_row[x][j] = check_col[y][j] = check_checker[checkerX][j] = True
puzzle[nx][ny]=i
puzzle[x][y]=j
if sdoku(z+1):
return True
check_row[nx][i] = check_col[ny][i] = check_checker[checkerNX][i] = False
domino[i][j]=domino[j][i]= False
check_row[x][j] = check_col[y][j] = check_checker[checkerX][j] = False
puzzle[nx][ny] = 0
puzzle[x][y] = 0
sdoku(0)<file_sep>from collections import deque
n,m=map(int,input().split())
graph=[list(map(int,input())) for _ in range(m)]
dist=[[-1]*n for _ in range(m)]
dx=[1,-1,0,0]
dy=[0,0,1,-1]
def dfs():
q=deque()
q.append((0,0))
dist[0][0] = 0
while q:
x,y=q.popleft()
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if 0<=nx<m and 0<=ny<n:
if dist[nx][ny] == -1:
if graph[nx][ny] == 1:
q.append((nx, ny))
dist[nx][ny] = dist[x][y] + 1
else:
q.appendleft((nx, ny))
dist[nx][ny] = dist[x][y]
dfs()
print(dist[m-1][n-1])<file_sep>n = int(input())
graph=[]
h_list=[]
for i in range(n):
graph.append(list(map(int,input())))
num=0
result=0
def dfs(x,y):
global num
if x<0 or x>=n or y<0 or y>=n:
return 0
if graph[x][y] == 1:
graph[x][y]=0
num += 1
dfs(x+1,y)
dfs(x-1,y)
dfs(x,y+1)
dfs(x,y-1)
return 1
return 0
for i in range(n):
for j in range(n):
if dfs(i,j) == 1:
result += 1
h_list.append(num)
num=0
h_list.sort()
print(result)
for i in h_list:
print(i)
<file_sep>a,d,n = map(int,input().split())
for i in range(n-1):
a+=d
print(a)<file_sep>from collections import defaultdict
def solution1(tickets):
graph=defaultdict(list)
for a,b in sorted(tickets):
graph[a].append(b)
route=[]
def dfs(a):
while graph[a]:
dfs(graph[a].pop(0))
route.append(a)
dfs('JFK')
return route[::-1]
def solution2(tickets):
graph = defaultdict(list)
for a,b in sorted(tickets,reverse=True):
graph[a].append(b)
route=[]
def dfs(a):
while graph[a]:
dfs(graph[a].pop())
route.append(a)
dfs('JFK')
return route[::-1]
solution1([["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]])<file_sep>n,m=map(int,input().split())
c=[False]*(n+1) #방문했는지
a=[0]*m #숫자
def go(index,start,n,m):
if index == m:
print(' '.join(map(str,a)))
return
for i in range(start,n+1):
#c[i]=True #사용 방법 검사
a[index]=i
go(index+1,i,n,m)
c[i]=False
go(0,1,n,m)<file_sep>#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
int score = 0;
int score_stk = 0;
string str = "";
cin >> n;
for (int i = 0; i < n; i++) {
cin >> str;
for (int j = 0; j < str.length(); j++) {
if (str[j] == 'O')
score_stk += 1;
if (str[j] == 'X')
score_stk = 0;
score += score_stk;
}
cout << score << endl;
score = 0;
score_stk = 0;
}
}<file_sep>#특이점 pypy만 통과됨..
from collections import deque
n,m=map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(n)]
temp=[[0]*m for _ in range(n)]
virus=[]
queue=[]
dx=[1,-1,0,0]
dy=[0,0,1,-1]
safe=0
for i in range(n):
for j in range(m):
if arr[i][j] == 2:
queue.append((i,j))
def cntsafe():
num=0
for i in range(n):
for j in range(m):
if temp[i][j] == 0:
num+=1
return num
def wall(cnt):
global safe
global queue
if cnt == 3:
for i in range(n):
for j in range(m):
temp[i][j]=arr[i][j]
v = [[0] * m for _ in range(n)]
q=deque(queue)
while q:
x, y = q.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0<=nx<n and 0<=ny<m:
if not v[nx][ny]:
if temp[nx][ny] == 0:
temp[nx][ny]=2
v[nx][ny] = True
q.append((nx,ny))
safe=max(safe,cntsafe())
return
for i in range(n):
for j in range(m):
if arr[i][j] == 0:
arr[i][j] = 1
cnt+=1
wall(cnt)
arr[i][j] = 0
cnt-=1
wall(0)
print(safe)
<file_sep>from collections import defaultdict
import heapq
n=int(input())
graph=defaultdict(list)
for _ in range(n-1):
start,end,weight=list(map(int,input().split()))
graph[start].append((end,weight))
graph[end].append((start, weight))
def check(root):
Q=[(0,root)]
dist=defaultdict(int)
while Q:
time, node = heapq.heappop(Q)
if node not in dist:
dist[node]=time
for v,w in graph[node]:
alt=time+w
heapq.heappush(Q,(alt,v))
return dist
dist=check(1)
n1=sorted(dist.items(),key=lambda x:-x[1])[0][0]
dist=check(n1)
n2=sorted(dist.items(),key=lambda x:-x[1])[0][0]
answer = sorted(dist.items(),key=lambda x:-x[1])[0][1]
print(answer)<file_sep>n,m = map(int,input().split())
minlist=[]
for i in range(n):
a=list(map(int,input().split()))
minlist.append(min(a))
print(max(minlist))
<file_sep>n=int(input())
target=list(map(int,input().split()))
arr=[i for i in range(1,n+1)]
ans=[]
prev_elements =[]
def dfs(elements):
if len(elements) == 0:
ans.append(prev_elements[:])
for e in elements:
next_elements=elements[:]
next_elements.remove(e)
prev_elements.append(e)
dfs(next_elements)
prev_elements.pop()
dfs(target)
print(ans)<file_sep>from itertools import permutations
def check(users, banned_id):
for i in range(len(banned_id)):
if len(users[i]) != len(banned_id[i]):
return False
for j in range(len(users[i])):
if banned_id[i][j] != "*" and banned_id[i][j] != users[i][j]:
return False
return True
def solution(user_id, banned_id):
answer = []
for com_set in permutations(user_id, len(banned_id)):
if check(com_set, banned_id):
com_set = set(com_set)
if com_set not in answer:
answer.append(com_set)
return len(answer)<file_sep>import sys
class Fish:
def __init__(self, size=0, speed=0, direction=0):
self.size = size
self.speed = speed
self.direction = direction
# up, down, right, left
dx = [-1,1,0,0]
dy = [0,0,1,-1]
n, m, mm = map(int,input().split())
fish = [[Fish() for j in range(m)] for i in range(n)]
nfish = [[Fish() for j in range(m)] for i in range(n)]
for _ in range(mm):
x,y,s,d,z = map(int,input().split())
x -= 1
y -= 1
d -= 1
if d<=1:
s%=(2*n-2)
else:
s%=(2*m-2)
fish[x][y] = Fish(z,s,d)
def get_next(x, y, speed, direction):
for k in range(speed):
if direction == 0: # up
if x == 0:
x = 1
direction = 1
else:
x -= 1
elif direction == 1: # down
if x == n-1:
x = n-2
direction = 0
else:
x += 1
elif direction == 2: # right
if y == m-1:
y = m-2
direction = 3
else:
y += 1
elif direction == 3: # left
if y == 0:
y = 1
direction = 2
else:
y -= 1
return (x,y,direction)
ans = 0
for j in range(m):
for i in range(n):
if fish[i][j].size > 0:
ans += fish[i][j].size
fish[i][j].size = 0
break
for l1 in range(n):
for l2 in range(m):
if fish[l1][l2].size == 0:
continue
f = fish[l1][l2]
x, y, direction = get_next(l1, l2, f.speed, f.direction)
if nfish[x][y].size == 0 or nfish[x][y].size < f.size:
nfish[x][y] = Fish(f.size, f.speed, direction)
for l1 in range(n):
for l2 in range(m):
fish[l1][l2] = Fish(nfish[l1][l2].size, nfish[l1][l2].speed, nfish[l1][l2].direction)
nfish[l1][l2].size = 0
print(ans)<file_sep>n,m= map(int,input().split())
graph = []
temp = [[0]*m for _ in range(n)]
safety=0
for i in range(n):
graph.append(list(map(int,input().split())))
dx=[-1,0,1,0]
dy=[0,1,0,-1]
def virus(x,y):
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if nx>=0 and ny>=0 and nx<n and ny<m:
if temp[nx][ny]==0:
temp[nx][ny] = 2
virus(nx,ny)
def safe():
num=0
for i in range(n):
for j in range(m):
if temp[i][j] == 0:
num += 1
return num
def dfs(count):
global safety
if count == 3:
for i in range(n):
for j in range(m):
temp[i][j]=graph[i][j]
for i in range(n):
for j in range(m):
if temp[i][j]== 2:
virus(i,j)
safety = max(safety,safe())
return
for i in range(n):
for j in range(m):
if graph[i][j] == 0:
graph[i][j] =1
count += 1
dfs(count)
graph[i][j]=0
count -= 1
dfs(0)
print(safety)
<file_sep>def solution(dirs):
answer = 0
visited = []
# LRUD
move = ['L', 'R', 'U', 'D']
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
x = y = 0
for dir in dirs:
for i, m in enumerate(move):
if dir == m:
nx = x + dx[i]
ny = y + dy[i]
if -5 <= nx <= 5 and -5 <= ny <= 5:
if ((x, y), (nx, ny)) not in visited:
visited.append(((x, y), (nx, ny)))
visited.append(((nx, ny), (x, y)))
answer += 1
x, y = nx, ny
return answer<file_sep>n,m = map(int,input().split())
arr = list(map(int,input().split()))
res=0
sum=0
for i in range(0,len(arr)):
for j in range(i,len(arr)):
if arr[i] != arr[j]:
sum += 1
print(sum)<file_sep># from itertools import product
# num=list(map(str,input()))
# m=int(input())
# if m:
# b_in=list(map(int,input().split()))
# else:
# b_in=[]
# button=[str(i) for i in range(10) if str(i) not in b_in] #어떻게 효율적으로 받을지
# real=int(''.join(num))
# min=99999
#
# if real==100:
# print(0)
# exit(-1)
#
# for i in product(button,repeat=len(num)):
# num_string="".join(str(j) for j in i)
# if abs(int(num_string)-real)<min:
# min = abs(int(num_string)-real)
#print(min(str(min+len(num)),abs(100-real)))
# 냅다 틀림
#이유 - 꼭 같은 자리 수가 최소 값이 아닐 수 있기 때문에.
N = int(input())
M = int(input())
if M != 0:
B = list(input().split())
else:
B = []
R = [str(i) for i in range(10) if str(i) not in B]
result = abs(N - 100)
for i in range(1000000):
tf = True
for s in str(i):
if s not in R:
tf = False
break
if tf:
result = min(result, abs(N - i)+len(str(i)))
print(result)
#단순하게 생각하면 되는데 굳이 굳이 중복 조합 씀 ㅠ<file_sep>r,g,b = map(int,input().split())
sum=r*g*b
print('%.2f' % (sum/8/1024/1024),'MB')<file_sep>import sys
sys.setrecursionlimit(10**6)
n = int(sys.stdin.readline())
for _ in range(n):
v, e = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(v+1)]
color = [False] * (v + 1)
check=True
def dfs(node,c):
color[node] = c
for i in graph[node]:
if color[i] == 0:
if not dfs(i,3-c):
return False
if color[i] == color[node]:
return False
return True
for _ in range(e):
v1, v2 = map(int, sys.stdin.readline().split())
graph[v1].append(v2)
graph[v2].append(v1)
for i in range(1,v+1):
if color[i] == 0:
if not dfs(i,1):
check = False
break
print("YES" if check else "NO")<file_sep>n=int(input())
arr=list(map(int,input().split()))
c=0
def prime(x):
if x<2:
return False
for i in range(2,x):
if x%i == 0:
return False
return True
for a in arr:
if prime(a):
c+=1
print(c)<file_sep>n,m,r=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(n)]
groups=[]
groupn=min(n,m)//2
#그룹을 만들고 1차원 배열
#1차원 배열 R번 회전
#다시 그룹을 만듬
for k in range(groupn):
group=[]
for j in range(k,m-k):
group.append(a[k][j])
for i in range(k+1,n-k-1):
group.append(a[i][m-k-1])
for j in range(k+1,m-k):
group.append(a[n-k-1][j])
for i in range(k,n-k-1):
group.append(a[i][m-k-1])
# # 남 동 북 서
# dx=[1,0,-1,0]
# dy=[0,1,0,-1]
#
# def dfs(x,y,d):
# for i in range(4):
# nx=x+dx[i]
# ny=y+dy[i]
# if d==3 and :
#
# if 0<=nx<n and 0<=ny<m and d!=3:
# rotated[nx][ny]=graph[x][y]
# print(nx, ny)
# dfs(nx,ny,d+1)
# # print(*rotated,sep='\n')
# # print()
#
# while do:
# for
# dfs(0,0,0)
# # for i in range(do):
<file_sep>a,b=map(int,input().split(" "))
res = a%b
print(res)
<file_sep>a,b=input().split("-")
print('%s%s' % (a,b))<file_sep>class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans=[]
stack=[]
def dfs(start):
if sum(stack) == target:
if stack not in ans:
ans.append(stack[:])
if sum(stack) > target:
return
for i in range(start,len(candidates)):
stack.append(candidates[i])
dfs(i)
stack.pop()
for i in range(len(candidates)):
dfs(i)
return ans<file_sep>def solution(people, limit):
count = len(people)
people.sort(reverse=True)
first,last=0,len(people)-1
while first<last:
if people[first]+people[last]<=limit:
count-=1
last-=1
first+=1
return count<file_sep>def solution(lottos, win_nums):
answer = []
win_num=len(set(lottos)&set(win_nums))
rank=[6,6,5,4,3,2,1]
answer.append(rank[win_num])
answer.append(rank[win_num+lottos.count(0)])
answer.sort()
return answer<file_sep>n=int(input())
arr=list(map(int,input().split()))
answer=0
def energy(a):
if len(a)==2:
return 0
answer=0
for i in range(1,len(a)-1):
en=a[i-1]*a[i+1]
b=a[:i]+a[i+1:] #배열을 새로 생성해서 넣어줌
en+=energy(b)
answer=max(answer,en)
return answer
print(energy(arr))<file_sep>def solution(n):
answer = 0
arr = [[0] * n for _ in range(n)]
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
x = y = direction = 0
for cnt in range(1, n * n + 1):
arr[x][y] = cnt
x += dx[direction]
y += dy[direction]
if x < 0 or y < 0 or x >= n or y >= n or arr[x][y]: #잘못 가버렸음 다시 빠꾸
x -= dx[direction]
y -= dy[direction]
direction = (direction + 1) % 4
x += dx[direction]
y += dy[direction]
for i in range(n):
answer += arr[i][i]
return answer
solution(3)<file_sep>def solution(brown, yellow):
s=brown+yellow
for i in range(s,2,-1):
if s%i == 0:
w = i
if (w-2)*(s//i-2) == yellow:
return [w,s//i]<file_sep>from collections import defaultdict
def solution(genres, plays):
answer = []
dic = defaultdict(list)
pla = defaultdict(int)
for i, (gen, play) in enumerate(zip(genres, plays)):
dic[gen].append([i, play])
pla[gen] += play
for key in dic:
dic[key].sort(key=lambda x: x[1], reverse=True)
for key, item in sorted(pla.items(), key=lambda x: x[1], reverse=True):
most = dic[key]
for i in range(2):
if i < len(most):
answer.append(most[i][0])
return answer<file_sep>def solution(n):
answer = ''
while n:
if n%3:
answer+=str(n%3)
n//=3
else:
answer+='4'
n=n//3 -1
return answer[::-1]
<file_sep>n= int(input())
list = [[0 for _ in range(20)] for _ in range(20)]
for i in range(0,n):
a,b=map(int,input().split())
list[a][b]=1
for i in range(1,20):
for j in range(1,20):
print(list[i][j], end =' ')
print()<file_sep>n,m=map(int,input().split())
arr = list(input().split())
arr.sort()
a=['']*n
mo=['a','e','i','o','u']
check=[False]*len(arr)
def cnt_mo(arr):
for a in arr:
if a in mo:
return True
return False
def cnt_ja(arr):
cnt=0
for a in arr:
if a not in mo:
cnt+=1
if cnt >= 2:
return True
return False
def go(start,index,n,m):
if index == n:
if cnt_mo(a) and cnt_ja(a):
print("".join(a))
return
else:
return
for i in range(start,len(arr)):
if check[i]:
continue
a[index]=arr[i]
check[i]=True
go(i,index+1,n,m)
check[i]=False
go(0,0,n,m)<file_sep>from collections import deque
n,m=map(int,input().split())
arr=[]
cctv_cnt=0
c_list=[]
ans=999999
for i in range(n):
a=list(map(int,input().split()))
arr.append(a)
for j in range(m):
if 1<=a[j]<=5:
cctv_cnt +=1
c_list.append([i,j,arr[i][j]])
dx=[-1,0,1,0]
dy=[0,1,0,-1]
q=deque()
moves=[[],[[0],[1],[2],[3]],[[1,3],[0,2]],[[0,1],[1,2],[2,3],[0,3]],[[0,1,3],[0,1,2],[1,2,3],[0,2,3]],[[0,1,2,3]]]
def bfs(x,y,direction,tmp):
for d in direction:
nx=x
ny=y
while True:
nx, ny = nx + dx[d], ny + dy[d]
if 0<=nx<n and 0<=ny<m and tmp[nx][ny]!=6:
if tmp[nx][ny] == 0:
tmp[nx][ny]='#'
else:
break
def copy(arr):
tmp=[[0]*m for _ in range(n)]
for i in range(n):
for j in range(m):
tmp[i][j]=arr[i][j]
return tmp
def dfs(arr,cnt):
global ans
tmp=copy(arr)
if cnt == cctv_cnt:
num=0
for i in range(n):
num+=tmp[i].count(0)
ans=min(ans,num)
return
x,y,direction=c_list[cnt]
for m in moves[direction]:
bfs(x,y,m,tmp)
dfs(tmp,cnt+1)
tmp=copy(arr)
dfs(arr,0)
print(ans)
<file_sep>def ddang(m, n, board):
al = 0
for j in range(m):
now = []
cnt = 0
for i in range(n - 1, -1, -1):
if board[i][j] != 0:
now.append(board[i][j])
else:
cnt += 1
now.extend([0] * (cnt))
for k in range(n):
board[n - k - 1][j] = now[k]
al += cnt
return board, al
def solution(n, m, board):
answer = 0
arr = []
for i in range(n):
arr.append(list(board[i]))
# 세 방향 확인
dx = [1, 1, 0]
dy = [1, 0, 1]
emp = []
def find(x, y):
if arr[x][y] == 0:
return []
chg = [(x, y)]
for i in range(3):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if arr[nx][ny] != 0 and arr[x][y] == arr[nx][ny]:
chg.append((nx, ny))
else:
chg = []
break
else:
chg = []
return chg if len(chg) == 4 else []
while True:
for i in range(n):
for j in range(m):
ee = find(i, j)
if ee:
emp.extend(ee)
for x, y in emp:
arr[x][y] = 0
arr, ans = ddang(m, n, arr)
emp = []
if ans != answer:
answer = ans
else:
return answer<file_sep>def solution(s):
if len(s)%2 != 0:
return 0
q=[s[0]]
for i in range(1,len(s)):
if q and q[-1] == s[i]:
q.pop()
else:
q.append(s[i])
return int(not q)<file_sep>i=int(input())
if(i==12 and i==1 and i==2):
print("winter")
elif i<=5 and i>=3:
print("spring")
elif i<=8 and i>=6:
print("summer")
elif i<=11 and i>=9:
print("fall")<file_sep>from collections import defaultdict
from itertools import combinations
from bisect import bisect_left
def solution(information, query):
answer = []
score = []
dict = defaultdict(list)
for info in information:
info = info.split()
condition = info[:-1]
score = int(info[-1])
for i in range(5):
case = list(combinations([0, 1, 2, 3], i))
for c in case:
tmp = condition[:]
for idx in c:
tmp[idx] = '-'
key = ''.join(tmp)
dict[key].append(score)
for value in dict.values():
value.sort()
for quer in query:
quer = ''.join(quer.split("and")).split()
target_key = ''.join(quer[:-1])
target_score = int(quer[-1])
cnt = 0
if target_key in dict:
target_list = dict[target_key]
idx = bisect_left(target_list, target_score)
cnt = len(target_list) - idx
answer.append(cnt)
return answer
#효율성 꽝 풀이
# def solution(info, query):
# answer = []
# for q in query:
# qu=''.join(q.split('and')).split()
# cnt=0
# for i in info:
# apply=i.split()
# chk=0
# for ap,q in zip(apply,qu):
# if q == '-':
# chk+=1
# continue
# if ap.isalpha() and ap == q:
# chk+=1
# if ap.isdigit() and int(ap)>=int(q):
# chk+=1
# if chk==5:
# cnt+=1
# answer.append(cnt)
# return answer<file_sep>n=int(input())
arr=[[False]*n for _ in range(n)]
check_col = [False] * n
check_dig = [False] * (2*n-1) #대각선 별 번호를 매김
check_dig2 = [False] * (2*n-1)
cnt=0
def check(a,row,col):
if check_col[col]: #같은 열에 있는지
return False
if check_dig[row+col]: #같은 백슬래시 대각선에 있는지
return False
if check_dig2[row-col+n-1]: #같은 슬래시 대각선에 있는지
return False
return True
def queen(row):
if row == n:#한 줄에 하나의 퀸을 배치할 수 있으므로 다 배치했으면 다 놓은거임
return 1
ans=0
for col in range(n):
if check(arr, row, col):
#queen 배치
check_col[col]=True
check_dig[row+col] = True
check_dig2[row-col+n-1]=True
arr[row][col]=True
ans+=queen(row+1)
arr[row][col] = False
check_col[col]=False
check_dig[row+col] = False
check_dig2[row-col+n-1]= False
return ans
print(queen(0))
#시간초과 풀이
# def check(a,x,y):
# for i in range(n):
# if i == x:
# continue
# if a[i][y]:
# return False
#
# dx=[-1,-1,1,1]
# dy=[1,-1,1,-1]
# b=1
# while b<n:
# for i in range(4):
# nx=x+dx[i]*b
# ny=y+dy[i]*b
#
# if 0<=nx<n and 0<=ny<n:
# if a[nx][ny]:
# return False
# b+=1
# return True
#
# def queen(row):
# if row == n:
# global cnt
# cnt+=1
# return
#
# for col in range(n):
# arr[row][col]=True
# if check(arr,row,col):
# queen(row+1)
# arr[row][col] = False
#
# queen(0)
# print(cnt)<file_sep>def solution(skill, skill_trees):
answer=len(skill_trees)
for skill_tree in skill_trees:
str=''
for tree in skill_tree:
if tree in skill:
str+=tree
for i in range(len(skill)):
if i <= len(str)-1:
if skill[i] != str[i]:
answer-=1
break
return answer
#남의 풀이
def solution(skill, skill_trees):
answer = 0
for skills in skill_trees:
skill_list = list(skill)
for s in skills:
if s in skill:
if s != skill_list.pop(0):
break
else:
answer += 1
return answer<file_sep>a,b=map(int,input().split(" "))
print(a+b)
print(a-b)
print(a*b)
print("%d" % (a/b))
print(a%b)
print("%.2f" % (float(a)/b))<file_sep>from collections import deque
def solution(begin, target, words):
queue = deque()
queue.append([begin, 0])
visited = [0 for _ in range(len(words))]
ans = 999
if target not in words:
return 0
while queue:
word, depth = queue.popleft()
if word == target:
ans = min(ans, depth)
break
for i in range(len(words)):
cnt = 0
if not visited[i]:
for b, w in zip(word, words[i]):
if b != w:
cnt += 1
if cnt == 1:
queue.append([words[i], depth + 1])
visited[i] = 1
return ans
<file_sep>from collections import deque
def solution(bridge_length, weight, truck_weights):
bridge=[0]*bridge_length
time=0
weight_now=0
while bridge:
time += 1
bridge.pop(0) #1초마다 그냥 나가면 됨....
if truck_weights:
if truck_weights[0]+sum(bridge) <= weight:
t=truck_weights.pop(0)
bridge.append(t)
weight_now+=t
else:
bridge.append(0) #초
return time<file_sep>def solution(food_times, k):
answer = 0
i=0
check = True
sort_food=[]
sort_food=sorted(food_times)
if k>=sort_food[0]:
for i in range(len(food_times)):
if i>=sort_food[i]:
food_times[i] -= sort_food[0]
else:
check = False
if k>= len(food_times)*sort_food[0]:
k -= len(food_times)*sort_food[0]
else:
if check == True:
k -= sort_food[0]
count = k+1
arr_sum = sum(food_times)
print(food_times, k)
while count != 0:
answer=i%len(food_times)
if arr_sum != 0:
if food_times[answer] != 0:
food_times[answer] = food_times[answer]-1
arr_sum -= 1
count -= 1
else:
answer += 1
else:
return -1
i += 1
answer += 1
return answer
print(solution([1,1,1,1],2))<file_sep>n=int(input())
for i in range(1,n+1):
print(' '*(n-i)+'*'*i)
#+로 연결 할 시 공백 없음 ,로 연결 할 시 공백 발생<file_sep>from collections import deque
queue = deque()
answer = []
n,m = map(int,input().split())
for i in range(1, n + 1):
queue.append(i)
while queue:
for i in range(m - 1):
queue.append(queue.popleft())
answer.append(queue.popleft())
print("<",end='')
for i,ans in enumerate(answer):
if i == len(answer)-1:
print(ans,end='')
else:
print(ans,end=', ')
print(">",end='')<file_sep>def solution(participant, completion):
participant.sort()
completion.sort()
print(participant)
print(completion)
return participant[-1]<file_sep>def solution(s):
alpha=['zero','one','two','three','four','five','six','seven','eight','nine']
for i,alp in enumerate(alpha):
s=s.replace(alp,str(i))
return int(s)<file_sep>a=int(input())
if a>=90 and a<=100:
print("A")
elif a>=70 and a<90:
print('B')
elif a>=40 and a<70:
print('C')
elif a>=0 and a<40:
print('D')<file_sep>SELECT INS.ANIMAL_ID,INS.ANIMAL_TYPE,INS.NAME
FROM ANIMAL_INS AS INS JOIN ANIMAL_OUTS AS OUTS ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
WHERE
INS.SEX_UPON_INTAKE != OUTS.SEX_UPON_OUTCOME
AND (OUTS.SEX_UPON_OUTCOME = 'Neutered Male' OR OUTS.SEX_UPON_OUTCOME = 'Spayed Female')
ORDER BY INS.ANIMAL_ID<file_sep>n=int(input())
for i in range(0,n):
print(' '*i+'*'*(((n*2)-1)-i*2))<file_sep>arr=input()
sum1=sum2=0
for i in range(len(arr)):
if i < len(arr)/2:
sum1+=int(arr[i])
else:
sum2+=int(arr[i])
if sum1 == sum2:
print("LUCKY")
else:
print("READY")<file_sep>n,m=map(int,input().split())
c=[False]*(n+1) #방문했는지
a=[0]*m #숫자
def go(index,n,m):
if index == m:
print(' '.join(map(str,a)))
return
for i in range(1,n+1):
c[i]=True
a[index]=i
go(index+1,n,m)
c[i]=False
go(0,n,m)<file_sep>def solution(s):
zero=0
cnt=0
check=s
while check!='1':
zero+=check.count('0')
check=check.replace('0','')
check=bin(len(check))[2:]
cnt+=1
return [cnt,zero]<file_sep>r,g,b= map(int, input().split())
sum=0
for R in range(r):
for G in range(g):
for B in range(b):
print(R,G,B)
sum+=1
print(sum)
<file_sep>n=int(input())
arr=list(map(int,input().split()))
ans=[]
arr.sort()
last=sum(arr)
num_list=[False for _ in range(1,last+2)]
num_list[0]=True
def go(ans,start):
if ans:
num_list[sum(ans)] = True
for i in range(start,n):
ans.append(arr[i])
go(ans,i+1)
ans.pop()
go(ans,0)
print(last+1) if False not in num_list else print(num_list.index(False))
n=int(input())
arr=list(map(int,input().split()))
num_list=[False for _ in range(1,sum(arr)+3)]
arr.sort()
num_list[0]=True
def go(arr,index,sum):
if sum and not num_list[sum]:
num_list[sum]=True
if index == len(arr):
return
go(arr,index+1,sum+arr[index])
go(arr,index+1,sum)
return #d
go(arr,0,0)
print(num_list.index(False))<file_sep>#내 풀이
class Solution:
def isPalindrome(self, s: str) -> bool:
alp=[]
for i in range(len(s)):
if s[i].isalpha() or s[i].isdigit():
alp.append(s[i].lower())
alp1=list(reversed(alp))
return True if''.join(alp) == ''.join(alp1) else False
#성능 업
while len(alp) > 1:
if alp.pop(0) != alp.pop():
return False
return True
#중간에 아니면 바로 return 할 수 있음
#isalnum -> 문자 또는 숫자
#최적의 풀이
s= s.lower()
s=re.sub('[^a-z0-9]','',s)
return s == s[::-1]<file_sep>a = float(input())
print('%.6f' % a)<file_sep>n,m,x,y,do=map(int,input().split())
arr = [list(map(int,input().split())) for _ in range(n)]
moves = list(map(int,input().split()))
dice=[0]*7
#동 서 북 남
dx=[0,0,-1,1]
dy=[1,-1,0,0]
for k in moves:
k-=1
nx,ny= x+dx[k],y+dy[k]
if 0<=nx<n and 0<=ny<m:
if k==0:
dice[1], dice[3], dice[4], dice[6] = dice[4], dice[1], dice[6], dice[3]
elif k == 1:
dice[1], dice[3], dice[4], dice[6] = dice[3], dice[6], dice[1], dice[4]
elif k==2:
dice[1], dice[2], dice[5], dice[6] = dice[5], dice[1], dice[6], dice[2]
else:
dice[1], dice[2], dice[5], dice[6] = dice[2], dice[6], dice[1], dice[5]
if arr[nx][ny]==0:
arr[nx][ny]=dice[6]
else:
dice[6]=arr[nx][ny]
arr[nx][ny]=0
x,y=nx,ny
print(dice[1])
#배열 돌리기처럼 냅다 돌려주면 되는 건데 너무 복잡하게 생각했고 심지어 전개도를 틀림
# NS =[0]*4
# NW =[0]*4
# for move in moves:
# if move <=2:
# if move == 1: #동
# if 0 <= y+1 < m:
# NW.insert(0,NW.pop())
# y+=1
#
# else: #서
# if 0 <= y - 1 < m:
# NW.append(NW.pop(0))
# y-=1
#
# if arr[x][y] == 0:
# arr[x][y]=NW[0]
# else:
# NW[0] = arr[x][y]
# ans.append(NW[2])
# NS[2]=NW[2]
# print("NW",NW)
# else:
# if move == 3: #북
# if 0<=x-1<n:
# NS.insert(0,NS.pop())
# x-=1
# else:
# if 0 <= x + 1 < n: #남
# NS.append(NS.pop(0))
# x+=1
# if arr[x][y] == 0:
# arr[x][y] = NS[0]
# else:
# NS[0] = arr[x][y]
# ans.append(NS[2])
# NW[2] = NS[2]
# NS[0] = NW[0]
# print("NS",NS)
# print(*ans,sep='\n')<file_sep>#500 100 50 10
num = int(input())
a=num//500
b=(num%500)//100
c=(num%500%100)//50
d=(num%500%100%50)//10
print(a,b,c,d)<file_sep>num_list=list(map(int,input().split()))
i=0
while 1:
if(num_list[i]==0):
break;
print(num_list[i])
i+=1<file_sep>def solution(s):
n_string = []
answer=[]
s=s.lstrip('{').rstrip('}').split('},{')
for i,se in enumerate(s):
n_string.append(se.split(','))
n_string.sort(key=len)
for tupl in n_string:
for i in tupl:
if int(i) not in answer:
answer.append(int(i))
return answer<file_sep>def arr_rotate(arr,n):
result=[[0]*n for _ in range(n)]
#no=[[0]* n] *n -> 얕은 복사로 인해 값이 모두 바뀌는 현상이 일어남.
for i in range(n):
for j in range(n):
result[j][n-1-i]=arr[i][j]
return result<file_sep>def solution(phone_book):
phone_book.sort()
answer = True
for x,y in zip(phone_book, phone_book[1:]):
if y.startswith(x):
answer = False
break
return(answer)
def solution(phone_book):
if len(phone_book) == 1:
return False
phone_book.sort()
for prefix in phone_book:
phone_book.remove(prefix)
for phone_num in phone_book:
if phone_num.startswith(prefix):
return False
return True
#효율성 3,4번 실패한 풀이<file_sep>n,m=map(int,input().split())
x,y,d=map(int,input().split())
g=[list(map(int,input().split())) for _ in range(n)]
check = [[0]*m for _ in range(n)]
ans=1
turn_count=0
#북 동 남 서
dx=[-1,0,1,0]
dy=[0,1,0,-1]
def turn_left():
global d
d = (d-1) % 4
return
check[x][y]=1 #현재 위치 청소
while True:
turn_left()
nx=x+dx[d]
ny=y+dy[d]
#check를 안하면 방문하지 않고 0일 때
if g[nx][ny] == 0 and check[nx][ny] == 0: #왼쪽에 청소하지 않은 공간이 존재한다면
x,y=nx,ny #전진
check[nx][ny]=1 #청소 완료
ans+=1
turn_count=0
continue
else:
turn_count+=1
if turn_count == 4:
nx = x - dx[d]
ny = y - dy[d]
if g[nx][ny] == 0:
x, y = nx, ny
else:
break
turn_count = 0
print(ans)<file_sep>from collections import defaultdict
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
way=defaultdict(list)
n=len(tickets)
answer=[]
for ticket in sorted(tickets):
_from,_to =ticket
way[_from].append(_to)
def dfs(f):
while way[f]:
dfs(way[f].pop(0))
answer.append(f)
dfs('JFK')
return answer[::-1]<file_sep>def solution(A, B):
answer = 0
A.sort(reverse = True)
B.sort(reverse = True)
for a in A:
if a >= B[0]:
continue
else:
answer += 1
del B[0]
return answer<file_sep>a,b,c=map(int,input().split())
day=1
while(day%a!=0 or day%b!=0 or day%c!=0):
day+=1
print(day)<file_sep>from collections import defaultdict
#순환 구조 판별
def solution():
traced=set()
arr=[]
graph=defaultdict(list)
visited=set()
for x,y in arr:
graph[x].append(y)
def dfs(i):
if i in traced:
return False
if i in visited:
return False
traced.add(i)
for y in graph[i]:
if not dfs(y):
return False
traced.remove(i)
visited.add(i) #탐색이 종료되고 나서 추가하는 것으로 탐색 도중에 순환 구조가 발견되면 False가 리턴되면서 visited 추가가 안되도록 함.
return True
for x in list(graph):
if not dfs(x):
return False
return True<file_sep>a=ord(input())
a_list = []
b=97
for i in range(b,a+1,1):
a_list.append(chr(b))
b+=1
for i in range(0,len(a_list)):
print(a_list[i],end=' ')<file_sep>#프로그래머스 괄호변환프로그래머스 괄호변환 60058
def solution(p):
ope = 0
close = 0
u=''
v=''
if len(p) == 0:
return p
if check(p) == True:
return p
for i in range(len(p)):
if p[i] == '(':
ope += 1
else:
close += 1
#u / v로 분리하는 과정
if ope - close == 0:
for j in range(i+1):
u += p[j]
for k in range(i+1,len(p)):
v += p[k]
break
if check(u) == True:
u+=solution(v)
return u
else:
st = '('
st+=solution(v)
st+=')'
u=list(u)
u.pop()
u.pop(0)
st+=reverse(''.join(u))
return st
#올바른 문자열인지 확인
def check(s):
correct = []
for i in range(len(s)):
if s[i] == '(':
correct.append('(')
if correct and correct[-1] == '(' and s[i] == ')':
correct.pop()
if not correct:
return True
else: return False
def reverse(strin):
s = list(strin)
for i in range(len(s)):
if s[i] == '(':
s[i] = ')'
else:
s[i] = '('
return ''.join(s)<file_sep>from collections import defaultdict
def solution(tickets):
graph = defaultdict(list)
for start, end in sorted(tickets):
graph[start].append(end)
route = []
def dfs(a):
while graph[a]:
dfs(graph[a].pop(0))
route.append(a)
dfs('ICN')
return route[::-1]<file_sep>remove_set={0} #제거하여할 요소들 ex) 0
arr=[0,0,1,3,4]
for i in range(len(arr)):
arr[i] = [i for i in arr[i] if i not in remove_set]
print(arr)<file_sep>n=int(input())
arr=list(map(int,input().split()))
stack=[]
ans=-999
def dfs(elements):
global ans
if len(stack) == n:
sum=0
for i in range(1,n):
sum += abs(stack[i]-stack[i-1])
if sum>ans:
ans=sum
for e in elements:
next_elements=elements[:]
next_elements.remove(e)
stack.append(e)
dfs(next_elements)
stack.pop()
dfs(arr)
print(ans)<file_sep>from collections import deque
n=int(input())
arr=[[0]*n for _ in range(n)]
k=int(input())
#북 동 남 서
dx=[-1,0,1,0]
dy=[0,1,0,-1]
for _ in range(k):
x,y=map(int,input().split())
arr[x-1][y-1]=1 #사과
l=int(input())
l_list=[]
direction=1
now=deque()
ans=0
for _ in range(l):
x,c=input().split()
l_list.append((int(x),c))
def rotate_90(d):
global direction
if d =='L':
direction = (direction-1)%4
else:
direction = (direction + 1) % 4
def start():
global direction
now.append((0,0))
time=1
x=y=0
arr[0][0] = 2
while True:
nx, ny = x + dx[direction], y + dy[direction] # 머리
if 0<=nx<n and 0<=ny<n and arr[nx][ny] !=2:
if arr[nx][ny] == 0: #사과가 없다면
temp_x,temp_y=now.popleft()
arr[temp_x][temp_y]=0
arr[nx][ny] = 2
now.append((nx,ny))
x,y=nx,ny
if l_list and l_list[0][0] == time:
rotate_90(l_list[0][1])
l_list.pop(0)
time += 1
else:
return time
print(start()) # 북 동 남 서<file_sep>n,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
b.sort()
for i in range(k):
if a[i] < b[n-1-i]:
a[i]=b[n-1-i]
else: break
<file_sep>from itertools import permutations
def is_prime_number(x):
if x < 2:
return False
for i in range(2,x):
if x%i ==0:
return False
return True
def solution(numbers):
number=list(map(int,numbers))
answer=[]
num=set()
count=0
for i in range(1,len(number)+1):
answer=list(permutations(numbers,i))
for ans in answer:
num.add(int(''.join(ans)))
for n in num:
if is_prime_number(n) == True:
count += 1
return count<file_sep>n=int(input())
graph=[list(map(int,input())) for _ in range(n)]
visited=[[0]*n for _ in range(n)]
ans=0
their=[]
count=0
def dfs(x,y):
global count
if 0<=x<n and 0<=y<n:
if visited[x][y] != 0:
return False
if graph[x][y] == 1:
count+=1
visited[x][y]=1
dfs(x+1,y)
dfs(x-1,y)
dfs(x,y+1)
dfs(x,y-1)
return True
for i in range(n):
for j in range(n):
if dfs(i,j):
ans +=1
their.append(count)
count=0
print(ans)
print(*sorted(their),sep='\n')<file_sep>a = float(input())
print("%.2f"% a)
# round 사용시 1.00은 오류 남
<file_sep>import math
def solution(arr):
lcm=(arr[0]*arr[1])//math.gcd(arr[0],arr[1])
for i in range(2,len(arr)):
lcm=(arr[i]*lcm)//math.gcd(arr[i],lcm)
return lcm<file_sep>from collections import deque
n,k=map(int,input().split())
arr=list(map(int,input().split()))
truck=[0]*n
ans=0
def rotate(arr):
q=deque(arr)
q.appendleft(q.pop())
return list(q)
while True:
truck=rotate(truck)
arr=rotate(arr)
truck[n-1]=0
ans+=1
for i in range(n-2,-1,-1):
if truck[i]:
if truck[i+1]==0 and arr[i+1]>=1:
truck[i+1]=1
arr[i+1]-=1
truck[i]=0
truck[n - 1] = 0
if truck[0]==0 and arr[0]>0:
arr[0]-=1
truck[0]=1
if arr.count(0)>=k:
break
print(ans)<file_sep>a=input()
b=int(a,16) #16진수를 10진수로 변환
print(format(b,'o')) #10진수를 8진수로 변환<file_sep>def solution(n):
return bin(n)[2:].count('1')
# 2의 n제곱 수인 경우에는 에너지가 필요하지 않다
# 2의 n제곱인 경우 -> 이진수로 변경 후에 1이 한 개일 경우
# 아닌 경우 -> 최대한 2의 n제곱쪽으로 편승해야함 그래서 +1 해서 맞춰줘야하는데 그 횟수 == 1의 개수<file_sep>#하향식 (메모이제이션)
class Solution:
d = [0] * 31
def fib(self, n: int) -> int:
if n <= 1:
return n
if self.d[n]:
return self.d[n]
self.d[n] = self.fib(n - 1) + self.fib(n - 2)
return self.d[n]
#타뷸레이션 (상향식)
class Solution:
d = [0] * 31
def fib(self, n: int) -> int:
self.d[1]=1
for i in range(2,n+1):
self.d[n] = self.d[n - 1] + self.d[n - 2]
return self.d[n]
#재귀를 사용하지 않고 반복으로 풀이하며 작은 값부터 계산하면서 타뷸레이션한다.
#두 변수만 이용해 공간 정략
def fib(self, n: int) -> int:
x,y=0,1
for i in range(0,n):
x,y=y,x+y
return x
<file_sep>n,k=map(int,input().split())
number=input()
stack=[]
K=k
for num in number:
while (k>0) and stack and stack[-1]<num:
stack.pop()
k-=1
stack.append(num)
print(''.join(stack[:n-K]))
<file_sep>s = input()
arr=[]
for i in range(len(s)):
arr.append(int(s[i]))
sum=arr[0]
for i in range(1,len(arr)):
if arr[i-1] != 0 :
sum *= arr[i]
else:
sum += arr[i]
print(sum)<file_sep>import sys
n,m=map(int,sys.stdin.readline().split())
vertex=[[] for i in range(n+1)]
visited=[False]*(n+1)
count=0
sys.setrecursionlimit(10**6)
for _ in range(m):
v1, v2 = map(int, sys.stdin.readline().split())
vertex[v1].append(v2)
vertex[v2].append(v1)
def dfs(start):
if not visited[start]:
visited[start] = True
for i in vertex[start]:
if not visited[i]:
dfs(i)
return
for i in range(1,n+1):
if not visited[i]:
dfs(i)
count += 1
print(count)
<file_sep>#K1KA5CB7
arr=input()
result=[]
value=0
for i in arr:
if i.isalpha() == True:
result.append(i)
else:
value += int(i)
result.sort()
print(''.join(result)+str(value))
<file_sep>n,k = map(int,input().split())
count=0
while n!=1:
if n%k != 0:
n-=1
count+=1
else:
n = n//k
count+=1
print(count)<file_sep>n=int(input())
days=[]
profit=[]
selected=[False]*n
max=0
_max=0
for _ in range(n):
a,b=map(int,input().split())
days.append(a)
profit.append(b)
def go(start,n):
global max
global _max
for i in range(start,n):
if selected[i]:
continue
if i+1+days[i]>n+1:
continue
selected[i]=True
_max += profit[i]
go(i+days[i],n)
_max -= profit[i]
selected[i]=False
if _max > max:
max = _max
go(0,n)
print(max)<file_sep>def dfs(cnt, result, add, sub, mul, div):
global max_v
global min_v
if cnt == n:
max_v = max(max_v, result)
min_v = min(min_v, result)
return
if add > 0:
dfs(cnt + 1, result + num_list[cnt], add - 1, sub, mul, div)
if sub > 0:
dfs(cnt + 1, result - num_list[cnt], add, sub - 1, mul, div)
if mul > 0:
dfs(cnt + 1, result * num_list[cnt], add, sub, mul - 1, div)
if div > 0:
dfs(cnt + 1, -((-result) // (num_list[cnt])) if result < 0 else result // num_list[cnt], add, sub, mul, div - 1)
n = int(input())
num_list = list(map(int, input().split()))
add, sub, mul, div = map(int, input().split())
max_v = -1000000001
min_v = 1000000001
dfs(1, num_list[0], add, sub, mul, div)
print(max_v)
print(min_v)
<file_sep>def solution(s):
stack=[]
if not len(s) or set(s) == {')'} or s[0]==')':
return False
for i in s:
if i == '(':
stack.append(i)
else:
if stack and stack[-1] == '(':
stack.pop()
return False if stack else True<file_sep>h,b,c,s = map(int,input().split())
sum=h*b*c*s
print('%.1f' % (sum/8/1024/1024),'MB')<file_sep>from collections import deque
q=deque()
s,b=map(int,input().split())
next=[i for i in range(101)]
dist=[-1 for _ in range(101)]
dist[1]=0
q.append(1)
for _ in range(s):
x,y=map(int,input().split())
next[x]=y
for _ in range(b):
u,v=map(int,input().split())
next[u]=v
while q:
x=q.popleft()
for i in range(1,7):
y=i+x
if y>100:
continue
y=next[y]
if dist[y] == -1:
dist[y]=dist[x]+1
q.append(y)
print(dist[100])<file_sep># from itertools import permutations
# from collections import deque
# n=int(input())
# arr=list(map(int,input().split()))
# op_list=list(map(int,input().split()))
# ops=[]
# a=[]
# op=['+','-','*','//']
# operators=[]
# answer=[]
# # q=deque(arr)
#
# for op,p in zip(op_list,op):
# for i in range(op):
# ops.append(p)
# print(len(list(permutations(ops,n-1))))
# v=[False for _ in range(len(ops))]
#
# def check(arr,operators):
# global answer
# numList=deque(arr)
# operators=deque(operators)
# while len(numList)!=1:
# a=numList.popleft()
# op=operators.popleft()
# b=numList.popleft()
# numList.appendleft(eval(str(a)+op+str(b)))
# return numList[0]
# cnt=0
#
# def go():
# global cnt
# if len(a)==len(ops):
# print(a,cnt)
# cnt+=1
# answer.append(check(arr,a))
# # operators.append(a)
# return
#
# for i in range(len(ops)):
# if v[i]:
# continue
# a.append(ops[i])
# v[i]=True
# go()
# a.pop()
# v[i]=False
#
# go()
# print(max(answer))
# print(min(answer))
#중복 순열을 구해야하는데 어떻게 구현..?
def dfs(cnt, result, add, sub, mul, div):
global max_v
global min_v
if cnt == n:
max_v = max(max_v, result)
min_v = min(min_v, result)
return
if add > 0:
dfs(cnt + 1, result + num_list[cnt], add - 1, sub, mul, div)
if sub > 0:
dfs(cnt + 1, result - num_list[cnt], add, sub - 1, mul, div)
if mul > 0:
dfs(cnt + 1, result * num_list[cnt], add, sub, mul - 1, div)
if div > 0:
dfs(cnt + 1, -((-result) // (num_list[cnt])) if result < 0 else result // num_list[cnt], add, sub, mul, div - 1)
n = int(input())
num_list = list(map(int, input().split()))
add, sub, mul, div = map(int, input().split())
max_v = -1000000001
min_v = 1000000001
dfs(1, num_list[0], add, sub, mul, div)
print(max_v)
print(min_v)
<file_sep>n,m,x,y,k=map(int,input().split())
#동 서 북 남
mmap=[list(map(int,input().split())) for _ in range(n)]
moves=list(map(int,input().split()))
dx=[0,0,-1,1]
dy=[1,-1,0,0]
dice=[0]*7
for mo in moves:
nx,ny=x+dx[mo-1],y+dy[mo-1]
if 0<=nx<n and 0<=ny<m:
if mo==1: #동
dice[1],dice[3],dice[6],dice[4]=dice[4],dice[1],dice[3],dice[6]
elif mo==2: #서
dice[1], dice[3], dice[6], dice[4]=dice[3],dice[6],dice[4],dice[1]
elif mo==3: #북
dice[2], dice[1], dice[5], dice[6]=dice[1],dice[5],dice[6],dice[2]
else: #남
dice[2], dice[1], dice[5], dice[6] = dice[6], dice[2], dice[1], dice[5]
x,y=nx,ny
if mmap[nx][ny] == 0:
mmap[nx][ny]=dice[6]
else:
dice[6]=mmap[nx][ny]
mmap[nx][ny]=0
print(dice[1])
<file_sep>from collections import deque
n,m,k=map(int,input().split())
arr=[list(map(int,input())) for _ in range(n)]
dist=[[[0]*(k+1) for j in range(m)] for i in range(n)]
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
q=deque()
q.append((0,0,k))
ans=1001
dist[0][0][k]=1
#벽을 뚫을 수 있는 수 k부터 시작해서 하나씩 줄여가는 식으로 작성
def dfs():
while q:
x,y,z=q.popleft()
if x==n-1 and y==m-1:
return dist[x][y][z]
for i in range(4):
nx,ny=x+dx[i],y+dy[i]
if 0<=nx<n and 0<=ny<m:
if arr[nx][ny] == 0 and dist[nx][ny][z] == 0:
dist[nx][ny][z]=dist[x][y][z]+1
q.append((nx,ny,z))
if z>0 and arr[nx][ny] == 1 and dist[nx][ny][z-1] == 0:
dist[nx][ny][z-1] = dist[x][y][z] + 1
q.append((nx,ny,z-1))
return -1
print(dfs())
# n, m = map(int, input().split())
# arr = []
# wall = []
# for i in range(n):
# inn = list(map(int, input()))
# arr.append(inn)
# for j in range(m):
# if inn[j] == 1:
# wall.append((i, j))
# q = deque()
# dx = [0, 0, -1, 1]
# dy = [1, -1, 0, 0]
# wall_v = [0] * len(wall)
# ans = 1000
# #
# def bfs(temp):
# dist = [[0] * m for _ in range(n)]
# visited = [[0] * m for _ in range(n)]
# dist[0][0]=1
# visited[0][0]=True
# q.append((0, 0))
#
# while q:
# x,y=q.popleft()
# for i in range(4):
# nx, ny = x + dx[i], y + dy[i]
# if 0 <= nx < n and 0 <= ny < m and not temp[nx][ny] and not visited[nx][ny]:
# visited[nx][ny] = True
# dist[nx][ny] = dist[x][y] + 1
# q.append((nx,ny))
# print(*visited,sep='\n')
# print()
# return dist[n - 1][m - 1]
#
#
# def copy(arr):
# temp = [[0] * m for _ in range(n)]
# for i in range(n):
# for j in range(m):
# temp[i][j] = arr[i][j]
# return temp
#
#
# def dfs(start, cnt):
# global ans
# temp = copy(arr)
#
# for i in range(start, len(wall)):
# if not wall_v[i]:
# x, y = wall[i]
# wall_v[i] = True
# temp[x][y] = 0
# least = bfs(temp)
# if least:
# ans = min(least, ans)
# cnt+=1
# dfs(i+1,cnt)
# temp[x][y] = 1
# cnt-=1
# dfs(0,0)
# print(ans) if ans != 1000 else print(-1)
# #시간초과
# #메모리 초과
# from collections import deque
# from itertools import combinations
# n,m,k=map(int,input().split())
# walls=[]
# arr=[]
# for i in range(n):
# inp = list(map(int,input()))
# for j,pp in enumerate(inp):
# if pp == 1:
# walls.append((i,j))
# arr.append(inp)
# dist=[[-1 for _ in range(m)] for _ in range(n)]
# dx=[1,-1,0,0]
# dy=[0,0,1,-1]
# ans=-1
# def back(index,cnt,wall):
# global ans
# global arr
# if index == len(wall):
# if cnt == k:
# dist = [[-1 for _ in range(m)] for _ in range(n)]
# q=deque()
# q.append((0,0))
# dist[0][0]=1
#
# while q:
# x,y=q.popleft()
# for i in range(4):
# nx,ny=x+dx[i],y+dy[i]
# if 0<=nx<n and 0<=ny<m:
# if dist[nx][ny] == -1 and not arr[nx][ny]:
#
# dist[nx][ny]=dist[x][y]+1
# q.append((nx,ny))
#
# if ans == -1 or ans>dist[n-1][m-1]:
# if dist[n-1][m-1]!= -1:
# ans=dist[n-1][m-1]
# return
#
# else:
# x,y=wall[index]
# arr[x][y]=0
# back(index+1,cnt+1,wall)
# arr[x][y]=1
# back(index+1,cnt,wall)
#
# for i in range(k+1):
# for combi in list(combinations(walls,i)):
# back(0,0,list(combi))
#
# print(ans)<file_sep>#include <iostream>
#include <string>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
int cost = 0;
cost = c - b;
if (cost <= 0) cout << "-1" << endl;
else cout << a / cost + 1;
}<file_sep>n=int(input())
arr= list(input().split())
x,y = 1,1
nx,ny=1,1
move_types=['L','R','U','D']
dx =[0,0,-1,1]
dy =[-1,1,0,0]
for i in arr:
for m in range(len(move_types)):
if i == move_types[m]:
nx=x+dx[m]
ny=y+dy[m]
if nx < 1 or nx > n or ny < 1 or ny > n:
continue
x,y=nx,ny
print(x,y)<file_sep>n,m=map(int,input().split())
_c=list(map(int,input().split()))
_c.sort()
c=[False]*n
a=[0]*m
def go(index,n,m):
if index == m:
print(" ".join(map(str,a)))
return
for i in range(n):
if c[i]:
continue
else:
c[i]=True
a[index]=_c[i]
go(index+1,n,m)
c[i]=False
go(0,n,m)<file_sep>a= int(input())
sum =0
i=1
while 1:
sum += i
i+=1
if(sum>=i):
print(sum)
break
<file_sep>n,m,k=map(int,input().split())
A=[list(map(int,input().split())) for _ in range(n)]
yangboon=[[5]*n for _ in range(n)]
tree=[[[] for _ in range(n)] for _ in range(n)]
die=[]
for i in range(m):
x,y,z=map(int,input().split())#x,y,나이
tree[x-1][y-1].append(z)
ans=0
dx=[-1,-1,-1,0,0,1,1,1]
dy=[-1,0,1,-1,1,-1,0,1]
for _ in range(k):
for i in range(n):
for j in range(n):
if tree[i][j]:
tree[i][j].sort()
temp_tree,dead=[],0
for age in tree[i][j]:
if age<=yangboon[i][j]:
yangboon[i][j] -= age
age+=1
temp_tree.append(age)
else:
dead+=age//2
yangboon[i][j]+=dead
tree[i][j]=[]
tree[i][j].extend(temp_tree)
if not tree:
print(0)
exit(0)
#가을
for i in range(n):
for j in range(n):
if tree[i][j]:
for age in tree[i][j]:
if age % 5 == 0:
for move in range(8):
nx,ny=i+dx[move],j+dy[move]
if 0<=nx<n and 0<=ny<n:
tree[nx][ny].append(1)
#겨울
for i in range(n):
for j in range(n):
yangboon[i][j]+=A[i][j]
for i in range(n):
for j in range(n):
if tree[i][j]:
ans+=len(tree[i][j])
print(ans)<file_sep>from collections import deque
tob=int(input())
tobnis=[list(map(int,input())) for _ in range(tob)]
m=int(input())
move=[list(map(int,input().split())) for _ in range(m)]
ans=0
d=[0]*tob
def clockwise(arr): #1
q=deque(arr)
q.appendleft(q.pop())
return list(q)
def counterClockwise(arr): #-1
q=deque(arr)
q.append(q.popleft())
return list(q)
for m in move:
which,how=m
which-=1
d = [0] * tob
d[which]=how
for i in range(which-1,-1,-1): #왼쪽 파트
if tobnis[i+1][6] != tobnis[i][2]:
d[i]=-d[i+1]
else: break #한 번 막히면 그 이후로는 안됨
for i in range(which+1,tob):
if tobnis[i - 1][2] != tobnis[i][6]: # 7
d[i]=-d[i-1]
else: break
for i in range(tob):
if d[i] == 0:
continue #안 돌아간 것도 check 해줘야함
if d[i] == 1:
tobnis[i] = clockwise(tobnis[i])
elif d[i] == -1:
tobnis[i] = counterClockwise(tobnis[i])
for tob in tobnis:
if tob[0] == 1:
ans+=1
print(ans)
<file_sep>a=input()
print(int(a,8))
#여기서 int 함수는 문자열을 전환하는 것이기 때문에 str 형식이어야 함.
<file_sep>def solution(food_times, k):
answer = 0
arr_sum = sum(food_times)
count = k+1
i=0
while count != 0:
if k>arr_sum:
break
answer=i%len(food_times)
if arr_sum != 0:
if food_times[answer] != 0:
food_times[answer] = food_times[answer]-1
arr_sum -= 1
count -= 1
else:
answer += 1
else:
return -1
i += 1
answer += 1
return answer
#나의 효율성 제로 코드
print('so',solution([0,0,0,0,0,0,0,1],5))<file_sep>a, b, c = map(int,input().split("."))
print("%.2d" % c +"-"+"%.2d" % b +"-"+"%.4d" % a)<file_sep>n=int(input())
d=[]
p=[]
v=[False]*n
t=n
_max=0
for _ in range(n):
day,pay=map(int,input().split())
d.append(day)
p.append(pay)
def check(start,hap):
global _max
for i in range(start,n):
if v[i]:
continue
if i+1+d[i]>n+1:
continue
v[i]=True
hap+=p[i]
check(i+d[i],hap)
hap-=p[i]
v[i]=False
_max=max(hap,_max)
check(0,0)
print(_max)
<file_sep>from collections import deque
def bfs(graph,start,visited):
queue = deque([start])
visited[start]= True
while queue:
v= queue.popleft()
print(v,end=' ')
for i in graph[v]:
if not visited[i]:
queue.append(i)
visited[i]= True
n=int(input())
m=int(input())
visited=[False] *(n+1)
graph=[[] for _ in range(n+1)]
for i in range(m):
arr=list(map(int,input().split()))
graph[arr[0]].append(arr[1])
graph[arr[1]].append(arr[0])
for i in graph:
i.sort()
bfs(graph,1,visited)
<file_sep>from collections import deque
n,l,r=map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(n)]
dx=[0,0,-1,1]
dy=[1,-1,0,0]
ans=0
def bfs(i,j,visited):
global ans
union = [(i, j)]
union_p = [arr[i][j]]
q = deque()
q.append((i, j))
visited[i][j]=True
while q:
x,y=q.popleft()
for i in range(4):
nx,ny=x+dx[i],y+dy[i]
if 0<=nx<n and 0<=ny<n:
if l<=abs(arr[nx][ny]-arr[x][y])<=r:
if not visited[nx][ny]:
union.append((nx,ny))
union_p.append(arr[nx][ny])
visited[nx][ny]=True
q.append((nx,ny))
for xx,yy in union:
arr[xx][yy]=sum(union_p)//len(union_p)
return len(union)
while True:
visited=[[0]*n for _ in range(n)]
chk=False
for i in range(n):
for j in range(n):
if not visited[i][j]:
if bfs(i,j,visited)>1:
chk=True
if not chk:
break
ans+=1
print(ans)
<file_sep>string=input()
target=input()
target_len=len(target)
stack=[]
for i in range(len(string)):
stack.append(string[i])
if ''.join(stack[-target_len:]) == target:
for _ in range(target_len):
stack.pop()
print(''.join(stack)) if len(stack) else print('FRULA')<file_sep>#1
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
if not nums:
return nums
l=len(nums)
ans=[]
for i in range(l-k+1):
ans.append(max(nums[i:i+k]))
return ans
#2
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
results=[]
window=collections.deque()
current_max=float('-inf')
for i,v in enumerate(nums):
window.append(v)
if i<k-1:
continue #k만큼은 로직 생각 않고 일단 넣는다
if current_max == float('-inf'):
current_max=max(window)
elif v>current_max:
current_max=v
results.append(current_max)
if current_max == window.popleft():
current_max = float('-inf')
return results
#3
class Solution:
def maxSlidingWindow(self, nums, k):
queue, ans = deque(), [] # queue: list of index where nums[index] is decreasing
for i, n in enumerate(nums):
while queue and nums[queue[-1]] < n:
queue.pop()
queue.append(i)
if queue[0] == i - k:
queue.popleft()
if i >= k - 1:
ans.append(nums[queue[0]])
return ans<file_sep>from collections import deque
def check(s):
che=[]
d = {
')' : '(',
'}' : '{',
']' : '['
}
answer = 0
for i in s:
if i in '{[(':
che.append(i)
else:
if che:
top=che.pop()
if d[i] != top:
return 0
else:
return 0
return len(che) == 0
def solution(s):
answer = 0
q=deque(s)
l=len(s)
while l:
q.append(q.popleft())
answer+=check(q)
l-=1
return answer<file_sep>n,m,k = map(int,input().split())
n_list=input().split()
sum=0
count=0
for i in range(n):
n_list[i]=int(n_list[i])
n_list.sort()
while count != m:
for j in range(k):
sum += n_list[n-1]
count+=1
sum += n_list[n-2]
count+=1
print(sum)<file_sep>class Solution {
public String solution(String my_string) {
StringBuffer sb = new StringBuffer(my_string);
return sb.reverse().toString();
}
}
class Solution {
public String solution(String my_string) {
StringBuilder sb = new StringBuilder(my_string);
return sb.reverse().toString();
}
}<file_sep>def find(pplace, waiting):
dx = [1, 0, 2, 0, -1, 0, -2, 0]
dy = [0, 1, 0, 2, 0, -1, 0, -2]
while pplace:
x, y = pplace.pop()
#대각선 확인 풀이
if 0 <= x + 1 < 5 and 0 <= y + 1 < 5 and waiting[x + 1][y + 1] == 'P':
if waiting[x + 1][y] == 'O' or waiting[x][y + 1] == 'O':
return 0
if 0 <= x - 1 < 5 and 0 <= y - 1 < 5 and waiting[x - 1][y - 1] == 'P':
if waiting[x - 1][y] == 'O' or waiting[x][y - 1] == 'O':
return 0
if 0 <= x - 1 < 5 and 0 <= y + 1 < 5 and waiting[x - 1][y + 1] == 'P':
if waiting[x - 1][y] == 'O' or waiting[x][y + 1] == 'O':
return 0
if 0 <= x + 1 < 5 and 0 <= y - 1 < 5 and waiting[x + 1][y - 1] == 'P':
if waiting[x + 1][y] == 'O' or waiting[x][y - 1] == 'O':
return 0
#가로 세로 확인 풀이
for i in range(8):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < 5 and 0 <= ny < 5:
if waiting[nx][ny] == 'P' and waiting[abs(nx + x) // 2][abs(ny + y) // 2] != 'X':
return 0
return 1
def solution(places):
answer = []
for place in places:
pplace = []
waiting = [list(p) for p in place]
for i in range(5):
for j in range(5):
if waiting[i][j] == 'P':
pplace.append((i, j))
answer.append(find(pplace, waiting))
return answer<file_sep>from collections import deque
def solution(maps):
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
q = deque()
n = len(maps)
m = len(maps[0])
visited = [[0] * m for _ in range(n)]
dist = [[0] * m for _ in range(n)]
q.append((0, 0))
visited[0][0] = 1
dist[0][0] = 1
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] == 1:
if not visited[nx][ny]:
dist[nx][ny] = dist[x][y] + 1
visited[nx][ny] = 1
q.append((nx, ny))
return -1 if dist[n - 1][m - 1] == 0 else dist[n - 1][m - 1]<file_sep>from itertools import permutations
from collections import deque
n= int(input())
arr= list(input().split())
queue=deque()
count = 0
#+ - * //
op_num=list(map(int,input().split()))
#개수 입력
operator=['+','-','*','/']
op_list=[]
answer=[]
for i in range(4):
for _ in range(op_num[i]):
op_list.append(operator[i])
result=list(set(list(permutations(op_list,n-1))))
for i in range(len(result)):
for j in range(n-1):
queue.append(result[i][j])
#연산자 꺼내기
i=1
r=arr[0]
while queue:
if count != n-1:
count+=1
r+=queue.popleft()
r+=arr[i]
i+=1
r=str(int(eval(r)))
else:
answer.append(int(r))
count = 0
r=arr[0]
i=1
answer.append(int(r))
print(max(answer),min(answer))<file_sep>a,b,c = map(int,input().split("."))
print("%.4d" % a+"."+"%.2d" % b + "."+ "%.2d" % c)<file_sep>from collections import deque
import sys
n= int(input())
graph=[]
count = 0
temp=[['X']*n for _ in range(n)]
where=[]
chec = False
for i in range(n):
a=list(input().split())
graph.append(a)
for i in range(n):
for j in range(n):
if graph[i][j] == 'T':
where.append((i,j))
#북 남 동 서
dx=[-1,1,0,0]
dy=[0,0,1,-1]
def prin():
print()
for i in range(n):
for j in range(n):
print(temp[i][j],end=' ')
print()
return
def check(x,y):
for i in range(4):
for move in range(1,n):
nx = x +(dx[i]*move)
ny = y +(dy[i]*move)
if nx>=0 and ny>=0 and nx<n and ny<n:
if temp[nx][ny] == 'X':
temp[nx][ny] = 'T'
elif temp[nx][ny] == 'S':
print('False')
return False
else:
break
prin()
return
def dfs(count):
global chec
if count == 3:
for a in range(n):
for b in range(n):
temp[a][b] = graph[a][b]
for this in where:
x,y=this
print(x,y)
check(x,y)
prin()
return
else:
for i in range(n):
for j in range(n):
if graph[i][j] == 'X' :
graph[i][j] = 'O'
count += 1
dfs(count)
graph[i][j] = 'X'
count -=1
dfs(0)
print('NO')<file_sep>def dfs(index,path):
digits = "23"
if len(path) == len(digits):
result.append(path)
print(path)
return
for i in range(index,len(digits)):
for j in dic[digits[i]]:
dfs(i+1,path+j)
dic={'2':"abc",'3':"def",'4':"ghi",'5':"jkl",'6':"mno",'7':"pqrs",'8':"tuv",'9':"wxyz"}
result=[]
dfs(0,"")<file_sep>n=int(input())
def go(sum,n):
if sum == n:
return 1
if sum > n:
return 0
answer=0
for i in range(1,4):
answer += go(sum+i,n)
return answer
#1,2,3을 이용해서 특정 값을 만들면 ( sum == n )이면 경우 하나 추가
for _ in range(n):
m = int(input())
print(go(0,m))<file_sep>SELECT INS.NAME,INS.DATETIME
FROM ANIMAL_INS AS INS LEFT OUTER JOIN ANIMAL_OUTS AS OUTS ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
WHERE OUTS.ANIMAL_ID IS NULL
ORDER BY INS.DATETIME
LIMIT 3
#limit할 때 조건이 있으면 맨 밑에 배치<file_sep>dx = [0,0,1,-1]
dy = [1,-1,0,0]
def go(step, x1, y1, x2, y2):
if step == 11:
return -1
fall1 = False
fall2 = False
if x1 < 0 or x1 >= n or y1 < 0 or y1 >= m: #동전1이 떨어졌을 때
fall1 = True
if x2 < 0 or x2 >= n or y2 < 0 or y2 >= m: #동전2가 떨어졌을 때
fall2 = True
if fall1 and fall2: #동전이 둘 다 떨어진 경우
return -1
if fall1 or fall2: #하나만 떨어진 경우
return step
ans = -1
for k in range(4):
nx1,ny1 = x1+dx[k],y1+dy[k]
nx2,ny2 = x2+dx[k],y2+dy[k]
#움직인 위치가 벽일 경우에 이동 전 위치로 바꿔줌
if 0 <= nx1 < n and 0 <= ny1 < m and a[nx1][ny1] == '#':
nx1,ny1 = x1,y1
if 0 <= nx2 < n and 0 <= ny2 < m and a[nx2][ny2] == '#':
nx2,ny2 = x2,y2
temp = go(step+1,nx1,ny1,nx2,ny2)
if temp == -1:
continue #정답이랑 비교를 하지 않기위해
if ans == -1 or ans > temp:
ans = temp
return ans
n,m = map(int,input().split())
x1=y1=x2=y2=-1
a = [list(input()) for _ in range(n)]
for i in range(n):
for j in range(m):
if a[i][j] == 'o':
if x1 == -1: #첫 동전
x1,y1 = i,j
else: #두번 째 동전
x2,y2 = i,j
a[i][j] = '.'
print(go(0,x1,y1,x2,y2))
<file_sep>def solution(n, left, right):
answer = []
for i in range(left,right+1):
answer.append(max(i//n,i%n)+1)
return answer<file_sep>n = int(input())
arr = list(map(int,input().split()))
arr.sort()
count =0
result=0
for i in range(len(arr)):
val = arr[i]
count+=1
if val == count:
result +=1
count=0
print(result)<file_sep>#숫자 앞에 0으로 채우기
str='4'
str=str.zfill(5) #비파괴적 함수 리턴해서 재할당 해줘야함.
print(str)<file_sep># from collections import deque
# n=int(input())
# arr=[]
# for i in range(n):
# inn=list(map(int,input().split()))
# arr.append(inn)
# for j in range(n):
# if inn[j] == 9:
# bx,by=i,j #상어 위치
# arr[bx][by]=0
#
# #북 남 서 동
# dx=[-1,1,0,0]
# dy=[0,0,-1,1]
#
# sang=[] #상어가 먹을 수 있는 애들 리스트
# baby=2 #상어 크기
# eat=0 #먹은 횟수
# cnt = 0 #몇 초 걸리는 지
#
# def cannoteat(): #종료 확인
# chk=False
# all=0
# for i in range(n):
# for j in range(n):
# if i==bx and j==by:
# continue
# if arr[i][j]<baby:
# chk=True
# all+=arr[i][j]
# if not chk or all == 0:
# return True
# return False
#
# while True:
# q = deque()
# q.append((bx, by))
# visited = [[0] * n for _ in range(n)]
# visited[bx][by]=True
# dist = [[0] * n for _ in range(n)]
# sang = []
# if cannoteat():
# break
# while q:
# x,y=q.popleft()
# turn=0
# for i in range(4):
# nx,ny=x+dx[i],y+dy[i]
# if 0<=nx<n and 0<=ny<n and arr[nx][ny] <= baby:
# if not visited[nx][ny]:
# visited[nx][ny]=True
# dist[nx][ny]=dist[x][y]+1
# if 1<=arr[nx][ny]<baby:
# sang.append([dist[nx][ny],nx,ny])
# else:
# q.append((nx,ny))
#
# else:
# turn+=1
# if turn==4:
# break
# if sang: #먹기 위해서
# sang.sort()
# # sang=sorted(sang,key=lambda x:(x[2],x[0],x[1]),reverse=True) #제일 가까운 것들 중에 제일 위쪽, 왼쪽인거,
# xx,yy,tt=sang[0]
# cnt+=tt
# eat+=1
# arr[xx][yy]=0
# arr[bx][by]=0
# bx,by=xx,yy
# else:
# break
# if eat == baby: #상어의 몸집이 먹은 횟수와 같다면
# eat=0
# baby+=1
#
# print(cnt)
from collections import deque
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def bfs(a, x, y, size):
n = len(a)
ans = []
d = [[-1]*n for _ in range(n)]
q = deque()
q.append((x,y))
d[x][y] = 0
while q:
x,y = q.popleft()
for k in range(4):
nx,ny = x+dx[k],y+dy[k]
if 0 <= nx < n and 0 <= ny < n and d[nx][ny] == -1:
ok = False
eat = False
# 아기 상어는 자신의 크기보다 큰 물고기가 있는 칸은 지나갈 수 없고, 나머지 칸은 모두 지나갈 수 있다.
if a[nx][ny] == 0:
ok = True
elif a[nx][ny] < size: # 아기 상어는 자신의 크기보다 작은 물고기만 먹을 수 있다.
ok = True
eat = True
elif a[nx][ny] == size: # 크기가 같은 물고기는 먹을 수 없지만, 그 물고기가 있는 칸은 지나갈 수 있다.
ok = True
if ok:
q.append((nx,ny))
d[nx][ny] = d[x][y] + 1
if eat:
ans.append((d[nx][ny],nx,ny))
if not ans:
return None
ans.sort()
return ans[0]
n = int(input())
a = [list(map(int,input().split())) for _ in range(n)]
x,y = 0,0
for i in range(n):
for j in range(n):
if a[i][j] == 9:
x,y = i,j
a[i][j] = 0
ans = 0
size = 2
exp = 0
while True:
p = bfs(a, x, y, size)
if p is None:
break
dist, nx, ny = p
a[nx][ny] = 0
ans += dist
exp += 1
if size == exp:
size += 1
exp = 0
x,y = nx,ny
print(ans)<file_sep>n,m,do=map(int,input().split())
graph=[list(map(int,input().split())) for _ in range(n)]
flag=list(map(int,input().split()))
def arrPrint(g):
n=len(g)
m=len(g[0])
for i in range(n):
for j in range(m):
print(g[i][j],end=' ')
print()
def upAndDown(g):
n = len(g)
m = len(g[0])
arr = [[0] * m for _ in range(n)]
for i in range(n//2):
for j in range(m):
arr[i][j],arr[(n-1)-i][j]=g[(n-1)-i][j],g[i][j]
return arr
def leftAndRight(g):
n = len(g)
m = len(g[0])
arr = [[0] * m for _ in range(n)]
for i in range(n):
for j in range(m//2):
arr[i][j],arr[i][(m-1)-j] = g[i][(m-1)-j],g[i][j]
return arr
def right90(g):
n = len(g)
m = len(g[0])
arr = [[0] * n for _ in range(m)] #90도로 돌리기 때문에 행과 열 수가 뒤바뀜
for i in range(n):
for j in range(m):
arr[j][n-1-i]=g[i][j]
return arr
def left90(g):
n = len(g)
m = len(g[0])
arr = [[0] * n for _ in range(m)]
for i in range(n):
for j in range(m):
arr[m-1-j][i] = g[i][j]
return arr
def partRotateRight(g):
n = len(g)
m = len(g[0])
arr = [[0] * m for _ in range(n)]
for i in range(n//2): # 1->2
for j in range(m//2):
arr[i][j+m//2]=g[i][j]
for i in range(n // 2): # 2->3
for j in range(m // 2):
arr[i+n//2][j+m//2] = g[i][j+m//2]
for i in range(n // 2): # 3->4
for j in range(m // 2):
arr[i+n//2][j] = g[i+n//2][j+m//2]
for i in range(n // 2): # 4->1
for j in range(m // 2):
arr[i][j] = g[i+n//2][j]
return arr
def partRotateLeft(g):
n = len(g)
m = len(g[0])
arr = [[0] * m for _ in range(n)]
for i in range(n // 2): # 1->4
for j in range(m // 2):
arr[i+ n // 2][j] = g[i][j]
for i in range(n // 2): # 4->3
for j in range(m // 2):
arr[i + n // 2][j + m // 2] = g[i + n // 2][j]
for i in range(n // 2): # 3->2
for j in range(m // 2):
arr[i][j+ m // 2] = g[i + n // 2][j + m // 2]
for i in range(n // 2): # 2->1
for j in range(m // 2):
arr[i][j] = g[i][j+ m // 2]
return arr
arr=graph
for f in flag:
if f == 1:
arr = upAndDown(arr)
elif f == 2:
arr = leftAndRight(arr)
elif f == 3:
arr = right90(arr)
elif f == 4:
arr = left90(arr)
elif f == 5:
arr = partRotateRight(arr)
else:
arr = partRotateLeft(arr)
arrPrint(arr)<file_sep>#선택 정렬
array=[7,5,9,0,3,1,6,2,4,8]
for i in range(len(array)):
min_index=i
for j in range(i+1,len(array)):
if array[min_index] >array[j]:
min_index=j
array[j],array[min_index]= array[min_index],array[i]
print(array)
#삽입 정렬
for i in range(len(array)):
for j in range(i,0,-1):
if array[j] < array[j-1]: #한 칸씩 왼쪽으로 이동
array[j-1],array[j] = array[j],array[j-1]
else:#자기보다 작은 데이터를 만나면 그 위치에서 멈춤
break
<file_sep>n=int(input())
arr =[list(map(int,input().split())) for _ in range(n)]
end = n//2
s=0
do=0
j=end
for i in range(n):
if i < end+1:
s+=arr[i][j]
for m in range(1,do+1):
s+=arr[i][j-m]
s+=arr[i][j+m]
do+=1
else:
if i == end+1:
do=end-1
s += arr[i][j]
for m in range(1, do + 1):
s += arr[i][j - m]
s += arr[i][j + m]
do-=1
print(s)<file_sep>from collections import deque
r,c,G,R=map(int,input().split())
garden=[]
brownSoil=[]
vitamin=[0]*10
GREEN=3
RED=4
FLOWER=5
EMPTY=0
ans=0
for row in range(r):
row_input=list(map(int,input().split()))
garden.append(row_input)
for i,col in enumerate(row_input):
if col == 2:
brownSoil.append((row,i))
dx=[1,-1,0,0]
dy=[0,0,1,-1]
def bfs():
q=deque()
result = 0
global ans
stateMap = [[[0, 0] for _ in range(c)] for _ in range(r)]
for i in range(len(brownSoil)):
if not vitamin[i]:
continue
x,y=brownSoil[i]
stateMap[x][y] = [0,vitamin[i]]
q.append((x,y))
while q:
x,y=q.popleft()
curT,curS=stateMap[x][y]
if curS == FLOWER:
continue
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if nx<0 or nx>=r or ny < 0 or ny >=c:
continue
if garden[nx][ny] == 0:
continue
if stateMap[nx][ny][1] == 0: #옮겨나갈 수 있는 상태
stateMap[nx][ny]=[curT+1,curS]
q.append((nx,ny))
if stateMap[nx][ny][1] == GREEN:
#빨간 색과 만나고 && 도달한 시간이 같을 경우
if curS == RED and stateMap[nx][ny][0] == curT + 1:
stateMap[nx][ny][1]=FLOWER
result+=1
if stateMap[nx][ny][1] == RED:
if curS == GREEN and stateMap[nx][ny][0] == curT + 1:
stateMap[nx][ny][1]=FLOWER
result+=1
ans=max(ans,result)
return
def bae(index,gcnt,rcnt):
if gcnt == G and rcnt == R:
bfs()
return
for i in range(index,len(brownSoil)):
if not vitamin[i] and gcnt <G:
vitamin[i]= GREEN
bae(i+1,gcnt+1,rcnt)
vitamin[i]=0
if not vitamin[i] and rcnt <R:
vitamin[i]= RED
bae(i+1,gcnt,rcnt+1)
vitamin[i] = 0
bae(0,0,0)
print(ans)<file_sep>a,b,c = map(int,input().split(" "))
print(a+b+c)
avg=(a+b+c)/3
print("%.1f" % avg)<file_sep>a,b=map(int,input().split(" "))
print(a & b)
#둘의 비트 중 둘다 1인것만 1로 <file_sep>n=int(input())
answer=0
s,g,p,d=list(map(int,input().split()))
tier=list(input())
prev=0
for t in tier:
if t == 'B':
answer += (s - 1) - prev
prev = (s - 1) - prev
elif t == 'S':
answer += (g - 1) - prev
prev = (g - 1) - prev
elif t == 'G':
answer += (p - 1) - prev
prev = (p - 1) - prev
elif t == 'P':
answer += (d - 1) - prev
prev = (d - 1) - prev
else:
answer+=d
prev=d
print(answer)<file_sep>from collections import deque
n,m=map(int,input().split())
arr=[]
virus=[]
dx=[1,-1,0,0]
dy=[0,0,-1,1]
ans=-1
for i in range(n):
inn=list(map(int,input().split()))
arr.append(inn)
for j in range(n):
if inn[j] == 2:
virus.append((i,j))
check=[False]*len(virus)
def do(index,cnt):
if index == len(virus):
if cnt==m:
#여기서 탐색
dist = [[-1] * n for _ in range(n)]
q=deque()
for i in range(n):
for j in range(n):
if arr[i][j] == '*':
q.append((i,j))
dist[i][j] = 0
while q:
x,y=q.popleft()
for k in range(4):
nx,ny=x+dx[k],y+dy[k]
if 0<=nx<n and 0<=ny<n:
if dist[nx][ny] == -1 and arr[nx][ny] != 1:
q.append((nx,ny))
dist[nx][ny]=dist[x][y]+1
cur=0
for i in range(n):
for j in range(n):
if arr[i][j] == 0:
if dist[i][j]==-1:
return
if cur<dist[i][j]:
cur=dist[i][j]
global ans
if ans == -1 or ans > cur:
ans=cur
return
else:
x,y=virus[index]
arr[x][y]='*'
do(index+1,cnt+1)
arr[x][y] = 2
do(index+1,cnt)
do(0,0)
print(ans)<file_sep>def solution(new_id):
new_id=new_id.lower()
new_id=list(new_id)
for i in range(len(new_id)):
if not (97<= ord(new_id[i]) <=122 or 48<= ord(new_id[i]) <=57 or ord(new_id[i])==45 or ord(new_id[i])==46 or ord(new_id[i])==95):
new_id[i]=' '
new_id=' '.join(new_id).split()
for i in range(1,len(new_id)):
if new_id[i-1] == new_id[i] == '.':
new_id[i-1] = ' '
continue
new_id=' '.join(new_id).split()
if new_id and new_id[-1]=='.':
new_id.pop(-1)
if new_id and new_id[0]=='.':
new_id.pop(0)
if not new_id:
new_id.append('a')
if len(new_id) >= 16:
new_id = new_id[:15]
if new_id[-1]=='.':
del new_id[-1]
if len(new_id) <= 2:
while len(new_id) != 3:
new_id.append(new_id[-1])
return ''.join(new_id)<file_sep>a=int(input())
print(chr(a))<file_sep>num = int(input())
for i in range(num):
if(i%3==0):
continue
print(i,end='')<file_sep>def solution(prices):
answer = []
count=0
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if prices[i]<=prices[j]:
count += 1
else:
count+=1
break
answer.append(count)
count=0
return answer
#시간 초과시 "리스트 슬라이싱" 사용 하지말고 c스타일의 range 사용
#리스트 슬라이싱 시 O(n)이기 때문<file_sep>from collections import deque
m,n=map(int,input().split())
graph=[list(map(int,input().split())) for _ in range(n)]
dist=[[0]*m for _ in range(n)]
check=[[0]*m for _ in range(n)]
q=deque()
dx=[-1,1,0,0]
dy=[0,0,-1,1]
one=0
minus=0
ans=[]
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
one+=1
if graph[i][j] == -1:
minus+=1
if minus == n*m:
print(-1)
exit()
if one == n*m - minus or one == n*m :
print(0)
exit()
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
q.append((i,j))
def not_all():
all = False
for i in range(n):
for j in range(m):
if graph[i][j] == 0 and check[i][j]== False:
all=True
return all
while q:
x,y=q.popleft()
for i in range(4):
nx,ny = x+dx[i],y+dy[i]
if 0<=nx<n and 0<=ny<m:
if graph[nx][ny] == 0 and check[nx][ny] == False:
q.append((nx,ny))
check[nx][ny] = True
dist[nx][ny] = dist[x][y]+1
ans.append(dist[nx][ny])
if not_all():
print(-1)
else:
print(ans[-1])<file_sep>from collections import Counter
from itertools import combinations
def solution(orders, course):
answer = []
for c in course:
temp=[]
for order in orders:
combi = list(combinations(sorted(order),c))
temp+=combi
counter=Counter(temp)
if len(counter) != 0 and max(counter.values()) != 1:
answer += [''.join(f) for f in counter if counter[f] == max(counter.values())]
return sorted(answer)<file_sep>from itertools import combinations_with_replacement
def solution(n, info):
answer=[-1]
max_dif=-1
#0~10까지의 점수들을 n번 나오도록 중복 조합 구하기
for combi in list(combinations_with_replacement(range(11),n)):
ryan=[0]*11
rsum=0
asum=0
#점수 배열의 0번째가 10을 뜻하므로
for i in combi:
ryan[10 - i] += 1
for i,(a,r) in enumerate(zip(info,ryan)):
if a==r==0:
continue
elif a>=r:
asum+=(10-i)
else:
rsum+=(10-i)
if rsum>asum:
dif=rsum-asum
#낮은 점수들을 먼저 채워줘서 max_dif을 갱신하도록 만듦
#동일한 max_dif을 가진 비교적 높은 점수들의 조합들이 아래의 조건문을 타지 않기때문에
#조건에 맞게 답이 추출될 수 있음.(라이언이 가장 큰 점수 차이로 우승할 수 있는 방법이 여러 가지 일 경우, 가장 낮은 점수를 더 많이 맞힌 경우를 return 해주세요.)
if dif>max_dif:
max_dif=dif
answer=ryan
return answer
print(solution(10,[0,0,0,0,0,0,0,0,3,4,3]))<file_sep>num= int(input())
a= input().split()
b=[]
for i in range(0,len(a)):
b.append(int(a[i]))
b.sort()
print(b[0])<file_sep>from collections import deque
def solution(priorities, location):
turn =deque()
prin=1
queue=deque()
for i,prior in enumerate(priorities):
queue.append(prior)
turn.append(i)
while queue:
if queue[0] < max(queue):
queue.append(queue.popleft())
turn.append(turn.popleft())
else:
t=turn.popleft()
queue.popleft()
if t == location:
return prin
prin += 1<file_sep>import collections
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words = [word for word in re.sub('[^a-zA-Z0-9]',' ',paragraph).lower().split() if word not in banned]
most = collections.Counter(words).most_common()
return (most[0][0])
<file_sep>a= int(input())
print(format(a,'o'))
#접두어 제거
<file_sep>from collections import deque
n,m,k=map(int,input().split())
arr=[list(map(int,input())) for _ in range(n)]
visited=[[[0]*(k+1) for j in range(m)] for i in range(n)]
dx=[-1,1,0,0]
dy=[0,0,1,-1]
q=deque()
q.append((0,0,k,1))
visited[0][0][k]=1
day=True
def dfs():
global day
while q:
x,y,z,d=q.popleft()
if x==n-1 and y==m-1:
return d
for i in range(4):
nx,ny,nd=x+dx[i],y+dy[i],d+1
if 0<=nx<n and 0<=ny<m:
#낮/밤과 상관없이 빈칸 -> 빈칸으로 이동할 때
if visited[nx][ny][z] == 0 and arr[nx][ny] == 0:
visited[nx][ny][z]=True
q.append((nx,ny,z,nd))
#다음이 벽일 때
if z>0 and arr[nx][ny] == 1 and visited[nx][ny][z-1] == 0:
#현재 낮이라서 벽을 부술 수 있을 때
if day:
visited[nx][ny][z-1]=True
q.append((nx,ny,z-1,nd))
#현재 밤이라서 벽을 부술 수 없고, 하루 기다렸다가 벽을 부숴야할 때
else:
q.append((x,y,z,nd))
day=not day
return -1
print(dfs())<file_sep>ans = []
import sys
input = sys.stdin.readline
def go(do,item):
global ans
if do == 'add':
if item not in ans:
ans.append(item)
elif do == 'remove':
if item in ans:
ans.remove(item)
elif do == 'check':
if item in ans:
print(1)
else:
print(0)
elif do == 'toggle':
if item in ans:
ans.remove(item)
else:
ans.append(item)
elif do == 'all':
ans = [i for i in range(1,21)]
else:
ans=[]
n=int(input())
for i in range(n):
s = input().strip()
if s == 'all' or s == 'empty':
go(s,0)
continue
s = s.split()
go(s[0],int(s[1]))
<file_sep>puzzle = []
number=[1,2,3,4,5,6,7,8,9]
check_row=[[False for _ in range(10)] for _ in range(9)] #행은 무슨 행인지/ 열은 1-9까지의 숫자
check_col=[[False for _ in range(10)] for _ in range(9)]
check_checker=[[False for _ in range(10)] for _ in range(9)]
checker_pos=[(0,0),(0,3),(0,6),(3,0),(3,3),(3,6),(6,0),(6,3),(6,6)]
where=[]
for i in range(9):
row_puzzle=list(map(int,input().split()))
puzzle.append(row_puzzle)
for r in range(9):
num=row_puzzle[r]
if num:
check_row[i][num]=True
else:
where.append((i,r))
for i in range(9):
for c in range(9):
num=puzzle[c][i]
if num:
check_col[i][num] = True #puzzle[c][i]란 해당 열의 숫자
for turn,pos in enumerate(checker_pos):
x,y=pos
for i in range(3):
for j in range(3):
num=puzzle[i+x][j+y]
if num:
check_checker[turn][num]=True
def check(num,row,col,checker):
if check_row[row][num]: #row 행에 해당 num이 있는지
return False
if check_checker[checker][num]: #해당 체커 번호에 그 숫자가 있는지
return False
if check_col[col][num]: #해당 열에 그 숫자가 있는지
return False
return True
def sdoku(idx):
if idx == len(where):
for i in range(9):
print(*puzzle[i])
exit(0)
row,col=where[idx]
checker = (row//3)*3+(col//3)
for i in range(1,10):
if check(i,row,col,checker):
check_row[row][i]=True
check_checker[checker][i]=True
check_col[col][i]=True
puzzle[row][col] = i
sdoku(idx+1)
#해당 칸에 현재 숫자가 들어가지 못할 시에 리턴됨. 그럼 이전 함수에서 넣을 수 있는 다음 숫자를 넣어보게 되고, 그게 또 된다면 idx+1 하고 다시
#안된다면 계속 리턴되며 되는 값을 찾을 때까지 재귀
#그렇기 때문에 리스트에 다시 해당 칸의 정보를 append 하면 안됨. -> 무한 루프
print(idx, [row, col],i)
check_row[row][i]=False
check_checker[checker][i]=False
check_col[col][i]=False
puzzle[row][col] = 0
sdoku(0)
<file_sep>def binary_search(arr,target,start,end):
if start>end:
return 'no'
mid=(start+end)//2
if arr[mid] == target:
return 'yes'
elif arr[mid] > target:
return binary_search(arr,target,start,mid-1)
else:
return binary_search(arr,target,mid+1,end)
n=int(input())
arr1=list(map(int,input().split()))
m=int(input())
arr2=list(map(int,input().split()))
answer=[]
for arr in arr2:
answer.append(binary_search(arr1,arr,0,n-1))
print(answer,end=' ')
<file_sep>n=int(input())
ans=0
for i in range(1,n+1):
ans+=i*(n//i)
print(ans)
#약수의 합 ex)10
# 1
# 1 2
# 1 3
# 1 2 4
# 1 5
# 1 2 3 6
# 1 7
# 1 2 4 8
# 1 3 9
# 1 2 5 10
#10까지의 모든 수의 약수의 합을 구하는 것이라고 가정했을 때,
#(1*10)+(2*5)+(3*3) ... 의 규칙이 발견됨<file_sep>import heapq
def solution(jobs):
heap = []
answer, now, i = 0, 0, 0
finished = -1
while i < len(jobs):
for job in jobs:
if finished < job[0] <= now:
heapq.heappush(heap, (job[1], job[0])) # 소요시간, 시작시간
if len(heap) > 0:
current = heapq.heappop(heap)
finished = now
now += current[0]
answer += (now - current[1])
i += 1
else:
now += 1 #현재 heap에 없다는 것 == 현재 실행할 수 있는 작업이 없다는 것 == 남아있는 작업들의 요청 시간이 아직 오지 않은 것
return answer // len(jobs)<file_sep>class Solution:
def maxProfit(self, prices: List[int]) -> int:
ans=0
for i in range(1,len(prices)):
if prices[i]>prices[i-1]:
ans+=prices[i]-prices[i-1]
return ans
class Solution:
def maxProfit(self, prices: List[int]) -> int:
return sum(max(prices[i+1]-prices[i],0) for i in range(len(prices)-1))
#0보다 크면 무조건 합산<file_sep>SELECT a.CART_ID
FROM
(SELECT CART_ID,name
FROM CART_PRODUCTS
WHERE NAME ='Milk') as a join
(SELECT CART_ID,name
FROM CART_PRODUCTS
WHERE NAME ='yogurt')as b
ON a.CART_ID = b.CART_ID
GROUP BY a.CART_ID
ORDER BY a.CART_ID
<file_sep>a,b=map(int,input().split(" "))
res = a/b
print("%d" % res)
<file_sep>class Solution:
def dfs(self, grid: List[List[str]],i:int,j:int,visited) -> int:
n=len(grid)
m=len(grid[0])
if 0 <= i < n and 0<= j < m:
if visited[i][j]:
return False
if grid[i][j] == '1':
visited[i][j]=True
self.dfs(grid,i+1,j,visited)
self.dfs(grid,i-1,j,visited)
self.dfs(grid,i,j+1,visited)
self.dfs(grid,i,j-1,visited)
return True
def numIslands(self, grid: List[List[str]]) -> int:
n=len(grid)
m=len(grid[0])
visited=[[False] * m for _ in range(n)]
ans =0
for i in range(n):
for j in range(m):
if self.dfs(grid,i,j,visited):
ans += 1
return ans<file_sep>n,m=map(int,input().split())
arr=[]
chic_list=[] #치킨 집 별로 치킨 거리의 합이 있는 거임.
least=999999
this=[]
for i in range(n):
a=list(map(int,input().split()))
arr.append(a)
for j in range(n):
if a[j] == 2:
chic_list.append((i,j))
visited=[0]*len(chic_list)
def bfs(start,cnt):
global least
global visited
if cnt == m:
all=0
for i in range(n):
for j in range(n):
minn = 9999999
if arr[i][j] == 1:
for x, y in this:
dif = abs(i - x) + abs(j - y)
minn = min(dif, minn)
all+=minn
least=min(all,least)
return
for i in range(start,len(chic_list)):
if not visited[i]:
visited[i]=True
this.append(chic_list[i])
cnt+=1
bfs(i+1,cnt)
visited[i]=False
this.pop()
cnt-=1
bfs(0,0)
print(least)<file_sep>h,m = input().split(":")
print(h+":"+m)<file_sep>a=input()
cro = ["c=","c-","dz=","d-","lj","nj","s=","z=" ]
for i in cro:
a=a.replace(i,'*')
print(len(a))<file_sep>n,m,t=map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(n)]
temp=[[0]*m for _ in range(n)]
#동 북 서 남
dx=[0,-1,0,1]
dy=[1,0,-1,0]
#공기청정기 위치 x,y에 넣어주기
for i in range(n):
for j in range(m):
if arr[i][j] == -1:
x,y=i,j
x-=1 #위쪽 공기청정기 기준으로
def go(sx,sy,z):
prev=0
x,y=sx,sy+1
k=0
while True:
if x == sx and y == sy: #다 돌고 나서 처음으로 돌아오게 되면
break
prev,arr[x][y]=arr[x][y],prev
x+=dx[k]
y+=dy[k]
if x<0 or y<0 or x>=n or y>=m:
x-=dx[k]
y-=dy[k]
k+=z
k%=4
x += dx[k]
y += dy[k]
for _ in range(t):
for i in range(n):
for j in range(m):
if arr[i][j]>0:
cnt = 0
val = arr[i][j] // 5
for k in range(4):
nx = i + dx[k]
ny = j + dy[k]
if 0 <= nx < n and 0 <= ny < m and arr[nx][ny] >= 0:
cnt += 1
temp[nx][ny] += val
if cnt > 0:
arr[i][j] = arr[i][j] - cnt * val
for i in range(n):
for j in range(m):
if arr[i][j] != -1:
arr[i][j] += temp[i][j]
temp[i][j]=0
go(x,y,1)
go(x+1,y,3)
ans=0
for i in range(n):
for j in range(m):
if arr[i][j]>=0:
ans+=arr[i][j]
print(ans)
<file_sep>n=int(input())
arr=[[0]*10 for _ in range(10)]
score=0
def check_green(arr):
l=[]
temp=[[0]*4 for _ in range(10)]
global score
for i in range(4,10):
if sum(arr[i])==4:
score+=1
l.append(i)
for row in l:
for i in range(6,row):
temp[i+1]=arr[i]
return l
def check_blue(arr):
l=[]
temp=[[0]*4 for _ in range(10)]
global score
for j in range(4,10):
if s==4:
score+=1
l.append(j)
s=0
for i in range(0,4):
s+=arr[i][j]
for col in l:
for j in range(6,col):
for i in range(4):
temp[i][j+1]=arr[i][j]
for i in range(4):
for j in range(6,col):
arr[i][j]=temp[i][j]
return l
def deadzone_green(arr):
cnt=0
ss=0
temp=[[0]*4 for _ in range(10)]
for i in range(2):
if sum(arr[i]) != 0:
cnt+=1
arr[i]=[0,0,0,0]
for i in range(6,10-cnt):
for j in range(4):
if arr[i][j] == 1:
if i+1<9:
temp[i+1][j] = 1
for i in range(6,10):
for j in range(4):
arr[i][j]=temp[i][j]
return
def deadzone_blue(arr):
cnt=0
temp=[[0]*4 for _ in range(10)]
ss=0
for j in range(2):
if ss != 0:
cnt+=1
for i in range(4):
arr[i][j]=0
ss=0
for i in range(4):
ss+=arr[i][j]
for j in range(6,10-cnt):
for i in range(4):
if arr[i][j] == 1:
if j+1<9:
temp[i][j+1]=1
for i in range(4):
for j in range(6,10):
arr[i][j]=temp[i][j]
return
for i in range(n):
t,x,y=map(int,input().split())
if t == 1:
arr[x][y] = 1
for j in range(9, x, -1): #초록이
if arr[j][y] == 0:
arr[x][y] = 0
arr[j][y] = 1
break
for j in range(9,y,-1): #파랑이
if arr[x][j] ==0:
arr[x][j]=1
arr[x][y]=0
break
elif t == 2: #옆으로
arr[x][y],arr[x][y+1]=1,1
for j in range(9, x, -1): # 초록이
if arr[j][y] == 0 and arr[j][y+1] == 0:
arr[x][y],arr[x][y+1] = 0,0
arr[j][y],arr[j][y + 1] = 1,1
break
for j in range(8,y,-1): #파랑이
if arr[x][j] == 0 and arr[x][j+1]==0:
arr[x][j],arr[x][j+1] = 1,1
arr[x][y],arr[x][y+1] =0, 0
break
else:
arr[x][y], arr[x+1][y] = 1, 1
for j in range(8, x, -1): # 초록이
if arr[j][y] == 0 and arr[j+1][y] == 0:
arr[x][y],arr[x+1][y] = 0,0
arr[j][y],arr[j+1][y] = 1,1
break
for j in range(9,y,-1): #파랑이
if arr[x][j] == 0 and arr[x+1][j]==0:
arr[x][j],arr[x+1][j] = 1,1
arr[x][y],arr[x+1][y] =0, 0
break
deadzone_blue(arr)
deadzone_green(arr)
cg=check_green(arr)
cb=check_blue(arr)
#연한 라인에 블록 있는지 확인
#초록이
# if sum(arr[0])
#초록이 한 줄 다 채워졌는지 chk 사라진 행을 return 해야함
#파랑이 한 열 다 채워졌는지 chk 한칸 지워지면 사라진 열을 return해야함
print(*arr,sep='\n')
print()
#빨간색 부분 -> 3까지 / 초록 행 4~9 열 0~3 / 파랑 행 0~3 열 4~9
<file_sep>from collections import deque
n = int(input())
dist = [[-1]* (n+1) for _ in range(n+1)]
q = deque()
q.append((1,0)) # 화면 이모티콘 개수, 클립보드 이모티콘 개수
dist[1][0] = 0
while q:
x,c = q.popleft()
#화면에 있는 x개의 이모티콘을 클립보드에 붙이는 경우
if dist[x][x] == -1: # 방문하지 않았으면 이미 붙여넣었다고 가정하고 방문 확인
dist[x][x] = dist[x][c] + 1
q.append((x,x))
#클립보드에 있는 c개의 이모티콘을 화면에 붙이는 경우
if x+c <= n and dist[x+c][c] == -1:
dist[x+c][c] = dist[x][c] + 1
q.append((x+c, c))
#화면에 있는 이모티콘을 하나 삭제하는 경우
if x-1 >= 0 and dist[x-1][c] == -1:
dist[x-1][c] = dist[x][c] + 1
q.append((x-1, c))
answer = -1
for i in range(n+1):
if dist[n][i] != -1:
if answer == -1 or answer > dist[n][i]: #최솟값 찾는 과정
answer = dist[n][i]
print(answer)<file_sep>class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
ans=[]
stack=[]
def dfs(start):
if stack not in ans:
ans.append(stack[:])
for i in range(start,len(nums)):
stack.append(nums[i])
dfs(i+1)
stack.pop()
for i in range(len(nums)):
dfs(i)
return ans<file_sep>data = [1, 1, 0, 0, 0, 1]
print([i for i, value in enumerate(data) if value == 1])<file_sep>from collections import deque,defaultdict
s,e=map(int,input().split())
dist=[0]*(10**5+1)
path=defaultdict(list)
def bfs():
global path
q = deque()
q.append(s)
path[s]=[]
while q:
x = q.popleft()
if x == e:
return
for nx in [x+1,x-1,x*2]:
if 0<=nx<= 10**5 and not dist[nx]:
q.append(nx)
dist[nx]=dist[x]+1
path[nx].append(x)
bfs()
now=e
way=[]
while now!=s:
way.append(now)
now = path[now][0]
way.append(s)
print(dist[e])
print(*reversed(way),end=' ')<file_sep>n=int(input())
g=[[0]*n for _ in range(n)]
#세로 상승 가로 하강
dx=[1,-1,0,1]
dy=[0,1,1,-1]
x=y=0
score=1
g[x][y] = score
for _ in range(n-1):
for i in range(4):
if i == 0:
score+=1
if 0<=x+dx[0]<n and 0<=y+dy[0]<n: #넘어가지 않으면 그대로 세로
x=x+dx[0]
y=y+dy[0]
g[x][y]=score
else:
x=x+dx[2]
y=y+dy[2]
g[x][y]=score
elif i==1:
while 0<=x+dx[1]<n and 0<=y+dy[1]<n:
score+=1
x=x+dx[1]
y=y+dy[1]
g[x][y]=score
elif i==2:
score += 1
if 0 <= x + dx[2] < n and 0 <= y + dy[2] < n: # 넘어가지 않으면 그대로 세로
x = x + dx[2]
y = y + dy[2]
g[x][y] = score
else:
x = x + dx[0]
y = y + dy[0]
g[x][y] = score
else:
while 0 <= x + dx[3] < n and 0 <= y + dy[3] < n:
score += 1
x = x + dx[3]
y = y + dy[3]
g[x][y] = score
print(*g,sep="\n")<file_sep>SELECT INS.ANIMAL_ID, INS.NAME
FROM ANIMAL_INS AS INS LEFT OUTER JOIN ANIMAL_OUTS AS OUTS
ON INS.ANIMAL_ID = OUTS.ANIMAL_ID
WHERE INS.DATETIME > OUTS.DATETIME
ORDER BY INS.DATETIME<file_sep>from collections import defaultdict
import heapq #튜플의 첫번째 원소를 기준으로 정렬함
def solution(times,k,n):
graph=defaultdict(list)
#그래프 인접 리스트 구성
for u,v,w in times:
graph[u].append((v,w))
#큐 변수 : [(소요시간, 정점)]
Q=[(0,k)]
dist=defaultdict(int)
#우선순위 큐 최솟값 기준으로 정점까지 최단 경로 삽입
while Q:
time,node = heapq.heappop(Q)
if node not in dist: #heapq때문에 항상 최솟값부터 셋팅되기 때문에 이미 값이 존재한다면 그 값은 이미 최단 경로임.
dist[node]=time
for v,w in graph[node]:
alt=time+w
heapq.heappush(Q,(alt,v))
if len(dist)==n:
return max(dist.values())
return -1
<file_sep>a=int(input())
print(a,a,a) #,은 공백으로 연속 출력됨
#print(a +" " +a +" "+a) -> a를 str화 해줘야함
<file_sep>num_list=list(map(int,input().split()))
i=0
while 1:
if(num_list[i]==0): break
print(num_list[i])
i+=1
<file_sep># while True:
# arr=list(map(int,input().split()))
# #k, *k_List = map(int, input().split())
# if arr[0] == 0:
# break
# n=arr.pop(0)
# stack=[]
# def lottery(elements,start):
# if len(stack) == 6:
# print(*stack)
#
# for i in range(start,n):
# stack.append(elements[i])
# lottery(elements,i+1)
# stack.pop()
# lottery(arr,0)
# print()
def solve(a,index,lotto):
if len(lotto) == 6:
print(' '.join(map(str,lotto)))
return
if index == len(a):
return
solve(a,index+1,lotto+[a[index]]) #배열에 +로 추가가 가능하다.
#리턴 되고 나서 이전 값으로 복원해야하기 때문에 아래 코드 추가
solve(a,index+1,lotto)
while True:
n, *a = list(map(int,input().split())) # 오름차순으로 정리되어있기 때문에 가능
if n == 0: # 갯수가 0일 경우 예외처리
break
solve(a,0,[])
print()<file_sep>n=int(input())
arr=[]
for i in range(n):
arr.append(list(input().split()))
arr.sort(key=lambda x: (-int(x[1]),int(x[2]),-int(x[3]),x[0]))
for i in arr:
print(i[0])<file_sep>def solution(N, stages):
stages.sort()
answer={}
num=len(stages)
for i in range(1,N+1):
num-=stages.count(i-1)
if stages.count(i) !=0:
answer[i]=stages.count(i)/num
else:
answer[i]=0
return answer
<file_sep>def check(i, n):
if (i + 1) % n == 0:
turn = (i + 1) // n
else:
turn = (i + 1) // n + 1
if (i + 1) % n != 0:
num = (i + 1) % n
else:
num = n
return num, turn
def solution(n, words):
for i in range(1,len(words)):
if words[i] in words[:i]:
return check(i, n)
if i != len(words) - 1 and words[i][-1] != words[i + 1][0]: # 앞에 끝이랑 뒤에 앞이랑 다르면
return check(i + 1, n) # 번호 , 차례
return [0, 0]
#한꺼번에 처리해 주어야함.
#남의 풀이
def solution(n, words):
for p in range(1, len(words)):
if words[p][0] != words[p-1][-1] or words[p] in words[:p]: return [(p%n)+1, (p//n)+1]
else:
return [0,0]
#일단 앞에 있는건지 확인하는거는 0부터 할 필요가 없기 때문에 1부터 시작해도 상관이 없다.
#뿐만 아니라 순서상 2부터 확인을 시작하기 때문에 위에 check 함수처럼 나누어서 check할 필요도 없다.
<file_sep>#include<iostream>
using namespace std;
int main() {
int t,w,h,n;
cin >> t;
for (int test=0; test < t; test++) {
cin >> h >> w >> n;
for (int wid = 0; wid < w; wid++) {
for (int hig = h - 1; hig >= 0; hig--) {
n--;
if (n == 0) {
cout<<((h-hig)*100)+wid+1<<endl;
}
}
}
}
}<file_sep>def solution(m, musicinfos):
m=m.replace("C#", "c").replace("D#", "d").replace("F#", "f").replace("G#", "g").replace("A#", "a")
answer = ('(None)', None)
for info in musicinfos:
l=info.split(',')
start,end,name,code=l
sh,sm,eh,em=map(int,start.split(':')+end.split(':'))
time=(eh-sh)*60+(em-sm)
code = code.replace("C#", "c").replace("D#", "d").replace("F#", "f").replace("G#", "g").replace("A#", "a")
melody_played = (code*time)[:time]
if m in melody_played:
if (answer[1] == None) or (time > answer[1]):
answer = (name, time)
return answer[0]<file_sep>a= int(input())
print(format(a,'x').upper())<file_sep>import re
from itertools import permutations
def solution(expression):
#1
op = [x for x in ['*','+','-'] if x in expression]
op = [list(y) for y in permutations(op)]
ex = re.split(r'(\D)',expression) #숫자가 아닌 것으로 split
#2
a = []
for x in op:
_ex = ex[:]
for y in x:
while y in _ex: #while을 이렇게 사용할 수 있다니..!
tmp = _ex.index(y)
_ex[tmp-1] = str(eval(_ex[tmp-1]+_ex[tmp]+_ex[tmp+1]))
_ex = _ex[:tmp]+_ex[tmp+2:]
a.append(_ex[-1])
#3
return max(abs(int(x)) for x in a)<file_sep>n=int(input())
i=0
a=2
b=1
while True:
if n==1:
print(1)
break
a=a+(6*i)
b=b+(6*(i+1))
if a<=n<=b:
print(i+2)
break
i+=1<file_sep>from collections import deque
n,m=map(int,input().split())
wall=[]
dx=[1,-1,0,0]
dy=[0,0,1,-1]
arr=[list(map(int,input())) for _ in range(n)]
group=[[0 for _ in range(m)] for _ in range(n)]
visited=[[False for _ in range(m)] for _ in range(n)]
def possible(x,y):
arr[x][y]=0
all_group=set()
ans=1
for i in range(4):
nx,ny=x+dx[i],y+dy[i]
if 0<=nx<n and 0<=ny<m and not arr[nx][ny]:
if not group[nx][ny]: continue
all_group.add(group[nx][ny])
for gg in all_group:
ans+=info[gg]
ans%=10
return ans
def bfs(x,y,g):
q = deque()
q.append((x,y))
visited[x][y] = True
cnt=1
while q:
x,y=q.popleft()
group[x][y] = g
for i in range(4):
nx,ny=x+dx[i],y+dy[i]
if 0<=nx<n and 0<=ny<m and not visited[nx][ny]:
if arr[nx][ny] == 0:
q.append((nx,ny))
visited[nx][ny]=True
cnt+=1
return cnt
g=1
info={}
for i in range(n):
for j in range(m):
if not arr[i][j] and not visited[i][j]:
count=bfs(i,j,g)
info[g]=count
g+=1
for i in range(n):
for j in range(m):
if arr[i][j]:
arr[i][j]=possible(i,j)
for i in range(n):
print(''.join(map(str, arr[i])))
<file_sep>class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans=[]
def dfs(start: int,k:int,elements):
if k==0:
ans.append(elements[:])
for i in range(start,n+1):
elements.append(i)
dfs(i+1,k-1,elements)
elements.pop()
dfs(1,k,[])
return ans<file_sep>list = []
for i in range(20):
list.append([])
for j in range(20):
list[i].append(0)
for i in range(19):
a= input().split()
for j in range(19):
list[i+1][j+1]= int(a[j])
n= int(input())
for i in range(n):
a,b=map(int,input().split())
for j in range(1,20):
if(list[a][j]==1) : list[a][j]=0
else: list[a][j]=1
for k in range(1,20):
if(list[k][b]==1): list[k][b]=0
else : list[k][b]=1
for i in range(1,20):
for j in range(1,20):
print(list[i][j],end=' ')
print()<file_sep>from collections import deque
s,e=map(int,input().split())
dist=[-1]*(10**5+1)
dist[s]=0
def bfs():
q = deque()
q.append(s)
while q:
x = q.popleft()
if x == e:
print(dist[x])
return
for nx in [x*2,x+1,x-1]:
if 0<=nx<= 10**5 and dist[nx] == -1:
if nx == x*2:
q.appendleft(nx)
dist[nx] = dist[x]
else:
q.append(nx)
dist[nx]=dist[x]+1
bfs()<file_sep>from collections import deque
s,e=map(int,input().split())
dist=[0]*(10**5+1)
def bfs():
q = deque()
q.append(s)
while q:
x = q.popleft()
if x == e:
print(dist[x])
return
for nx in [x+1,x-1,x*2]:
if 0<=nx<= 10**5 and not dist[nx]:
q.append(nx)
dist[nx]=dist[x]+1
bfs()
<file_sep># 다음과 같이 import를 사용할 수 있습니다.
# import math
# 슬라이딩 윈도우
def solution(arr, K):
arr.sort()
ans=10000
for i in range(len(arr)-K+1):
ans=min(ans,arr[i+K-1]-arr[i])
return ans
# 아래는 테스트케이스 출력을 해보기 위한 코드입니다.
arr = [9, 11, 9, 6, 4, 19]
K = 4
ret = solution(arr, K)
# 자연수가 들어있는 리스트에서 숫자 K개를 선택하려 합니다. 이때, 선택한 숫자 중 가장 큰 수와 가장 작은 수의 차이가 최소가 되도록 해야합니다.
# 예를 들어 리스트에 들어있는 숫자가 [9, 11, 9, 6, 4, 19] 이고, K = 4 라면
# 숫자 4개를 [9, 11, 9, 6]로 뽑으면 (가장 큰 수 - 가장 작은 수) = (11 - 6) = 5가 됩니다.
# [9, 9, 6, 4] 와 같이 숫자를 뽑아도 (가장 큰 수 - 가장 작은 수) = (9 - 4) = 5가 됩니다.
# 그러나 가장 큰 수와 가장 작은 수의 차이가 5보다 작아지도록 숫자 4개를 선택하는 방법은 없습니다.
# 자연수가 들어있는 리스트 arr, 선택해야 하는 숫자 개수 K가 매개변수로 주어질 때, 선택한 숫자중 가장 큰 수와 가장 작은 수의 차이가 최소가 되록 arr에서 숫자 K개를 선택했을 때, 그때의 가장 큰 수와 가장 작은 수의 차이를 return 하도록 solution 함수를 완성해주세요.
|
eab375f33e071b2a70bbf3e2c5d03e262d87de21
|
[
"Java",
"SQL",
"Python",
"C++"
] | 240 |
Python
|
jihyun12/Algorithm_study
|
c925670949eec8d48dc002fc718ab2aff2617087
|
0d89c41dbfc321d87174156963c623adc91c9efd
|
refs/heads/main
|
<repo_name>sgkl/zhiliao<file_sep>/src/main.rs
use clap::{Arg, App};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches: App = App::new("zl")
.version("0.1.0")
.author("sgk <<EMAIL>>")
.about("知了客户端")
.subcommand(
App::new("article")
.about("文章")
)
.subcommand(
App::new("articles")
.about("文章列表")
)
.subcommand(
App::new("books")
.about("列出本地已下载书籍")
)
.subcommand(
App::new("book")
.about("书籍")
.subcommand(
App::new("list")
.about("list local books")
)
.subcommand(
App::new("delete")
.about("delete book")
.arg("<book> 'book'")
)
)
.subcommand(
App::new("note")
.about("笔记")
)
.subcommand(
App::new("notes")
.about("列出笔记")
);
matches.get_matches();
println!("Hello, world!");
Ok(())
}
<file_sep>/README.md
# zhiliao
知了
<file_sep>/Cargo.toml
[package]
name = "zhiliao"
version = "0.1.0"
authors = ["sunguanke"]
edition = "2018"
[[bin]]
name = "zl"
path = "src/main.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = "3.0.0-beta.2"
console = "0.14.1"
tokio = { version = "1", features = ["full"] }
|
82a44253ca088ae888023be7186bd72fca194850
|
[
"Markdown",
"Rust",
"TOML"
] | 3 |
Rust
|
sgkl/zhiliao
|
a9bca2b856d4bdaa9f7ef1c518c920a039ef8b67
|
2ceea7e61e6ee8a8d478079d0adcbdc06b1308ea
|
refs/heads/master
|
<repo_name>hsl-rd/hsl-open-php<file_sep>/demo5.php
<?php
/**
* POS订单推送
*/
require_once './vendor/autoload.php'; // 加载自动加载文件
//require './config.php';
use Hsl\Open\Open;
const BRAND_ID = '161616';
const SHOP_ID = '123456';
const APP_ID = '0217d3da-5347-4ec7';
$hslOpen = new Open(APP_ID, './private.pem', './public.pem', true);
$tradeId = '161001422' . time(); // 订单ID
var_dump($hslOpen->postOrderInfo(SHOP_ID, BRAND_ID, $tradeId, 1, '小程序', 'A004', 1));<file_sep>/demo.php
<?php
/**
* 设置推送url的demo
*/
require_once './vendor/autoload.php'; // 加载自动加载文件
require './config.php';
use Hsl\Open\Open;
$hslOpen = new Open(APP_ID, './private.pem', './public.pem', true);
// 设置推送地址
$host = 'https://newapi.hesiling.com';
$path = '/test/path';
$brandId = BRAND_ID;
var_dump($hslOpen->setPushUrl($host, $path, $brandId));
<file_sep>/README.md
### 盒司令开放平台PHP版本SDK
```
composer require hsl/open dev-master -vvv
```
```
具体使用详情 demo.php demo1.php demo2.php
```<file_sep>/demo6.php
<?php
/**
* 获取等餐时长
*/
require_once './vendor/autoload.php'; // 加载自动加载文件
require './config.php';
use Hsl\Open\Open;
$hslOpen = new Open(APP_ID, './private.pem', './public.pem', true);
// 设置推送地址
$brandId = BRAND_ID;
$res = $hslOpen->getOrderWaitTime(SHOP_ID, BRAND_ID);
var_dump($res);
//var_dump($hslOpen->postOrder([
// 'shopId' => SHOP_ID,
// 'brandId' => $brandId,
// 'tradeId' => time(),
// 'channel' => 11,
// 'channelDesc' => '小程序',
// 'pickUpCode' => time(),
// 'productStatus' => 1,
// 'timestamp' => time(),
// 'appId' => APP_ID
//]));
<file_sep>/demo1.php
<?php
/**
* 查询订单详情
*/
require_once './vendor/autoload.php'; // 加载自动加载文件
require './config.php';
use Hsl\Open\Open;
$hslOpen = new Open(APP_ID, './private.pem', './public.pem', true);
// 设置推送地址
$shopId = SHOP_ID; // 门店编号
$brandId = BRAND_ID; // 品牌编号
$tradeId = '101101010101'; // 订单ID
var_dump($hslOpen->getOrderInfo($shopId, $brandId, $tradeId));
<file_sep>/config.php
<?php
CONST BRAND_ID= '161616';
CONST SHOP_ID= '123456';
CONST APP_ID= '53113a58-1406-4078';
<file_sep>/demo2.php
<?php
header('Content-Type:application/json; charset=utf-8');
/**
* 接受推送,验证流程
*/
require_once './vendor/autoload.php'; // 加载自动加载文件
$postData = file_get_contents("php://input");
$postData = json_decode($postData, true);
$headers = getAllHeaders();
$token = $headers['Access-Token'] ?? '';
$messageUuid = $headers['Messageuuid'] ?? '';
use Hsl\Open\Open;
$hslOpen = new Open(APP_ID, './private.pem', './public.pem', true);
// 判断接口加密是否正确
// var_dump($hslOpen->checkPostRsa($postData, $token));
// .. 执行下面流程
// 返回结果
file_put_contents('./a.log', $messageUuid . 'status:' . $hslOpen->checkPostRsa($postData, $token));
exit(json_encode([
'code' => 200,
'message' => 'OK',
'messageUuid' => $messageUuid
]));
/**
* 获取请求头数据
* @return array
*/
function getAllHeaders()
{
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
<file_sep>/src/Hsl/Open/Rsa.php
<?php
namespace Hsl\Open;
class Rsa
{
/**
* 获取公钥
* @param $publicKeyPath
* @return false|resource
*/
private static function getPublicKey($publicKeyPath)
{
$content = file_get_contents($publicKeyPath);
return openssl_pkey_get_public($content);
}
/**
* 公钥加密
* @param $data
* @param $publicKeyPath
* @return string|null
*/
public function publicEncrypt($data, $publicKeyPath)
{
if (!is_string($data)) {
return null;
}
return openssl_public_encrypt($data, $encrypted, self::getPublicKey($publicKeyPath), OPENSSL_PKCS1_PADDING) ? base64_encode($encrypted) : null;
}
/**
* 获取私钥
* @param $PrivatePath
* @return false|resource
*/
private static function getPrivateKey($PrivatePath)
{
$content = file_get_contents($PrivatePath);
return openssl_pkey_get_private($content);
}
/**
* 私钥解密
* @param $encrypted
* @param $PrivatePath
* @return mixed|null
*/
public static function privateDecrypt($encrypted, $PrivatePath)
{
if (!is_string($encrypted)) {
return null;
}
return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey($PrivatePath))) ? $decrypted : null;
}
}<file_sep>/src/Hsl/Open/Open.php
<?php
namespace Hsl\Open;
class Open
{
private $appId;
private $privateKey;
private $publicKey;
private $urlPrefix;
public function __construct($appId, $privateKey, $publicKey, $debug)
{
$this->appId = $appId;
$this->publicKey = $publicKey;
$this->privateKey = $privateKey;
$this->urlPrefix = $debug ? 'https://csapi.hesiling.com' : 'https://api.hesiling.com';
}
public function postOrder($params)
{
$hslPath = '/api/open/v4/kds/newOrder';
$data = $params;
return $this->post($data, $this->urlPrefix . $hslPath, $this->getAccessToken($data));
}
/**
* @param $shopId
* @param $brandId
* @param $tradeId
* @param $posChannel
* @return bool|string
*/
public function getOrderWaitTime($shopId, $brandId, $tradeId = null, $posChannel = null) {
$hslPath = '/api/open/v4/kds/queueNumberV2';
$data = [
'appId' => $this->appId,
'shopId' => $shopId,
'brandId' => $brandId,
'tradeId' => $tradeId,
'posChannel' => $posChannel,
];
return $this->post($data, $this->urlPrefix . $hslPath, $this->getAccessToken($data));
}
/**
* 设置推送地址
* @param $host
* @param $path
* @param $brandId
* @return bool|string
*/
public function setPushUrl($host, $path, $brandId)
{
$hslPath = '/api/open/v4/kds/setPush';
$data = [
'appId' => $this->appId,
'brandId' => $brandId,
'host' => $host,
'path' => $path,
];
return $this->post($data, $this->urlPrefix . $hslPath, $this->getAccessToken($data));
}
/**
* 获取订单详情
* @param $shopId
* @param $brandId
* @param $tradeId
* @return bool|string
*/
public function getOrderInfo($shopId, $brandId, $tradeId)
{
$hslPath = '/api/open/v4/kds/queryOrders';
$data = [
'appId' => $this->appId,
'shopId' => $shopId,
'brandId' => $brandId,
'tradeId' => $tradeId,
];
return $this->post($data, $this->urlPrefix . $hslPath, $this->getAccessToken($data));
}
/**
* @param $shopId
* @param $brandId
* @param $tradeId
* @param $channel
* @param $channelDesc
* @param $pickUpCode
* @param $productStatus
* @return bool|string
* 推送订单详情
*/
public function postOrderInfo($shopId, $brandId, $tradeId, $channel, $channelDesc, $pickUpCode, $productStatus)
{
$hslPath = '/api/open/v4/kds/newOrder';
$data = [
'appId' => $this->appId,
'shopId' => $shopId,
'brandId' => $brandId,
'tradeId' => $tradeId,
'channel' => $channel,
'channelDesc' => $channelDesc,
'pickUpCode' => $pickUpCode,
'productStatus' => $productStatus,
'timestamp' => time() * 1000
];
return $this->post($data, $this->urlPrefix . $hslPath, $this->getAccessToken($data));
}
/**
* 检查推送接口加密
* @param $data
* @param $token
* @return bool
*/
public function checkPostRsa($data, $token)
{
$rsa = new Rsa();
return $rsa->privateDecrypt($token, $this->privateKey) === $this->arrToString($data);
}
/**
* 获取token
* @param $data
* @return string|null
*/
private function getAccessToken($data)
{
$rsa = new Rsa();
return $rsa->publicEncrypt($this->arrToString($data), $this->publicKey);
}
/**
* arr转string
* @param $data
* @return string
*/
private function arrToString($data)
{
ksort($data);
$str = '';
foreach ($data as $k => $v) {
$str .= $k . $v;
}
unset($k, $v);
return $str;
}
/**
* curl 发送post请求
* @param $data
* @param $url
* @param $accessToken
* @return bool|string
*/
private function post($data, $url, $accessToken)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json;charset=utf-8',
'messageUuid: ' . $this->uuid(),
'access-token: ' . $accessToken
]);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
/**
* 生成UUID
* @param string $prefix
* @return string
*/
private function uuid($prefix = '')
{
$chars = md5(uniqid(mt_rand(), true));
$uuid = substr($chars, 0, 8) . '-';
$uuid .= substr($chars, 8, 4) . '-';
$uuid .= substr($chars, 12, 4) . '-';
$uuid .= substr($chars, 16, 4) . '-';
$uuid .= substr($chars, 20, 12);
return $prefix . $uuid;
}
}
|
f8676996eef2753962e3834c1c10697de567de7e
|
[
"Markdown",
"PHP"
] | 9 |
PHP
|
hsl-rd/hsl-open-php
|
a4ed4a6845dbf094a1d6016d9de2e6f605cc9f96
|
6c2fe77883c5eb4ada1e21f17406b3f1af8249d5
|
refs/heads/master
|
<repo_name>nithyadhana/library-bot<file_sep>/test.py
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 28 15:17:06 2018
@author: Surya
"""
import csv
csv_file = csv.reader(open('books1.csv'), delimiter=",")
zone = "1"
for row in csv_file:
if zone == row[0]:
speech = ("\n\nBook Id: " + row[0] + "\n Book Title: " + row[1] + "\n Authors: " + row[2] + "\n Publication: " + row[3] + "\n Rack Number:" + row[4])
print(speech)
<file_sep>/var.py
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 05 14:54:32 2018
@author: Surya
"""
class UnQstn:
def __init__(self, user, question, answer, status):
self.user = user
self.question = question
self.answer = answer
self.status = status
UnknownQuery_one = UnQstn("user","question","answer","status")
ArrayOfQuestions = [UnknownQuery_one]
|
544b3319cb2cb6d1a71c4d763f48ac8b75a6a6c9
|
[
"Python"
] | 2 |
Python
|
nithyadhana/library-bot
|
c1b7d4a375355c65040740692f97399581343baa
|
663f4cfec613863853be526718a53da731f9ce3c
|
refs/heads/master
|
<file_sep><?php
getJson('example_input.txt', 'example_output.json');
function getJson( $input, $output ){
$fr = fopen($input, "r");
$fw = fopen($output, 'w');
$file_start = 'START_OF_THIS_FILE';
$file_end = 'END_OF_THIS_FILE';
$data_start = ':';
$data_end = '@';
while (!feof($fr)){
$content = fgets($fr);
if (strpos($content, $file_end) !== false) {
fwrite($fw, "]\n}");
break;
}
if (strpos($content, $file_start) !== false) {
fwrite($fw, "{"."\n".' "" : [""],'."\n");
} else {
if ( strpos($content, $data_start) !== false ) {
$content = ' "' . str_replace( array($data_start, "\n"), '', $content) . '"' . ' : [';
$tmp = fgets($fr);
$tmp = '"' . str_replace( "\n", '', $tmp) . '"';
$content = $content . $tmp;
fwrite($fw, $content);
} else {
if ( strpos($content, $data_end) !== false ){
$content = "],\n";
fwrite($fw, $content);
} else {
$content = ', "' . str_replace("\n", '', $content) . '"';
fwrite($fw, $content);
}
}
}
//echo $content;
}
fclose($fr);
fclose($fw);
}
?><file_sep># get_json
Convert text file with specific format into json format
|
9f4d4e59083f05809c76244981856c09d6bf2303
|
[
"Markdown",
"PHP"
] | 2 |
PHP
|
weichuntsai0217/get_json
|
7f90cd745714e734664c935e211abff7f2d8ca45
|
eb24611b89aaa590f7c2c37ddacb6923b582bca5
|
refs/heads/main
|
<repo_name>Kenebehi/testdriven-app<file_sep>/services/users/requirements.txt
flask== 0.12.2
Werkzeug==0.16.1
Flask-SQLAlchemy==2.3.2
psycopg2==2.7.3.2
<file_sep>/services/test.py
#!/usr/bin/python
import pandas as pd
import os
import json<file_sep>/services/testcopy.py
#!/usr/bin/python
import pandas as pd
import numpy as np
import os<file_sep>/test.sh
# find . -path "*/services/*" -prune -type f -name "*.py" | while read file; do
# new_file="--include ${file}"
# echo "${new_file}"
# done
# find . -path "*/services/*" -prune -type f -name "*.py" -exec printf "--include %p\n" | xargs -I{} echo -n "{} " | sed 's/ $//'
# find . -path "*/services/*" -prune -type f -name "*.py" -print0 | while IFS= read -r -d '' file; do echo "--include $file "; done | tr '\n' ' '
#PATHS="./services/hello.py ./services/test.py ./service/testcopy.py services/workers/services/new.py"
#FILES="$(echo $PATHS | tr ' ' '\n' | grep "services/workers/.*\.py" | awk -F/ '{print $NF}' | tr '\n' ' ')"
#echo $FILES
#
#INCLUDES=""
#for path in $FILES; do
# INCLUDES="$INCLUDES --include $path"
#done
#echo $INCLUDES
#!/bin/bash
## set the path to the input path
#full_path="airflow/utils/dag_utils/spark_etl.py"
#filename="$(basename "$full_path")" # extracts "hello.py"
#dirname="$(dirname "$full_path")" # extracts "foo/bar/baz"
#parentdir="$(basename "$dirname")" # extracts "baz"
#new_path="${parentdir}/${filename}" # creates "baz/hello.py"
#echo "$new_path" # prints "baz/hello.py"
#include=""
#for file in $full_path; do
# include="$include --include $(basename "$(dirname "$file")")/$(basename "$file")"
#done
#echo $include
#path="airflow/settings/subfolder/settings.yml airflow/settings/settings.yml"
#include=""
#for file in $path; do
# include="$include --include $(expr $file : '[^/]*/\(.*\)')"
#done
#echo $include
#include=""
#for file in "airflow/settings/globals.yml" "airflow/settings/subfolder/settings.yml"; do
# include="$include --include $( $file | sed 's/^[^\/]*\///')"
#done
#echo $include
include=""
for file in "airflow/settings/globals.yml" "airflow/settings/subfolder/settings.yml"; do
include="$include --include ${file#*/}"
done
echo "$include"
|
57f46a39df558cf90d0cd7fd3cf0af6f8d21a30b
|
[
"Python",
"Text",
"Shell"
] | 4 |
Text
|
Kenebehi/testdriven-app
|
70964b10a47a2939bf87aeee100d2f624a33cae3
|
96001478d2a6c0359f1e745fa3d00f78e437eb39
|
refs/heads/main
|
<file_sep> success({
name: 'zs',
age: 20
});<file_sep>window.addEventListener('load', function() {
// 获取大盒子
var box = this.document.querySelector('.box');
// 左侧按钮
var left_btn = this.document.getElementById('left_btn');
// 右侧按钮
var right_btn = this.document.getElementById('right_btn');
//鼠标经过,左侧和右侧箭头显示
box.addEventListener('mouseenter', function() {
left_btn.style.display = 'block';
right_btn.style.display = 'block';
clearInterval(time);
time = null;
});
//鼠标离开,左侧和右侧箭头隐藏
box.addEventListener('mouseleave', function() {
left_btn.style.display = 'none';
right_btn.style.display = 'none';
img_zidong();
});
//根据图片数量,动态生成小圆点
//1.获取插入小圆点的父级ol
var circle = this.document.querySelector('.circle');
//2.获取图片数量(li的个数)
var ul = box.querySelector('ul');
//左右按钮控制图片移动的大小下标
var index_img = 0;
//存放所有生成的li
var arr_li = [];
//s③放图片盒子的宽度(图片的大小)
var boxWidth = box.offsetWidth;
//3.循环插入小圆点
for (var i = 0; i < ul.children.length; i++) {
//(1).创建li,给自定义属性:记录索引号
var li = this.document.createElement('li');
arr_li.push(li);
li.setAttribute('index', i);
//(2).插入li
circle.appendChild(li);
//(4)为每个生成的小圆圈绑定点击事件
li.addEventListener('click', function() {
//①将所有li背景颜色清除
for (var i = 0; i < circle.children.length; i++) {
circle.children[i].className = '';
}
//②设置点击的li背景颜色
this.className = 'current';
//s④获取点击的li的index属性
var index = this.getAttribute('index');
index_img = parseInt(index);
console.log('左侧按钮:' + index_img);
console.log(index);
animate_huandong(ul, -index * boxWidth);
});
}
//(3).将第一个小圆点设置类名为current(样式设置了背景为红色)
circle.children[0].className = 'current';
//先克隆图片
var fist = ul.children[0].cloneNode(true);
ul.appendChild(fist);
//1.左鼠标箭头控制轮播图
var flag = true;
left_btn.addEventListener('click', function() {
if (flag) {
console.log('执行节流阀');
//关闭
flag = false;
// if ((index_img + 1) < ul.children.length) {
//当到最后一张的时候,让ul快速回到left=0
if (index_img + 1 == ul.children.length) {
ul.style.left = 0;
index_img = 0;
}
//(1)点击图片移动
index_img++;
animate_huandong(ul, -index_img * boxWidth, function() {
flag = true;
});
//(2)点击让对应的小圆点背景设置为红色
//①将所有li背景颜色清除
for (var i = 0; i < arr_li.length; i++) {
arr_li[i].className = '';
}
//②设置点击的li背景颜色
if (index_img == arr_li.length) {
arr_li[0].className = 'current';
} else {
arr_li[index_img].className = 'current';
}
// }
}
});
//2.右鼠标箭头控制轮播图
right_btn.addEventListener('click', function() {
if (flag) {
console.log('执行节流阀');
//关闭
flag = false;
console.log('所有li' + arr_li);
if (index_img == 0) {
ul.style.left = -(box.offsetWidth * (ul.children.length - 1)) + 'px';
index_img = 4;
}
index_img--;
animate_huandong(ul, -index_img * boxWidth, function() {
flag = true;
});
//①将所有li背景颜色清除
for (var i = 0; i < arr_li.length; i++) {
arr_li[i].className = '';
}
//②设置点击的li背景颜色
arr_li[index_img].className = 'current';
}
});
//1.自动播放轮播图
var time;
img_zidong();
function img_zidong() {
time = this.setInterval(function() {
if (index_img + 1 == ul.children.length) {
console.log(ul.children.length);
ul.style.left = 0;
index_img = 0;
}
//(1)点击图片移动
index_img++;
animate_huandong(ul, -index_img * boxWidth);
//(2)点击让对应的小圆点背景设置为红色
//①将所有li背景颜色清除
for (var i = 0; i < arr_li.length; i++) {
arr_li[i].className = '';
}
//②设置点击的li背景颜色
if (index_img == arr_li.length) {
arr_li[0].className = 'current';
} else {
arr_li[index_img].className = 'current';
}
}, 2000);
}
})<file_sep>(function() {
var data = [{
date: 20180701,
dizhi: '11北京市昌平西路金燕龙写字楼',
bianhao: 1000001
}, {
date: 20180702,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000002
},
{
date: 20180703,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000003
},
{
date: 20180704,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000004
},
{
date: 20180705,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000005
},
{
date: 20180706,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000006
},
{
date: 20180707,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000007
},
{
date: 20180708,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000008
},
{
date: 20180709,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000009
},
{
date: 20180710,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000010
},
]
var data_two = [{
date: 201807011,
dizhi: '11北京市昌平西路金燕龙写字楼',
bianhao: 10000012
}, {
date: 201807013,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000002
},
{
date: 201807014,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000003
},
{
date: 201807015,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000004
},
{
date: 201807016,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000005
},
{
date: 201807017,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000006
},
{
date: 201807018,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000007
},
{
date: 201807019,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000008
},
{
date: 201807020,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000009
},
{
date: 201807121,
dizhi: '北京市昌平区城西路金燕龙写字楼',
bianhao: 1000010
},
]
var arr_data = [data, data_two];
//1、按钮切换
$(".tab").on("click", ".jiankong", function() {
$(this).addClass("active").siblings(".jiankong").removeClass("active");
xuanrang(arr_data[$(this).index()]);
});
// $(".marquee").append("<div class='row'><span>20180701</span><span>11北京市昌平西路金燕龙写字楼</span> <span>1000001</span></div>");
// $(".marquee").append("<div class='row'><span>20180701</span><span>11北京市昌平西路金燕龙写字楼</span> <span>1000001</span></div>")
function xuanrang(data) {
var createElement = '';
$.each(data, function(index, element) {
// console.log(element);
createElement += "<div class='row'><span>" + element.date + "</span><span>" + element.dizhi +
"</span> <span>" + element.bianhao + "</span></div>";
});
$(".marquee").empty();
$(".marquee").append(createElement);
// 1. 先克隆marquee里面所有的行( row)
$(".shuju .marquee").each(function() {
var rows = $(this)
.children()
.clone();
$(this).append(rows);
});
};
xuanrang(data);
})();<file_sep>// window.onload = function() {
// var div = document.querySelector('div');
// var btn_400 = document.querySelector('.btn_400');
// var btn_800 = document.querySelector('.btn_800');
//1、动画函数(匀速动画)的封装 obj:谁调用该函式 target:到哪个位子结束
function animate(obj, target) {
//保证一个对象只有一个定时器,解决每点击一次就会开启一个定时器的bug
clearInterval(obj.timer);
obj.timer = setInterval(function() {
if (div.offsetLeft >= target) {
clearInterval(timer);
}
obj.style.left = div.offsetLeft + 5 + 'px';
}, 30);
}
//1、动画函数(缓动动画)的封装 obj:谁调用该函式 target:到哪个位子结束 callback:接收一个函数
function animate_huandong(obj, target, callback) {
//保证一个对象只有一个定时器,解决每点击一次就会开启一个定时器的bug
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var step = (target - obj.offsetLeft) / 10;
//后退是负数,取整要用负数的函数取,整数取整用Math.ceil
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
//回调函数
if (callback) {
//调用回调函数
callback();
}
}
//(目标值 - 当前位子)/ 10
obj.style.left = obj.offsetLeft + step + 'px';
}, 30);
}
// btn_400.addEventListener('click', function() { //此次有bug,每点击一次就会调用一次,开启一个定时器,导致速度越来越快
// //2、调用函数
// // animate(div, 400);
// animate_huandong(div, 400, function() {
// console.log('定时器结束,调用该函数');
// div.style.backgroundColor = 'blue';
// });
// });
// btn_800.addEventListener('click', function() { //此次有bug,每点击一次就会调用一次,开启一个定时器,导致速度越来越快
// //2、调用函数
// // animate(div, 400);
// animate_huandong(div, 800);
// });<file_sep>$(function() {
load();
//一、按下回车,保存输入框中的数据
$("#title").on("keydown", function(event) {
if (event.keyCode === 13) {
//1、先读取本地已存储的数据
var local = getDate();
// console.log(local);
//2、将数据追加到数组中
local.push({ title: $(this).val(), done: false });
//3、存储到本地
// localStorage.setItem("todolist",local);
saveDate(local);
//4、将数据渲染到页面中
load();
}
});
//二、点一下a标签,删除数据数据
$("ol").on("click", "a", function() {
// alert("111");
//1、获取本地数据
var date = getDate();
//2、修改数据
var index = $(this).attr("id");
// console.log(index);
date.splice(index, 1);
//3、保存数据到本地
saveDate(date);
//4、重新渲染
load();
});
//读取本地数据的函数
function getDate() {
var data = localStorage.getItem("todolist");
if (data != null) {
//获取的数据是字符串,转换成数组对象
return JSON.parse(data);
} else {
return [];
}
}
//保存本地存储数据
function saveDate(date) {
localStorage.setItem("todolist", JSON.stringify(date));
}
//渲染页面
function load() {
//1、读取数据
var data = getDate();
//2、遍历数据
//先清空ol中的标签
$("ol").empty();
//再遍历数据
$.each(data, function(i, n) {
$("ol").prepend("<li><input type='checkbox'><p>" + n.title + "</p><a href='#' id=" + i + "></a></li>");
});
}
})<file_sep>$(function() {
// 初始化右侧滚动条
// 这个方法定义在scroll.js中
resetui();
//1、为发送按钮绑定点击事件
$('#btnSen').on('click', function() {
var text = $('#input_txt').val().trim();
if (text.length <= 0) {
// console.log('1');
return $('#input_txt').val('');
}
//2、用户输入了内容,追加到页面中
$('#talk_list').append('<li class="right_word"><img src="img/person02.png" /> <span>' + text + '</span></li>');
$('#input_txt').val('');
//3、页面内容过多,重置滚动条
resetui();
getMsg(text);
});
//2、回车的时候,执行绑定的点击事件
$('#input_txt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#btnSen').click();
}
});
//获取聊天机器人响应的消息
function getMsg(text) {
$.ajax({
method: 'get',
url: 'http://www.liulongbin.top:3006/api/robot',
data: {
spoken: text
},
success: function(res) {
// console.log(res);
if (res.message === 'success') {
var msg = res.data.info.text;
// console.log(msg);
$('#talk_list').append('<li class="left_word"><img src="img/person02.png" /> <span>' + msg + '</span></li>');
//3、页面内容过多,重置滚动条
resetui();
//语音播放,将获取的信息转换成语音
getVoice(msg);
}
}
})
}
//语音播放
function getVoice(text) {
$.ajax({
method: 'get',
url: 'http://www.liulongbin.top:3006/api/synthesize',
data: {
text: text
},
success: function(res) {
if (res.status === 200) {
//播放语音
$('#voice').attr('src', res.voiceUrl);
}
}
})
}
})<file_sep>// 1、将对象转换成查询字符串
function resolveData(data) {
var arr = [];
for (var k in data) {
var str = k + '=' + data[k];
arr.push(str);
}
return arr.join('$');
}
// var result = resolveData({ name: 'zs', age: 20 });
// console.log(result);
function itheima(options) {
var xhr = new XMLHttpRequest();
//把外界传递过来的参数对象,转换为查询字符串
var qs = resolveData(options.data);
if (options.method.toUpperCase() === 'GET') {
//GET请求
xhr.open(options.method, options.url + '?' + qs)
xhr.send();
} else if (options.method.toUpperCase() === 'POST') {
xhr.open(options.method, options.url)
xhr.setRequestHeader('Conten-Type', 'application/x-www/form-urlencode');
xhr.send();
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText);
options.success(result);
}
}
}
|
1bcd983339b4af16ddac501ab66b99a21b678283
|
[
"JavaScript"
] | 7 |
JavaScript
|
Hunsomeboby/web_bigevent
|
aa520fb987832387692f8b798b414be09c440454
|
f88e473d2360ba9c5721f71fdd29f76cd895e601
|
refs/heads/master
|
<repo_name>dtg01100/add_ean8_barcode_to_spreadsheet_utility<file_sep>/main.py
#!/usr/bin/env python3
import shutil
import warnings
import barcode
import openpyxl
import openpyxl.utils
from openpyxl.drawing.image import Image as OpenPyXlImage
from PIL import Image as pil_Image
import ImageOps as pil_ImageOps
import math
from barcode.writer import ImageWriter
import tkinter
import tkinter.ttk
import tkinter.filedialog
import tkinter.messagebox
import tempfile
import argparse
import textwrap
import threading
import platform
import os
import configparser
import appdirs
import re
import io
import barcode.pybarcode
import logging
from contextlib import redirect_stdout
version = '1.7.1'
appname = "Barcode Insert Utility"
supported_barcode_types = ['code39', 'ean8', 'ean13', 'UPC']
config_folder = appdirs.user_data_dir(appname)
try:
os.makedirs(config_folder)
except FileExistsError:
pass
settings_file_path = os.path.join(config_folder, 'barcode insert utility settings.cfg')
# read launch options
launch_options = argparse.ArgumentParser()
launch_options.add_argument('-d', '--debug', action='store_true', help="print debug output to stdout")
launch_options.add_argument('-l', '--log', action='store_true', help="write stdout to log file")
launch_options.add_argument('--keep_barcodes_in_cwd', action='store_true',
help="temp folder in working directory")
launch_options.add_argument('--keep_barcode_files', action='store_true', help="don't delete temp files")
launch_options.add_argument('--reset_configuration', action='store_true', help="remove configuration file")
args = launch_options.parse_args()
if args.reset_configuration: # remove configuration file if reset_configuration flag is set
try:
os.remove(settings_file_path)
except FileNotFoundError:
pass
config = configparser.RawConfigParser()
if not os.path.exists(settings_file_path):
config.add_section('settings')
config.set('settings', 'initial_input_folder', os.path.expanduser('~'))
config.set('settings', 'initial_output_folder', os.path.expanduser('~'))
config.set('settings', 'barcode_dpi', '120')
config.set('settings', 'barcode_module_height', '5')
config.set('settings', 'barcode_border', '0')
config.set('settings', 'barcode_font_size', '6')
config.set('settings', 'input_data_column', 'B')
config.set('settings', 'barcode_output_column', 'A')
config.set('settings', 'barcode type', 'code39')
config.set('settings', 'pad ean barcodes', "False")
with open(settings_file_path, 'w', encoding='utf8') as configfile:
config.write(configfile)
config.read(settings_file_path) # open config file
root_window = tkinter.Tk()
root_window.title("Barcode Insert Utility " + version)
# this builds a list of the launch flags
flags_list_string = "Flags="
flags_count = 0
if args.debug:
flags_list_string += "(Debug)"
flags_count += 1
if args.log:
flags_list_string += "(Logged)"
flags_count += 1
if args.keep_barcodes_in_cwd:
flags_list_string += "(Barcodes In Working Directory)"
flags_count += 1
if args.keep_barcode_files:
flags_list_string += "(Keep Barcodes)"
flags_count += 1
if args.reset_configuration:
flags_list_string += "(Reset Configuration)"
flags_count += 1
old_workbook_path = ""
new_workbook_path = ""
program_launch_cwd = os.getcwd()
process_workbook_keep_alive = True
column_letter_list = []
column_count = 0
while column_count < 200:
column_count += 1
column_letter = openpyxl.utils.get_column_letter(column_count)
column_letter_list.append(column_letter)
column_letter_tuple = tuple(column_letter_list)
barcode_type_variable = tkinter.StringVar()
pad_ean_option = tkinter.BooleanVar()
def invalid_configuration_error():
root_window.withdraw()
tkinter.messagebox.showerror(title="Batch File Sender Version " + version,
message="Configuration file is broken, "
"relaunch program with the option '--reset_configuration'")
raise SystemExit
# set initial variables for configuration file test
barcode_dpi_test = None
barcode_module_height_test = None
barcode_border_test = None
barcode_font_size_test = None
barcode_type_test = None
invalid_configuration = False
input_barcode_test_column = None
output_barcode_test_column = None
# check to see if the following four are integers
try:
barcode_dpi_test = config.getint('settings', 'barcode_dpi')
barcode_module_height_test = config.getint('settings', 'barcode_module_height')
barcode_border_test = config.getint('settings', 'barcode_border')
barcode_font_size_test = config.getint('settings', 'barcode_font_size')
except ValueError:
invalid_configuration_error()
try:
input_barcode_test_column = config.get('settings', 'input_data_column')
output_barcode_test_column = config.get('settings', 'barcode_output_column')
barcode_type_test = config.get('settings', 'barcode type')
_ = config.getboolean('settings', 'pad ean barcodes')
except (configparser.NoOptionError, ValueError):
invalid_configuration_error()
# check that values are in acceptable ranges
if input_barcode_test_column not in column_letter_list or output_barcode_test_column not in column_letter_list:
invalid_configuration = True
if barcode_dpi_test not in range(120, 400):
invalid_configuration = True
if barcode_module_height_test not in range(5, 50):
invalid_configuration = True
if barcode_border_test not in range(0, 25):
invalid_configuration = True
if barcode_font_size_test not in range(0, 15):
invalid_configuration = True
if barcode_type_test not in supported_barcode_types:
invalid_configuration = True
if invalid_configuration: # if any of the previous values are incorrect, show an error dialog and close out
invalid_configuration_error()
# the following sets internal open file limits
try:
if platform.system() == 'Windows':
import win32file
file_limit = win32file._getmaxstdio()
else:
import resource
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
file_limit = soft
except Exception as error:
warnings.warn("Getting open file limit failed with: " + str(error) + " setting internal file limit to 100")
file_limit = 100
if args.log:
class Logger():
def __init__(self):
self.logger = logging.getLogger('Barcode Insert Utility')
self.logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('logfile.log')
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
self.logger.addHandler(fh)
self.logger.addHandler(ch)
def write(self, message):
self.logger.debug(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
loghandler = Logger()
if args.debug:
print(launch_options.parse_args())
# this is a wrapper function for print, so that we can have it only spam stdout when debug is set
def print_if_debug(string):
if args.debug:
loghandler.write(string)
print_if_debug("Barcode Insert Utility version " + version)
print_if_debug("File limit is: " + str(file_limit))
# get supported formats from pybarcode, in case debugging is required
with io.StringIO() as buf, redirect_stdout(buf):
barcode.pybarcode.list_types(ImageWriter)
output = buf.getvalue()
print_if_debug(output)
# this is the workbook selector, the code was a bit of an experiment and is a bit of a pain to debug.
# not enough of the logic is shared between the two codepaths to make it worth the complexity
# ill probably rewrite this at some point.
def select_folder_old_new_wrapper(selection):
global old_workbook_path
global new_workbook_path
for child in size_spinbox_frame.winfo_children():
child.configure(state=tkinter.DISABLED)
new_workbook_selection_button.configure(state=tkinter.DISABLED)
old_workbook_selection_button.configure(state=tkinter.DISABLED)
if selection == "old":
old_workbook_path_proposed = tkinter.filedialog.askopenfilename(
initialdir=config.get('settings', 'initial_input_folder'),
filetypes=[("Excel Spreadsheet", "*.xlsx")])
file_is_xlsx = False
try:
if os.path.exists(old_workbook_path_proposed):
config.set('settings', 'initial_input_folder', os.path.dirname(old_workbook_path_proposed))
with open(settings_file_path, 'w', encoding='utf8') as configuration_file:
config.write(configuration_file)
try:
openpyxl.load_workbook(old_workbook_path_proposed, read_only=True)
file_is_xlsx = True
except Exception as file_test_open_error:
print(file_test_open_error)
except TypeError:
old_workbook_path_proposed = ''
if os.path.exists(old_workbook_path_proposed) and file_is_xlsx is True:
old_workbook_path = old_workbook_path_proposed
old_workbook_path_wrapped = '\n'.join(textwrap.wrap(old_workbook_path, width=75, replace_whitespace=False))
old_workbook_label.configure(text=old_workbook_path_wrapped, justify=tkinter.LEFT)
else:
new_workbook_path_proposed = tkinter.filedialog.asksaveasfilename(
initialdir=config.get('settings', 'initial_output_folder'),
initialfile=os.path.basename(old_workbook_path),
defaultextension='.xlsx',
filetypes=[("Excel Spreadsheet", "*.xlsx")])
try:
if os.path.exists(os.path.dirname(new_workbook_path_proposed)):
new_workbook_path = new_workbook_path_proposed
config.set('settings', 'initial_output_folder', os.path.dirname(new_workbook_path))
with open(settings_file_path, 'w', encoding='utf8') as configuration_file:
config.write(configuration_file)
new_workbook_path_wrapped = '\n'.join(
textwrap.wrap(new_workbook_path, width=75, replace_whitespace=False))
new_workbook_label.configure(text=new_workbook_path_wrapped, justify=tkinter.LEFT,
background=old_workbook_label._root().cget('background'))
except AttributeError:
new_workbook_path = ''
if os.path.exists(old_workbook_path) and os.path.exists(os.path.dirname(new_workbook_path)):
process_workbook_button.configure(state=tkinter.NORMAL, text="Process Workbook")
for child in size_spinbox_frame.winfo_children():
child.configure(state=tkinter.NORMAL)
set_spinbutton_state_read_only()
new_workbook_selection_button.configure(state=tkinter.NORMAL)
old_workbook_selection_button.configure(state=tkinter.NORMAL)
def generate_barcode(input_string, tempdir):
border_size = int(border_spinbox.get())
ean = barcode.get(barcode_type_variable.get(), input_string, writer=ImageWriter())
# select output image size via dpi. internally, pybarcode renders as svg, then renders that as a png file.
# dpi is the conversion from svg image size in mm, to what the image writer thinks is inches.
ean.default_writer_options['dpi'] = int(dpi_spinbox.get())
# module height is the barcode bar height in mm
ean.default_writer_options['module_height'] = float(height_spinbox.get())
# text distance is the distance between the bottom of the barcode, and the top of the text in mm
ean.default_writer_options['text_distance'] = 1
# font size is the text size in pt
ean.default_writer_options['font_size'] = int(font_size_spinbox.get())
# quiet zone is the distance from the ends of the barcode to the ends of the image in mm
ean.default_writer_options['quiet_zone'] = 2
# save barcode image with generated filename
print_if_debug("generating barcode image")
with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as initial_temp_file_path:
filename = ean.save(initial_temp_file_path.name[0:-4])
print_if_debug("success, barcode image path is: " + filename)
print_if_debug("opening " + str(filename) + " to add border")
barcode_image = pil_Image.open(str(filename)) # open image as pil object
print_if_debug("success")
print_if_debug("adding barcode and saving")
img_save = pil_ImageOps.expand(barcode_image, border=border_size,
fill='white') # add border around image
width, height = img_save.size # get image size of barcode with border
# write out image to file
with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as final_barcode_path:
img_save.save(final_barcode_path.name)
print_if_debug("success, final barcode path is: " + final_barcode_path.name)
return final_barcode_path.name, width, height
def interpret_barcode_string(upc_barcode_string):
if not upc_barcode_string == '':
if barcode_type_variable.get() == "ean13" or barcode_type_variable.get() == "ean8":
try:
_ = int(upc_barcode_string) # check that "upc_barcode_string" can be cast to int
except ValueError as exc:
raise ValueError("Input contents are not an integer") from exc
# select barcode type, specify barcode, and select image writer to save as png
if barcode_type_variable.get() == "ean8":
if pad_ean_option.get() is True:
if len(upc_barcode_string) < 6:
upc_barcode_string = upc_barcode_string.rjust(6, '0')
if len(upc_barcode_string) <= 7:
upc_barcode_string = upc_barcode_string.ljust(7, '0')
else:
raise ValueError("Input contents are more than 7 characters")
else:
if len(upc_barcode_string) != 7:
raise ValueError("Input contents are not 7 characters")
elif barcode_type_variable.get() == "ean13":
if pad_ean_option.get() is True:
if len(upc_barcode_string) < 11:
upc_barcode_string = upc_barcode_string.rjust(11, '0')
if len(upc_barcode_string) <= 12:
upc_barcode_string = upc_barcode_string.ljust(12, '0')
else:
raise ValueError("Input contents are more than 12 characters")
else:
if len(upc_barcode_string) != 12:
raise ValueError("Input contents are not 12 characters")
elif barcode_type_variable.get() == "UPC":
if pad_ean_option.get() is True:
if len(upc_barcode_string) < 10:
upc_barcode_string = upc_barcode_string.rjust(11, '0')
if len(upc_barcode_string) <= 11:
upc_barcode_string = upc_barcode_string.ljust(12, '0')
else:
raise ValueError("Input contents are more than 11 characters")
else:
if len(upc_barcode_string) != 11:
raise ValueError("Input contents are not 11 characters")
elif barcode_type_variable.get() == "code39":
upc_barcode_string = upc_barcode_string.upper()
upc_barcode_string = re.sub('[^A-Z0-9./*$%+\- ]+', ' ', upc_barcode_string)
return upc_barcode_string
raise ValueError("Input is empty")
def do_process_workbook():
# this is called as a background thread to ensure the interface is responsive
print_if_debug("creating temp directory")
if not args.keep_barcodes_in_cwd:
tempdir = tempfile.mkdtemp()
else:
temp_dir_in_cwd = os.path.join(program_launch_cwd, 'barcode images')
os.mkdir(temp_dir_in_cwd)
tempdir = temp_dir_in_cwd
print_if_debug("temp directory created as: " + tempdir)
progress_bar.configure(mode='indeterminate', maximum=100)
progress_bar.start()
progress_numbers.configure(text="opening workbook")
wb = openpyxl.load_workbook(old_workbook_path)
ws = wb.worksheets[0]
progress_numbers.configure(text="testing workbook save")
wb.save(new_workbook_path)
count = 0
save_counter = 0
progress_bar.configure(maximum=ws.max_row, value=count)
progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
for _ in ws.iter_rows(): # iterate over all rows in current worksheet
if not process_workbook_keep_alive:
break
try:
count += 1
progress_bar.configure(maximum=ws.max_row, value=count, mode='determinate')
progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
progress_bar.configure(value=count)
# get code from column selected in input_colum_spinbox, on current row,
# add a zeroes to the end if option is selected to make seven or 12 digits
print_if_debug("getting cell contents on line number " + str(count))
upc_barcode_string = str(ws[input_column_spinbox.get() + str(count)].value)
print_if_debug("cell contents are: " + upc_barcode_string)
upc_barcode_string = interpret_barcode_string(upc_barcode_string)
generated_barcode_path, width, height = generate_barcode(upc_barcode_string, tempdir)
# resize cell to size of image
ws.column_dimensions[output_column_spinbox.get()].width = int(math.ceil(float(width) * .15))
ws.row_dimensions[count].height = int(math.ceil(float(height) * .75))
# open image with as openpyxl image object
print_if_debug("opening " + generated_barcode_path + " to insert into output spreadsheet")
img = OpenPyXlImage(generated_barcode_path)
print_if_debug("success")
# attach image to cell
print_if_debug("adding image to cell")
# add image to cell
ws.add_image(img, anchor=output_column_spinbox.get() + str(count))
save_counter += 1
print_if_debug("success")
except Exception as barcode_error:
print_if_debug(barcode_error)
# This save in the loop frees references to the barcode images,
# so that python's garbage collector can clear them
if save_counter >= file_limit - 50:
print_if_debug("saving intermediate workbook to free file handles")
progress_bar.configure(mode='indeterminate', maximum=100)
progress_bar.start()
progress_numbers.configure(text=str(count) + "/" + str(ws.max_row) + " saving")
wb.save(new_workbook_path)
print_if_debug("success")
save_counter = 1
progress_numbers.configure(text=str(count) + "/" + str(ws.max_row))
progress_bar.configure(value=0)
print_if_debug("saving workbook to file")
progress_bar.configure(mode='indeterminate', maximum=100)
progress_bar.start()
progress_numbers.configure(text="saving")
wb.save(new_workbook_path)
print_if_debug("success")
if not args.keep_barcode_files:
print_if_debug("removing temp folder " + tempdir)
shutil.rmtree(tempdir)
print_if_debug("success")
def process_workbook_thread():
# this function handles setup and teardown of the process workbook thread
global new_workbook_path
process_errors = False
global process_workbook_keep_alive
process_workbook_keep_alive = True
try:
do_process_workbook()
except (IOError, OSError):
print("Error saving file")
process_errors = True
new_workbook_label.configure(text="Error saving, select another output file.", background='red')
finally:
progress_bar.stop()
progress_bar.configure(maximum=100, value=0, mode='determinate')
progress_numbers.configure(text="")
new_workbook_path = ""
if not process_errors:
new_workbook_label.configure(text="No File Selected")
def process_workbook_command_wrapper():
def kill_process_workbook():
# this function sets the keep alive flag for the processing workbook thread to false,
# this lets the thread exit gracefully, and clean up after itself
global process_workbook_keep_alive
process_workbook_keep_alive = False
cancel_process_workbook_button.configure(text="Cancelling", state=tkinter.DISABLED)
# this sets interface elements to disabled, and then saves config options to file
new_workbook_selection_button.configure(state=tkinter.DISABLED)
old_workbook_selection_button.configure(state=tkinter.DISABLED)
config.set('settings', 'barcode_dpi', dpi_spinbox.get())
config.set('settings', 'barcode_module_height', height_spinbox.get())
config.set('settings', 'barcode_border', border_spinbox.get())
config.set('settings', 'barcode_font_size', font_size_spinbox.get())
config.set('settings', 'input_data_column', input_column_spinbox.get())
config.set('settings', 'barcode_output_column', output_column_spinbox.get())
config.set('settings', 'barcode type', barcode_type_variable.get())
config.set('settings', 'pad ean barcodes', pad_ean_option.get())
with open(settings_file_path, 'w', encoding='utf8') as configfile_before_processing:
config.write(configfile_before_processing)
for child in size_spinbox_frame.winfo_children():
child.configure(state=tkinter.DISABLED)
process_workbook_button.configure(state=tkinter.DISABLED, text="Processing Workbook")
cancel_process_workbook_button = tkinter.ttk.Button(master=go_button_frame, command=kill_process_workbook,
text="Cancel")
cancel_process_workbook_button.pack(side=tkinter.RIGHT)
process_workbook_thread_object = threading.Thread(target=process_workbook_thread)
process_workbook_thread_object.start()
while process_workbook_thread_object.is_alive():
root_window.update()
cancel_process_workbook_button.destroy()
new_workbook_selection_button.configure(state=tkinter.NORMAL)
old_workbook_selection_button.configure(state=tkinter.NORMAL)
for child in size_spinbox_frame.winfo_children():
child.configure(state=tkinter.NORMAL)
set_spinbutton_state_read_only()
if process_workbook_keep_alive:
process_workbook_button.configure(text="Done Processing Workbook")
else:
process_workbook_button.configure(text="Processing Workbook Canceled")
def generate_single_barcode():
print("single barcode stub")
if upc_entry.get() == '':
return
print_if_debug("creating temp directory")
if not args.keep_barcodes_in_cwd:
tempdir = tempfile.mkdtemp()
else:
temp_dir_in_cwd = os.path.join(program_launch_cwd, 'barcode images')
os.mkdir(temp_dir_in_cwd)
tempdir = temp_dir_in_cwd
save_path = tkinter.filedialog.asksaveasfilename(
initialdir=config.get('settings', 'initial_output_folder'),
initialfile=upc_entry.get(),
defaultextension='.png',
filetypes=[("PNG Image File", "*.png")])
try:
if os.path.exists(os.path.dirname(save_path)):
barcode_path, _, _ = generate_barcode(interpret_barcode_string(upc_entry.get()), tempdir)
shutil.copyfile(barcode_path, save_path)
except Exception as error:
tkinter.messagebox.showerror(master=root_window, message=f"Failed to generate barcode image: {str(error)}")
if not args.keep_barcode_files:
print_if_debug("removing temp folder " + tempdir)
shutil.rmtree(tempdir)
print_if_debug("success")
both_workbook_frame = tkinter.ttk.Frame(root_window)
old_workbook_file_frame = tkinter.ttk.Frame(both_workbook_frame)
new_workbook_file_frame = tkinter.ttk.Frame(both_workbook_frame)
go_and_progress_frame = tkinter.ttk.Frame(root_window)
go_button_frame = tkinter.ttk.Frame(go_and_progress_frame)
progress_bar_frame = tkinter.ttk.Frame(go_and_progress_frame)
size_spinbox_frame = tkinter.ttk.Frame(root_window, relief=tkinter.GROOVE, borderwidth=2)
def set_spinbutton_state_read_only():
# this sets all spinbuttons to readonly, this prevents invalid input from being inserted.
# eventually, ill get a validator working and this will be unnecessary
dpi_spinbox.configure(state='readonly')
height_spinbox.configure(state='readonly')
border_spinbox.configure(state='readonly')
font_size_spinbox.configure(state='readonly')
input_column_spinbox.configure(state='readonly')
output_column_spinbox.configure(state='readonly')
barcode_type_menu = tkinter.ttk.OptionMenu(size_spinbox_frame, barcode_type_variable,
config.get('settings', 'barcode type'), *supported_barcode_types)
pad_ean_checkbutton = tkinter.ttk.Checkbutton(size_spinbox_frame, text="Pad EAN Barcodes", variable=pad_ean_option,
onvalue=True, offvalue=False)
pad_ean_option.set(config.getboolean('settings', 'pad ean barcodes'))
dpi_spinbox = tkinter.Spinbox(size_spinbox_frame, from_=120, to=400, width=3, justify=tkinter.RIGHT)
dpi_spinbox.delete(0, "end")
dpi_spinbox.insert(0, str(config.getint('settings', 'barcode_dpi')))
height_spinbox = tkinter.Spinbox(size_spinbox_frame, from_=5, to=50, width=3, justify=tkinter.RIGHT)
height_spinbox.delete(0, "end")
height_spinbox.insert(0, str(config.getint('settings', 'barcode_module_height')))
border_spinbox = tkinter.Spinbox(size_spinbox_frame, from_=0, to=25, width=3, justify=tkinter.RIGHT)
border_spinbox.delete(0, "end")
border_spinbox.insert(0, str(config.getint('settings', 'barcode_border')))
font_size_spinbox = tkinter.Spinbox(size_spinbox_frame, from_=0, to=15, width=3, justify=tkinter.RIGHT)
font_size_spinbox.delete(0, "end")
font_size_spinbox.insert(0, str(config.getint('settings', 'barcode_font_size')))
input_column_spinbox = tkinter.Spinbox(size_spinbox_frame, values=column_letter_tuple, width=3, justify=tkinter.RIGHT)
input_column_spinbox.delete(0, "end")
input_column_spinbox.insert(0, str(config.get('settings', 'input_data_column')))
output_column_spinbox = tkinter.Spinbox(size_spinbox_frame, values=column_letter_tuple, width=3, justify=tkinter.RIGHT)
output_column_spinbox.delete(0, "end")
output_column_spinbox.insert(0, str(config.get('settings', 'barcode_output_column')))
set_spinbutton_state_read_only()
old_workbook_selection_button = tkinter.ttk.Button(master=old_workbook_file_frame, text="Select Original Workbook",
command=lambda: select_folder_old_new_wrapper("old"))
old_workbook_selection_button.pack(anchor='w')
new_workbook_selection_button = tkinter.ttk.Button(master=new_workbook_file_frame, text="Select New Workbook",
command=lambda: select_folder_old_new_wrapper("new"))
new_workbook_selection_button.pack(anchor='w')
old_workbook_label = tkinter.ttk.Label(master=old_workbook_file_frame, text="No File Selected", relief=tkinter.SUNKEN)
new_workbook_label = tkinter.ttk.Label(master=new_workbook_file_frame, text="No File Selected", relief=tkinter.SUNKEN)
old_workbook_label.pack(anchor='w', padx=(1, 0))
new_workbook_label.pack(anchor='w', padx=(1, 0))
# create spinbox labels
barcode_type_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Barcode Type:", anchor=tkinter.E)
size_spinbox_dpi_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Barcode DPI:", anchor=tkinter.E)
size_spinbox_height_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Barcode Height:", anchor=tkinter.E)
border_spinbox_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Barcode Border:", anchor=tkinter.E)
font_size_spinbox_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Barcode Text Size:", anchor=tkinter.E)
input_column_spinbox_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Input Column:", anchor=tkinter.E)
output_column_spinbox_label = tkinter.ttk.Label(master=size_spinbox_frame, text="Output Column:", anchor=tkinter.E)
# insert spinbox labels into frame with grid packer
barcode_type_label.grid(row=0, column=0, sticky=tkinter.W + tkinter.E, pady=2)
size_spinbox_dpi_label.grid(row=1, column=0, sticky=tkinter.W + tkinter.E, pady=2)
size_spinbox_height_label.grid(row=2, column=0, sticky=tkinter.W + tkinter.E, pady=2)
border_spinbox_label.grid(row=3, column=0, sticky=tkinter.W + tkinter.E, pady=2)
font_size_spinbox_label.grid(row=1, column=2, sticky=tkinter.W + tkinter.E, pady=2)
input_column_spinbox_label.grid(row=2, column=2, sticky=tkinter.W + tkinter.E, pady=2)
output_column_spinbox_label.grid(row=3, column=2, sticky=tkinter.W + tkinter.E, pady=2)
# set labels as stretchable
barcode_type_label.columnconfigure(0, weight=1)
size_spinbox_dpi_label.columnconfigure(0, weight=1)
size_spinbox_height_label.columnconfigure(0, weight=1)
border_spinbox_label.columnconfigure(0, weight=1)
font_size_spinbox_label.columnconfigure(0, weight=1)
input_column_spinbox_label.columnconfigure(0, weight=1)
output_column_spinbox_label.columnconfigure(0, weight=1)
# insert spinboxes into frame with grid packer
barcode_type_menu.grid(row=0, column=1)
dpi_spinbox.grid(row=1, column=1, sticky=tkinter.E, pady=2, padx=(0, 2))
height_spinbox.grid(row=2, column=1, sticky=tkinter.E, pady=2, padx=(0, 2))
border_spinbox.grid(row=3, column=1, sticky=tkinter.E, pady=2, padx=(0, 2))
pad_ean_checkbutton.grid(row=0, column=2, columnspan=2, sticky=tkinter.E)
font_size_spinbox.grid(row=1, column=3, sticky=tkinter.E, pady=2)
input_column_spinbox.grid(row=2, column=3, sticky=tkinter.E, pady=2)
output_column_spinbox.grid(row=3, column=3, sticky=tkinter.E, pady=2)
sidebar_frame = tkinter.ttk.Frame(master=root_window)
single_barcode_frame = tkinter.Frame(master=sidebar_frame)
single_barcode_frame.grid(row=0, column=1)
show_sidebar = True
def toggle_single_process_sidebar():
global show_sidebar
if show_sidebar:
single_barcode_frame.grid_remove()
show_sidebar = False
else:
single_barcode_frame.grid()
show_sidebar = True
toggle_sidebar_button = tkinter.ttk.Button(master=sidebar_frame, text=">", command=toggle_single_process_sidebar, width=1)
toggle_sidebar_button.grid(row=0, column=0, sticky=tkinter.N + tkinter.S)
toggle_single_process_sidebar()
upc_entry = tkinter.ttk.Entry(master=single_barcode_frame)
create_barcode = tkinter.ttk.Button(master=single_barcode_frame, text="Save Barcode...", command=generate_single_barcode)
upc_entry.pack()
create_barcode.pack()
process_workbook_button = tkinter.ttk.Button(master=go_button_frame, text="Select Workbooks",
command=process_workbook_command_wrapper)
process_workbook_button.configure(state=tkinter.DISABLED)
process_workbook_button.pack(side=tkinter.LEFT)
progress_bar = tkinter.ttk.Progressbar(master=progress_bar_frame)
progress_bar.pack(side=tkinter.RIGHT)
progress_numbers = tkinter.ttk.Label(master=progress_bar_frame)
progress_numbers.pack(side=tkinter.LEFT)
if flags_count != 0: # only show flags header when there is something to display
tkinter.ttk.Label(root_window, text=flags_list_string).grid(row=0, column=0, columnspan=2)
old_workbook_file_frame.pack(anchor='w', pady=2)
new_workbook_file_frame.pack(anchor='w', pady=(3, 2))
both_workbook_frame.grid(row=1, column=0, sticky=tkinter.W, padx=5, pady=5)
both_workbook_frame.columnconfigure(0, weight=1)
size_spinbox_frame.grid(row=1, column=1, sticky=tkinter.E + tkinter.N, padx=5, pady=(8, 5))
size_spinbox_frame.columnconfigure(0, weight=1)
sidebar_frame.grid(row=1, column=2, sticky=tkinter.N + tkinter.S, padx=5, pady=(8, 5))
sidebar_frame.rowconfigure(0, weight=1)
go_button_frame.pack(side=tkinter.LEFT, anchor='w')
progress_bar_frame.pack(side=tkinter.RIGHT, anchor='e')
go_and_progress_frame.grid(row=2, column=0, columnspan=2, sticky=tkinter.W + tkinter.E, padx=5, pady=5)
go_and_progress_frame.columnconfigure(0, weight=1)
root_window.columnconfigure(0, weight=1)
root_window.minsize(400, root_window.winfo_height())
root_window.resizable(width=tkinter.FALSE, height=tkinter.FALSE)
root_window.mainloop()
|
b883106af97b2fba60eefa0f2a45f5d45a3be809
|
[
"Python"
] | 1 |
Python
|
dtg01100/add_ean8_barcode_to_spreadsheet_utility
|
b24777861c637ed615ea02aa66e27c3a9c95aa37
|
49e7b5c778c111c66627d9549f642b6b4a185fc7
|
refs/heads/main
|
<repo_name>gchamon/igti-deng-cloud-proc-debate<file_sep>/candidatos-brasil.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
from spark.sql.session import SparkSession
spark = SparkSession.builder.getOrCreate()
bucket_name = "gchamon-igti-deng-cloud-proc-datalake"
# In[8]:
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 150)
# In[4]:
latin_1 = "ISO-8859-1"
cassacao = (
spark
.read
.csv(f"gs://{bucket_name}/raw/motivo_cassacao_2020_BRASIL.csv",
sep=";",
encoding=latin_1,
escape="\"",
header=True)
)
# In[5]:
cassacao.limit(1).toPandas()
# In[6]:
candidatos = (
spark
.read
.csv(f"gs://{bucket_name}/raw/consulta_cand_2020_BRASIL.csv",
sep=";",
encoding=latin_1,
escape="\"",
header=True)
)
# In[9]:
candidatos.limit(1).toPandas()
# In[10]:
bens_candidatos = (
spark
.read
.csv(f"gs://{bucket_name}/raw/bem_candidato_2020_BRASIL.csv",
sep=";",
encoding=latin_1,
escape="\"",
header=True)
)
# In[27]:
bens_candidatos.limit(1).toPandas()
# In[12]:
cassacao.write.mode("overwrite").parquet(f"gs://{bucket_name}/staging/cassacao")
candidatos.write.mode("overwrite").parquet(f"gs://{bucket_name}/staging/candidatos")
bens_candidatos.write.mode("overwrite").parquet(f"gs://{bucket_name}/staging/bens_candidatos")
# In[14]:
candidatos = (
spark
.read
.parquet(f"gs://{bucket_name}/staging/candidatos")
)
bens_candidatos = (
spark
.read
.parquet(f"gs://{bucket_name}/staging/bens_candidatos")
)
cassacao = (
spark
.read
.parquet(f"gs://{bucket_name}/staging/cassacao")
)
# In[38]:
candidatos_bens_columns = set(candidatos.columns).intersection(bens_candidatos.columns)
candidatos_bens = (
candidatos
.join(bens_candidatos, list(candidatos_bens_columns), "left")
)
candidatos_bens_cassacao_columns = set(candidatos_bens.columns).intersection(cassacao.columns)
candidatos_bens_cassacao = (
candidatos_bens
.join(cassacao, list(candidatos_bens_cassacao_columns), "left")
)
candidatos_bens_cassacao.limit(5).toPandas()
# In[32]:
candidatos_bens_cassacao.limit(5).toPandas()
# In[39]:
(
candidatos_bens_cassacao
.write
.mode("overwrite")
.partitionBy("SG_UF")
.parquet(f"gs://{bucket_name}/curated/candidatos_bens_cassacao")
)
# In[40]:
(
candidatos_bens_cassacao
.write
.mode("overwrite")
.partitionBy("SG_UF")
.csv(f"gs://{bucket_name}/human_readable/candidatos_bens_cassacao")
)
<file_sep>/up.sh
source '.env'
gcloud dataproc clusters create cluster-debate \
--enable-component-gateway \
--region us-east1 --zone us-east1-c \
--master-machine-type n1-standard-4 \
--master-boot-disk-size 500 \
--num-workers 2 \
--worker-machine-type n1-standard-4 \
--worker-boot-disk-size 500 \
--image-version 2.0-debian10 \
--optional-components JUPYTER \
--project igti-deng-cloud-proc
gsutil mb -p igti-deng-cloud-proc gs://$BUCKET_NAME
<file_sep>/down.sh
source '.env'
gcloud dataproc clusters delete cluster-debate \
--region us-east1 \
--project igti-deng-cloud-proc
gsutil rb -p igti-deng-cloud-proc gs://$BUCKET_NAME
<file_sep>/README.md
# igti-deng-cloud-proc-debate
Debate em grupo sobre consumo de dados abertos
## Pré-requisitos
- tar
- spark
- pyspark
- jupyter
## Configuração
Crie um arquivo `.env` baseado em `.env.dist` e modifique `BUCKET_NAME` com o nome do bucket alvo.
Modifique o arquivo `candidatos-brasil.py` trocando `bucket_name` para o mesmo nome configurado em `.env`.
## Criação da infraestrutura
Executar `up.sh`. O script criará o bucket do datalake e um cluster dataproc.
## Upload de arquivos crus
Executar `upload_to_gcp.sh`. O arquivo carregara os dados crus na pasta `raw` no datalake.
## Conversão de arquivos
Crie e submeta um job spark com o arquivo `candidatos-brasil.py`.
# Fonte de arquivos
Os arquivos foram baixados do site https://www.tse.jus.br/eleicoes/estatisticas/repositorio-de-dados-eleitorais-1
Incluimos um único CSV com os dados de todo o brasil.
<file_sep>/upload_to_gcp.sh
source .env
files=($(ls *.tar.gz))
for file in "${files[@]}"; do
tar -xzvf "$file"
done
gsutil cp *.csv gs://$BUCKET_NAME/raw
rm *.csv
|
bf63e5d50e14d8b05f7515682108bca3d3ab2bf0
|
[
"Markdown",
"Python",
"Shell"
] | 5 |
Python
|
gchamon/igti-deng-cloud-proc-debate
|
3d767ef0a43be475f250b92aed0a6c3888ea666c
|
cfcdf09e35b8eca528600f687977243837518687
|
refs/heads/master
|
<repo_name>nosix/AndroidMDT<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/view/WaveView.java
package jp.gr.java_conf.inosix.mdt.view;
import jp.gr.java_conf.inosix.view.RedrawHandler;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class WaveView extends View {
private final WaveViewLayout layout = new WaveViewLayout();
private final GestureDetector gesture;
private final RedrawHandler handler;
public WaveView(Context context, AttributeSet attrs) {
super(context, attrs);
gesture = new GestureDetector(getContext(), new GestureListener());
handler = new RedrawHandler(this, 1000);
handler.start();
}
public void attach(RuleView view, WaveViewSource source) {
layout.setSource(source);
view.setLayout(layout);
}
@Override
public void onDraw(Canvas canvas) {
layout.setViewSize(getWidth(), getHeight());
layout.update();
layout.onDraw(canvas);
}
public void onPause() {
handler.stop();
}
public void onResume() {
handler.start();
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (gesture.onTouchEvent(e)) {
return true;
}
return super.onTouchEvent(e);
}
private class GestureListener extends SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public void onShowPress(MotionEvent e) {
DrawArea area = layout.getDrawArea((int)e.getX(), (int)e.getY());
if (area != null && !area.getName().isEmpty()) {
Toast t =
Toast.makeText(
getContext(), area.getName(), Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP | Gravity.LEFT, 0, area.getRect().top);
t.show();
}
}
}
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/lib/DataValueListener.java
package jp.gr.java_conf.inosix.mdt.lib;
import java.util.List;
public interface DataValueListener {
void dataValueReceived(List<DataValue> values);
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/ReportReceiver.java
package jp.gr.java_conf.inosix;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class ReportReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "inosix.MDT";
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String localName = extras.getString(BluetoothAdapter.EXTRA_LOCAL_NAME);
int duration =
extras.getInt(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION);
int curState = extras.getInt(BluetoothAdapter.EXTRA_STATE);
int preState = extras.getInt(BluetoothAdapter.EXTRA_PREVIOUS_STATE);
int curScanMode = extras.getInt(BluetoothAdapter.EXTRA_SCAN_MODE);
int preScanMode =
extras.getInt(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE);
Log.d(LOG_TAG, stateToString(curState));
}
private String stateToString(int state) {
if (state == BluetoothAdapter.STATE_TURNING_ON) {
return "STATE_TURNING_ON";
}
if (state == BluetoothAdapter.STATE_ON) {
return "STATE_ON";
}
if (state == BluetoothAdapter.STATE_TURNING_OFF) {
return "STATE_TURNING_OFF";
}
if (state == BluetoothAdapter.STATE_OFF) {
return "STATE_OFF";
}
assert false;
return "";
}
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/app/DataDispatcher.java
package jp.gr.java_conf.inosix.mdt.app;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import jp.gr.java_conf.inosix.mdt.lib.DataLogger;
import jp.gr.java_conf.inosix.mdt.lib.DataValue;
import jp.gr.java_conf.inosix.mdt.lib.DataValueListener;
import jp.gr.java_conf.inosix.mdt.view.LineAttribute;
import jp.gr.java_conf.inosix.mdt.view.WaveLine;
import jp.gr.java_conf.inosix.mdt.view.WaveLineSet;
public class DataDispatcher implements DataValueListener, WaveLineSet {
private final String name;
private final DataLogger logger;
private final List<WaveLine> lines = new ArrayList<WaveLine>();
public DataDispatcher(String name) {
assert name != null;
this.name = name;
this.logger = new DataLogger();
for (LineAttribute attr : LineAttribute.values()) {
lines.add(new WaveLine(attr));
}
}
public void startDispatch() {
logger.open(name);
}
public void stopDispatch() {
logger.close();
}
@Override
public String getName() {
return name;
}
@Override
public Iterator<WaveLine> getLines() {
return lines.iterator();
}
@Override
public void dataValueReceived(List<DataValue> values) {
logger.dataValueReceived(values);
for (DataValue v : values) {
if (v.isMultiValue()) {
for (DataValue.EEGValues type : DataValue.EEGValues.values()) {
assert v.getCode() == DataValue.ASIC_EEG_POWER;
LineAttribute attr = LineAttribute.find(v.getCode(), type);
if (attr != null) {
WaveLine line = lines.get(attr.ordinal());
line.put(v.values()[type.ordinal()]);
}
}
} else {
LineAttribute attr = LineAttribute.find(v.getCode(), null);
if (attr != null) {
WaveLine line = lines.get(attr.ordinal());
line.put(v.get());
}
}
}
}
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/lib/DefaultDataValueFilter.java
package jp.gr.java_conf.inosix.mdt.lib;
public class DefaultDataValueFilter implements DataValueFilter {
@Override
public boolean accept(int code) {
switch (code) {
case DataValue.POOR_SIGNAL:
case DataValue.ATTENSION:
case DataValue.MEDITATION:
case DataValue.RAW_WAVE:
case DataValue.ASIC_EEG_POWER:
return true;
default:
assert false;
return false;
}
}
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/view/LineAttribute.java
package jp.gr.java_conf.inosix.mdt.view;
import jp.gr.java_conf.inosix.mdt.lib.DataValue;
import android.graphics.Color;
public enum LineAttribute {
POOR_SIGNAL(
"Poor Signal", Color.argb(60, 255, 255, 255),
DataValue.POOR_SIGNAL_CPS, DataValue.POOR_SIGNAL_MIN,
DataValue.POOR_SIGNAL_MAX, 0),
ATTENSION(
"Attension", Color.argb(100, 189, 247, 109), DataValue.ATTENSION_CPS,
DataValue.ATTENSION_MIN, DataValue.ATTENSION_MAX, 0),
MEDITATION(
"Meditation", Color.argb(100, 109, 224, 247), DataValue.MEDITATION_CPS,
DataValue.MEDITATION_MIN, DataValue.MEDITATION_MAX, 0),
RAW_WAVE(
"Raw Wave", Color.argb(100, 255, 255, 255), DataValue.RAW_WAVE_CPS,
DataValue.RAW_WAVE_MIN, DataValue.RAW_WAVE_MAX, 0),
EEG_DELTA(
"EEG Delta", Color.argb(80, 169, 55, 249),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_THETA(
"EEG Theta", Color.argb(80, 55, 120, 249),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_LOW_ALPHA(
"EEG Low Alpha", Color.argb(80, 55, 185, 249),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_HIGH_ALPHA(
"EEG High Alpha", Color.argb(80, 55, 249, 185),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_LOW_BETA(
"EEG Low Beta", Color.argb(80, 72, 249, 55),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_HIGH_BETA(
"EEG High Beta", Color.argb(80, 169, 249, 55),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_LOW_GAMMA(
"EEG Low Gamma", Color.argb(80, 249, 169, 55),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0),
EEG_MID_GAMMAA(
"EEG Mid Gamma", Color.argb(80, 249, 55, 55),
DataValue.ASIC_EEG_POWER_CPS, DataValue.ASIC_EEG_POWER_MIN,
DataValue.ASIC_EEG_POWER_MAX, 0);
public final String name;
public final int color;
public final int cps;
public final int min;
public final int max;
public final int defaultValue;
private LineAttribute(
String name, int color, int cps, int min, int max, int defaultValue) {
this.name = name;
this.color = color;
this.cps = cps;
this.min = min;
this.max = max;
this.defaultValue = defaultValue;
}
public static LineAttribute find(int code, DataValue.EEGValues type) {
switch (code) {
case DataValue.POOR_SIGNAL:
return LineAttribute.POOR_SIGNAL;
case DataValue.ATTENSION:
return LineAttribute.ATTENSION;
case DataValue.MEDITATION:
return LineAttribute.MEDITATION;
case DataValue.RAW_WAVE:
return LineAttribute.RAW_WAVE;
case DataValue.ASIC_EEG_POWER:
switch (type) {
case DELTA:
return LineAttribute.EEG_DELTA;
case THETA:
return LineAttribute.EEG_THETA;
case LOW_ALPHA:
return LineAttribute.EEG_LOW_ALPHA;
case HIGH_ALPHA:
return LineAttribute.EEG_HIGH_ALPHA;
case LOW_BETA:
return LineAttribute.EEG_LOW_BETA;
case HIGH_BETA:
return LineAttribute.EEG_HIGH_BETA;
case LOW_GAMMA:
return LineAttribute.EEG_LOW_GAMMA;
case MID_GAMMA:
return LineAttribute.EEG_MID_GAMMAA;
default:
return null;
}
default:
return null;
}
}
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/view/WaveViewLayout.java
package jp.gr.java_conf.inosix.mdt.view;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
class WaveViewLayout {
private static final Rect MARGIN = new Rect(5, 5, 5, 5);
private static final Rect PADDING = new Rect(0, 5, 0, 5);
private final List<DrawArea> areas = new ArrayList<DrawArea>();
private final List<GraphicLine> lines = new ArrayList<GraphicLine>();
private WaveViewSource source = new LayoutSourceNull();
private Point viewSize = new Point(0, 0);
private boolean isUpdated = true;
void setSource(WaveViewSource source) {
this.source = source;
}
void setViewSize(int width, int height) {
if (viewSize.x != width || viewSize.y != height) {
viewSize = new Point(width, height);
isUpdated = true;
}
}
boolean equalsSize(int width, int height) {
return viewSize.x == width && viewSize.y == height;
}
void update() {
if (isUpdated == false)
return;
isUpdated = false;
initDrawArea();
initMap();
}
private void initDrawArea() {
areas.clear();
for (int i = 0; i < source.getNumOfDrawArea(); i++) {
areas.add(new DrawArea(area(i), source.getTimeFrame(), source
.getDrawAreaAttr(i)));
}
}
private Rect area(int index) {
int height =
(viewSize.y - getSpaceHeight()) / source.getNumOfDrawArea();
int left = MARGIN.left + PADDING.left;
int right = viewSize.x - (MARGIN.right + PADDING.right);
int top =
MARGIN.top + PADDING.top * (index + 1) + (PADDING.bottom + height)
* index;
int bottom = top + height;
return new Rect(left, top, right, bottom);
}
private int getSpaceHeight() {
return MARGIN.top + MARGIN.bottom + (PADDING.top + PADDING.bottom)
* source.getNumOfDrawArea();
}
private void initMap() {
lines.clear();
Iterator<WaveLineSet> lsi = source.getLineSet();
while (lsi.hasNext()) {
WaveLineSet lineSet = lsi.next();
Iterator<WaveLine> li = lineSet.getLines();
while (li.hasNext()) {
WaveLine line = li.next();
int areaIndex = source.getAreaIndex(lineSet, line.attr);
if (areaIndex >= 0) {
line.setTimeFrame(source.getTimeFrame());
lines.add(new GraphicLine(
line, areas.get(areaIndex), source.getLineColor(
lineSet, line.attr)));
}
}
}
}
Iterator<DrawArea> getDrawAreas() {
return areas.iterator();
}
DrawArea getDrawArea(int x, int y) {
for (DrawArea area : areas) {
if (area.getRect().contains(x, y)) {
return area;
}
}
return null;
}
void onDraw(Canvas canvas) {
for (int t = 0; t < source.getTimeFrame(); t++) {
for (GraphicLine l : lines) {
l.line.onDraw(canvas, l.area, l.paint, t);
}
}
}
private static class GraphicLine {
final WaveLine line;
final DrawArea area;
final Paint paint;
GraphicLine(WaveLine line, DrawArea area, int color) {
this.line = line;
this.area = area;
this.paint = new Paint();
paint.setStrokeWidth(3);
paint.setColor(color);
}
}
private static class LayoutSourceNull implements WaveViewSource {
private List<WaveLineSet> lineSet = new ArrayList<WaveLineSet>();
@Override
public Iterator<WaveLineSet> getLineSet() {
return lineSet.iterator();
}
@Override
public int getTimeFrame() {
return 0;
}
@Override
public int getNumOfDrawArea() {
return 0;
}
@Override
public DrawAreaAttr getDrawAreaAttr(int i) {
return null;
}
@Override
public int getAreaIndex(WaveLineSet lineSet, LineAttribute attr) {
return 0;
}
@Override
public int getLineColor(WaveLineSet lineSet, LineAttribute attr) {
return 0;
}
}
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/app/AndroidMDTActivity.java
package jp.gr.java_conf.inosix.mdt.app;
import java.util.ArrayList;
import java.util.List;
import jp.gr.java_conf.inosix.R;
import jp.gr.java_conf.inosix.app.SelectBluetoothDeviceActivity;
import jp.gr.java_conf.inosix.mdt.LogTag;
import jp.gr.java_conf.inosix.mdt.lib.BluetoothService;
import jp.gr.java_conf.inosix.mdt.lib.DataValue;
import jp.gr.java_conf.inosix.mdt.lib.DataValueFilter;
import jp.gr.java_conf.inosix.mdt.lib.ThinkGearParser;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
public class AndroidMDTActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_SELECT_BT = 1;
private final List<DataDispatcher> dispatchers =
new ArrayList<DataDispatcher>();
private BluetoothService btService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((LogTag.MASK & LogTag.FLAG_MDT_ACTIVITY) != 0)
Log.d(LogTag.S, "AndroidMDTActivity onCreate.");
setContentView(R.layout.main);
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(new WaveViewPagerAdapter(this, dispatchers));
initBluetooth();
}
private void initBluetooth() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
Log.w(LogTag.S, "Bluetooth is not supported.");
return;
}
if ((LogTag.MASK & LogTag.FLAG_MDT_ACTIVITY) != 0)
Log.d(LogTag.S, "Bluetooth is supported.");
if (!adapter.isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, REQUEST_ENABLE_BT);
} else {
connectDevice();
}
}
private void connectDevice() {
if ((LogTag.MASK & LogTag.FLAG_MDT_ACTIVITY) != 0)
Log.d(LogTag.S, "Connect bluetooth device...");
Intent i =
new Intent(
AndroidMDTActivity.this, SelectBluetoothDeviceActivity.class);
startActivityForResult(i, REQUEST_SELECT_BT);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
if ((LogTag.MASK & LogTag.FLAG_MDT_ACTIVITY) != 0)
Log.d(LogTag.S, "Bluetooth has been enabled.");
connectDevice();
return;
}
if (resultCode == RESULT_CANCELED) {
if ((LogTag.MASK & LogTag.FLAG_MDT_ACTIVITY) != 0)
Log.d(LogTag.S, "Bluetooth has not been enabled.");
return;
}
assert false;
}
if (requestCode == REQUEST_SELECT_BT) {
if (resultCode == RESULT_OK) {
assert btService == null;
List<BluetoothDevice> devices =
data.getParcelableArrayListExtra(SelectBluetoothDeviceActivity.EXTRA_NAME_DEVICES);
startObservation(devices);
return;
}
if (resultCode == RESULT_CANCELED) {
if ((LogTag.MASK & LogTag.FLAG_MDT_ACTIVITY) != 0)
Log.d(LogTag.S, "Bluetooth device can't select.");
return;
}
assert false;
}
}
private void startObservation(List<BluetoothDevice> devices) {
btService = new BluetoothService();
for (BluetoothDevice dev : devices) {
DataDispatcher dispatcher = new DataDispatcher(dev.getAddress());
dispatchers.add(dispatcher);
ThinkGearParser parser =
new ThinkGearParser(createDataValueFilter());
parser.addDataValueListener(dispatcher);
dispatcher.startDispatch();
btService.connect(dev, parser);
}
}
private DataValueFilter createDataValueFilter() {
return new DataValueFilter() {
@Override
public boolean accept(int code) {
switch (code) {
case DataValue.POOR_SIGNAL:
case DataValue.ATTENSION:
case DataValue.MEDITATION:
case DataValue.RAW_WAVE:
case DataValue.ASIC_EEG_POWER:
return true;
default:
return false;
}
}
};
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
if (btService != null) {
btService.stop();
btService = null;
}
for (DataDispatcher d : dispatchers) {
d.stopDispatch();
}
dispatchers.clear();
}
}<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/view/WaveLineSet.java
package jp.gr.java_conf.inosix.mdt.view;
import java.util.Iterator;
public interface WaveLineSet {
String getName();
Iterator<WaveLine> getLines();
}
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/view/WaveLine.java
package jp.gr.java_conf.inosix.mdt.view;
import android.graphics.Canvas;
import android.graphics.Paint;
public class WaveLine {
final LineAttribute attr;
private int[] values;
private int index;
public WaveLine(LineAttribute attr) {
assert attr != null;
this.attr = attr;
initValuesArray(0);
}
private void initValuesArray(int size) {
values = new int[size + 1];
}
void setTimeFrame(int second) {
initValuesArray(attr.cps * second);
for (int i = 0; i < values.length; i++) {
values[i] = attr.defaultValue;
}
index = 0;
}
public void put(int value) {
values[index++] = value;
index = index % values.length;
}
void onDraw(Canvas canvas, DrawArea area, Paint paint, int timeIndex) {
assert (timeIndex < values.length / attr.cps - 1);
int x0 = timeIndex * attr.cps;
int y0 = values[getIndex(x0)];
while (x0 < (timeIndex + 1) * attr.cps) {
int x1 = x0 + 1;
int y1 = values[getIndex(x1)];
canvas.drawLine(
area.x(xr(x0)), area.y(yr(y0)), area.x(xr(x1)), area.y(yr(y1)),
paint);
x0 = x1;
y0 = y1;
}
}
private int getIndex(int x) {
return (index + x) % values.length;
}
private float xr(int x) {
return (float)x / (values.length - 1);
}
private float yr(int y) {
return (float)(y - attr.min) / (attr.max - attr.min);
}
}
<file_sep>/AndroidMDT/TODO.txt
- 波ごとの表示/非表示
- 保存してネット経由でアップする
- 各波形の縮尺を変更
- タップで選択して各波毎に表示する
- 最大表示時間を変更できるようにする
- 拡大/縮小
- 他のアプリからイベントの記録を受け取る
- 他のアプリにデータを提供する
- DataLogger のイベント記録に時刻情報を追加
- パフォーマンスチューニング
- データが欠損した場合、横がずれる
- データの欠損はない(定時でデータが届く)前提とする
- 初回起動時に表示されないことがある
<file_sep>/AndroidMDT/src/jp/gr/java_conf/inosix/mdt/view/DrawAreaAttr.java
package jp.gr.java_conf.inosix.mdt.view;
import android.graphics.Color;
class DrawAreaAttr {
private final int color;
private final String name;
DrawAreaAttr(int color, String name) {
this.color = color;
this.name = name;
}
int getColor(int alpha) {
return Color.argb(
(Color.alpha(color) * alpha) / 100, Color.red(color),
Color.green(color), Color.blue(color));
}
String getName() {
return name;
}
}
|
ffa6414970cd52e46bb9296f7d17f060a20265cf
|
[
"Java",
"Text"
] | 12 |
Java
|
nosix/AndroidMDT
|
611af83b594325e539df8909a50f91a0281dcad8
|
11775875fdfad99b8de48b6559d88dfe8edd6cb6
|
refs/heads/master
|
<file_sep># Practice
활용
<file_sep>#include<stdio.h>
int main(void)
{
int x, y, k, iHeight;
/*****************
x = 폭
y = 높이
k = 시작점
*****************/
printf_s("입력 : ");
scanf_s("%d", &iHeight);
k = iHeight - 2;
for (y = 0; y < iHeight; y++)
{
int i = 0;
for (x = 0; x < iHeight + y; x++)
{
if (x > k)
{
printf_s("%c", (i + 65));
if ((iHeight - 1) <= x)
i--;
else
i++;
}
else
printf_s(" ");
}
k--;
printf_s("\n");
}
return 0;
}<file_sep>#include<stdio.h>
int main(void)
{
int width, high, thick;
while (true)
{
printf("너비를 입력하시오. ");
scanf("%d", &width);
if (width > 0 && width < 21)
break;
}
while (true)
{
printf("높이를 입력하시오. ");
scanf("%d", &high);
if (high > 0 && high < 21)
break;
}
while (true)
{
printf("두께를 입력하시오. ");
scanf("%d", &thick);
if ((width / 2) >= thick && (high / 2) >= thick)
break;
}
for (int i = 0; i < high; ++i)
{
for (int j = 0; j < width; ++j)
{
if (j < thick || (width - thick) <= j || i < thick || (high - thick) <= i)
{
printf("*");
}
else
printf(" ");
}
printf("\n");
}
return 0;
}
/*
while (true)
{
system("cls");
int iWidth, iHeight, iCount = 0;
int t = 0; // 벽 두께
while (true)
{
switch (iCount)
{
case 0:
printf_s("너비를 입력하시오. ");
scanf_s("%d", &iWidth);
if (iWidth > 0 && iWidth < 21)
iCount++;
break;
case 1:
printf_s("높이를 입력하시오. ");
scanf_s("%d", &iHeight);
if (iHeight > 0 && iHeight < 21)
iCount++;
break;
case 2:
printf_s("두께를 입력하시오. ");
scanf_s("%d", &t);
if ((iWidth / 2) >= t && (iHeight / 2) >= t)
iCount++;
break;
}
if (iCount >= 3)
break;
}
//** 입력한 높이 값만큼 반복
for (int i = 0; i < iHeight; i++)
{
//** 입력한 폭 만큼 반복
for (int j = 0; j < iWidth; j++)
{
//** 만약
if (i < t || //** 현재 높이가 벽두께보다 작다면
//** (최대높이 - 두께) 값보다 현재높이가 클때
i >= iHeight - t ||
j < t || //** 현재 폭이 벽두께보다 작다면
//** (최대폭 - 두께) 값보다 현재폭이 클때
j >= iWidth - t)
//** 위 조건중 하나라도 만족한다면
printf_s("*"); //** 별을
else //** 아니면
printf_s(" "); //** 공백을 출력
}
printf_s("\n");
}
system("pause");
return 0;
}
*/
|
61f47b693627baaaa20356576514acf60d6d860a
|
[
"Markdown",
"C++"
] | 3 |
Markdown
|
khw9905/Practice
|
745ca2262024cdb811463901df4cab09c18992e5
|
8a398a66bfcbcf79701f38cdcfb53017459861de
|
refs/heads/master
|
<repo_name>ergovia-devs/grunt-properties-reader<file_sep>/tasks/properties_reader.js
/*
* grunt-properties-reader
* https://github.com/slawrence/grunt-properties-reader
*
* Copyright (c) 2013 <NAME>
* Licensed under the MIT license.
*/
'use strict';
/**
* If a string is "true" "TRUE", or " TrUE" convert to boolean type else
* leave as is
*/
function _convertStringIfTrue(original) {
var str;
if (original && typeof original === "string") {
str = original.toLowerCase().trim();
return (str === "true" || str === "false") ? (str === "true") : original;
}
return original;
}
/**
* Convert property-strings into a json object.
*
* Nested properties will be converted to nested objects and parseable numeric values to int.
*
*/
function convertPropsToJson(text) {
var configObject = {};
if (text && text.length) {
// handle multi-line values terminated with a backslash
text = text.replace(/\\\r?\n\s*/g, '');
text.split(/\r?\n/g).forEach(function (line) {
var props,
name,
val;
line = line.trim();
if (line && line.indexOf("#") !== 0 && line.indexOf("!") !== 0) {
props = line.split(/\=(.+)?/);
var nestedProperties = props[0].split('.');
// if the current property-line is a nested path then objectify it
if (nestedProperties.length > 1) {
var data = configObject,
i;
while(nestedProperties.length) {
i = nestedProperties.shift().trim();
if (nestedProperties.length) {
if (!data.hasOwnProperty(i)) {
// If the current nested property (i) is not in our datastructure, add it
data[i] = {};
}
data = data[i];
} else {
val = props[1] && props[1].trim();
data[i] = isNaN(val) ? val : parseInt(val, 10);
}
}
} else {
name = props[0] && props[0].trim();
val = props[1] && props[1].trim();
configObject[name] = isNaN(val) ? _convertStringIfTrue(val) : parseInt(val, 10);
}
}
});
}
// console.log(configObject);
return configObject;
}
/**
* Merges the source-file into the target-file
*
* @param {object} target the destination-object, where all keys from the source will be added
* @param {object} source the source-object, which will be merged into the target file
* @returns {object} the target-object with the merged keys and values
*/
function merge(target, source) {
if (!source) {
return target;
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
return target;
}
/**
* Converts the given value to an array
*
* @param {string} value the value which should be put into a new array
*
* @returns {Array} an empty array, if the value is null
* the value itself, if the value is an array already
* a new array with the given value, if the value is from another type
*/
function convertToArray(value) {
if (!value) {
return [];
}
if (value instanceof Array) {
return value;
}
return [ value ];
}
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('properties',
'Reads values from one or more Java style properties into the specified variable',
function() {
var readFile = function(filename, readOptions) {
return grunt.file.exists(filename) && grunt.file.read(filename, readOptions);
};
// Merge task-specific and/or target-specific options with these defaults.
if (grunt.config.get(this.target)) {
grunt.log.error("Conflict - property, " + this.target + ", already exists in grunt config");
return false;
}
var filenames = convertToArray(this.data);
var parsed = {};
for (var i=0; i < filenames.length; i++) {
var filename = filenames[i];
var file = readFile(filename, this.options);
// Only require the first file ...
if (!file && i === 0) {
grunt.log.error("Could not read required properties file: " + filename);
return false;
} else if (!file) {
grunt.log.warn("Could not read optional properties file: " + filename);
}
parsed = merge(parsed, convertPropsToJson(file));
}
grunt.config.set(this.target, parsed);
});
};
|
424ab228f240e198731169aae72d36152d1a6fa5
|
[
"JavaScript"
] | 1 |
JavaScript
|
ergovia-devs/grunt-properties-reader
|
fd42f28eac4c25f30097304a5a9996c0549c1e99
|
c62f2aa0500f322ebe60fdf226140739d3836786
|
refs/heads/master
|
<repo_name>congncif/SiFUtilities<file_sep>/Foundation/Bundle++.swift
//
// Bundle++.swift
// SiFUtilities
//
// Created by <NAME> on 2/15/19.
//
import Foundation
public extension Bundle {
static var appVersion: String? {
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
static var buildNumber: String? {
Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
}
}
<file_sep>/CHANGELOG.md
# Change Log
All notable changes to this project will be documented in this file.
#### 3.x Releases
- `3.9.x` Releases - [3.9.0](#390) | [3.9.1](#391) | [3.9.2](#392)
- `3.8.x` Releases - [3.8.0](#380)
- `3.7.x` Releases - [3.7.0](#370) | [3.7.1](#371) | [3.7.2](#372)
---
## [3.9.2](https://github.com/congncif/SiFUtilities/releases/tag/3.9.2)
Released on 2018-4-8
#### Updated
- KeyValueProtocol: add stringDictionary which returns [String: String] instead of [String: Any]
## [3.9.1](https://github.com/congncif/SiFUtilities/releases/tag/3.9.1)
Released on 2018-4-7
#### Updated
- Rename type to resolve conflicts
## [3.9.0](https://github.com/congncif/SiFUtilities/releases/tag/3.9.0)
Released on 2018-4-7
#### Added
- Added WeakReferenceProtocol
- Added modern TypeNameProtocol
#### Updated
- Allow override UITextField leftPadding, rightPadding
- Updated show alert, prevent show multiple alerts
## [3.8.0](https://github.com/congncif/SiFUtilities/releases/tag/3.8.0)
Released on 2018-4-6
#### Added
- Added array safe subscript method
- Added array chunk func to split array
- Added func Get next element of array
- Common elements in two arrays
- Added Sequence group func
- Added UINavigationBar utils: transparent(), opaque()
- Apply gradient to Navigation Bar
- Added UITextField left/right padding
- Split String into words
## [3.7.2](https://github.com/congncif/SiFUtilities/releases/tag/3.7.2)
Released on 2018-4-6
#### Updated
- Removed unused code: protocol PropertyNames
## [3.7.1](https://github.com/congncif/SiFUtilities/releases/tag/3.7.1)
Released on 2018-4-6
#### Fixed
- Support XCode 9.2, Swift 4.0: Swizzling -> types.deallocate()
## [3.7.0](https://github.com/congncif/SiFUtilities/releases/tag/3.7.0)
Released on 2018-4-5
#### Added
- Added a sugar present view controller method with embedIn navigation option
#### Added
- Initial release of SiFUtilities.
- Added by [<NAME>](https://github.com/congncif).
<file_sep>/Foundation/String+Name.swift
//
// String+Name.swift
//
//
// Created by <NAME> on 12/25/20.
//
import Foundation
extension String {
public static func moduleName(for anClass: AnyClass) -> String {
guard let name = String(reflecting: anClass).split(separator: ".").first else {
assertionFailure("You are in this case because Swift.String(reflecting:) API was broken. Will fallback to subject name in release configuration.")
return String(describing: anClass)
}
return String(name)
}
}
<file_sep>/Example/SiFUtilities/LastViewController.swift
//
// LastViewController.swift
// SiFUtilities_Example
//
// Created by <NAME> on 8/18/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import SiFUtilities
import UIKit
final class LastViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction private func returnButtonDidTap() {
// let root = (UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController as? UINavigationController
// root?.rootViewController?.returnHere(animated: true) {
// let exVC = EXViewController.instantiateFromMainStoryboard()
// root?.show(exVC, configurations: { $0.style = .defaultPresent })
// }
}
}
<file_sep>/Localize/UITextField+Localize.swift
//
// UITextField+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
// @IBDesignable
extension UITextField {
@IBInspectable public var placeholderLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedPlaceholderTextKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedPlaceholderTextKey)
}
}
@IBInspectable public var textLocalizedKey: String? {
get {
return getAssociatedObject(key: &RunTimeKey.localizedTextKey)
}
set {
if let value = newValue, !newValue.isNoValue {
setAssociatedObject(key: &RunTimeKey.localizedTextKey, value: value)
registerLocalizeUpdateNotification()
}
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let text = attributes[.localizedTextKey]?.localized {
self.text = text
}
if let text = attributes[.localizedPlaceholderTextKey]?.localized {
placeholder = text
}
}
@objc override open func updateLanguage() {
if let key = textLocalizedKey {
updateLocalize(attributes: [.localizedTextKey: key])
}
if let key = placeholderLocalizedKey {
updateLocalize(attributes: [.localizedPlaceholderTextKey: key])
}
}
}
<file_sep>/Foundation/Codable/JSONCodable.swift
//
// JSONCodable.swift
//
//
// Created by <NAME> on 12/18/20.
//
import Foundation
public protocol JSONDecodable {
init(from jsonData: Data) throws
init(from jsonString: String) throws
}
public protocol JSONEncodable {
func encodeData() throws -> Data
}
public extension JSONDecodable where Self: Decodable {
init(from jsonData: Data) throws {
self = try JSONDecoder().decode(Self.self, from: jsonData)
}
init(from jsonString: String) throws {
guard let data = jsonString.data() else {
throw NSError(domain: "JSONDecodable.jsonString.invalid", code: 0, userInfo: [NSLocalizedDescriptionKey: "Cannot convert json string to data"])
}
try self.init(from: data)
}
}
public extension JSONEncodable where Self: Encodable {
func encodeData() throws -> Data {
try JSONEncoder().encode(self)
}
}
<file_sep>/Helpers/FittingView.swift
//
// FittingView.swift
// SiFUtilities
//
// Created by <NAME> on 8/8/18.
// Copyright © 2019 <NAME>. All rights reserved.
//
import CoreGraphics
import Foundation
import UIKit
public enum FittingContentHeight: Equatable {
case autoSizing
case explicit(CGFloat)
public static func == (lhs: FittingContentHeight, rhs: FittingContentHeight) -> Bool {
switch (lhs, rhs) {
case (.autoSizing, .autoSizing):
return true
case let (.explicit(lhsHeight), .explicit(rhsHeight)):
return lhsHeight == rhsHeight
default:
return false
}
}
}
protocol ContentFitting: UIView {
var fittingHeight: FittingContentHeight { get set }
}
extension ContentFitting {
func adjustContentHeight(_ contentHeight: FittingContentHeight) {
guard contentHeight != fittingHeight else { return }
fittingHeight = contentHeight
invalidateIntrinsicContentSize()
layoutIfNeeded()
DispatchQueue.main.async {
self.closestContainerTableView?.performUpdates()
}
}
}
// MARK: - FittingView
open class FittingView: UIView, ContentFitting {
var fittingHeight: FittingContentHeight = .autoSizing
override open var intrinsicContentSize: CGSize {
switch fittingHeight {
case .autoSizing:
let contentSize = super.intrinsicContentSize
if contentSize.height == 0 {
return CGSize(width: contentSize.width, height: CGFloat.leastNonzeroMagnitude)
}
return contentSize
case let .explicit(height):
return CGSize(width: bounds.size.width, height: height)
}
}
public func updateHeight(_ contentHeight: FittingContentHeight) {
adjustContentHeight(contentHeight)
}
}
// MARK: - FittingTableView
open class FittingTableView: UITableView, ContentFitting {
private var observation: NSKeyValueObservation?
var fittingHeight: FittingContentHeight = .autoSizing
func registerContentSizeObserver() {
observation = contentSizeObservation
}
override public init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
registerContentSizeObserver()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
registerContentSizeObserver()
}
deinit {
if #available(iOS 11.0, *) {
observation?.invalidate()
observation = nil
} else if let observer = observation {
removeObserver(observer, forKeyPath: "contentSize")
}
}
override open var intrinsicContentSize: CGSize {
switch fittingHeight {
case .autoSizing:
return contentSize
case let .explicit(height):
return CGSize(width: bounds.size.width, height: height)
}
}
public func updateHeight(_ contentHeight: FittingContentHeight) {
adjustContentHeight(contentHeight)
}
}
// MARK: - FittingCollectionView
open class FittingCollectionView: UICollectionView, ContentFitting {
private var observation: NSKeyValueObservation?
var fittingHeight: FittingContentHeight = .autoSizing
func registerContentSizeObserver() {
observation = contentSizeObservation
}
override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
registerContentSizeObserver()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
registerContentSizeObserver()
}
deinit {
if #available(iOS 11.0, *) {
observation?.invalidate()
observation = nil
} else if let observer = observation {
removeObserver(observer, forKeyPath: "contentSize")
}
}
override open var intrinsicContentSize: CGSize {
switch fittingHeight {
case .autoSizing:
return contentSize
case let .explicit(height):
return CGSize(width: bounds.size.width, height: height)
}
}
public func updateHeight(_ contentHeight: FittingContentHeight) {
adjustContentHeight(contentHeight)
}
}
// MARK: - FittingScrollView
open class FittingScrollView: UIScrollView, ContentFitting {
private var observation: NSKeyValueObservation?
var fittingHeight: FittingContentHeight = .autoSizing
func registerContentSizeObserver() {
observation = contentSizeObservation
}
override public init(frame: CGRect) {
super.init(frame: frame)
registerContentSizeObserver()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
registerContentSizeObserver()
}
deinit {
if #available(iOS 11.0, *) {
observation?.invalidate()
observation = nil
} else if let observer = observation {
removeObserver(observer, forKeyPath: "contentSize")
}
}
override open var intrinsicContentSize: CGSize {
switch fittingHeight {
case .autoSizing:
return contentSize
case let .explicit(height):
return CGSize(width: bounds.size.width, height: height)
}
}
public func updateHeight(_ contentHeight: FittingContentHeight) {
adjustContentHeight(contentHeight)
}
}
// MARK: - Extensions
extension UIScrollView {
var contentSizeObservation: NSKeyValueObservation {
observe(\.contentSize, options: [.old, .new]) { object, change in
let oldValue = change.oldValue
let newValue = change.newValue
if oldValue?.height != newValue?.height {
object.invalidateIntrinsicContentSize()
object.closestContainerTableView?.performUpdates()
}
}
}
}
public extension UIView {
var closestContainerTableView: UITableView? {
if let tableView = superview as? UITableView {
return tableView
} else {
return superview?.closestContainerTableView
}
}
}
private var animationKey: UInt8 = 1
extension UITableView {
public var resizingAnimationEnabled: Bool {
set {
objc_setAssociatedObject(self, &animationKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
get {
objc_getAssociatedObject(self, &animationKey) as? Bool ?? true
}
}
public func performUpdates(_ updates: (() -> Void)? = nil) {
if resizingAnimationEnabled {
beginUpdates()
updates?()
endUpdates()
} else {
UIView.performWithoutAnimation {
beginUpdates()
updates?()
endUpdates()
}
}
}
}
<file_sep>/Foundation/Data/DataConvert.swift
//
// DataConvert.swift
//
//
// Created by <NAME> on 12/18/20.
//
import Foundation
extension String {
public func data() -> Data? {
data(using: .utf8)
}
public func jsonDictionary(encoding: String.Encoding = .utf8) -> [String: Any]? {
data(using: encoding)?.jsonDictionary()
}
public func jsonArray(encoding: String.Encoding = .utf8) -> [Any]? {
data(using: encoding)?.jsonArray()
}
}
extension Data {
public func string(encoding: String.Encoding = .utf8) -> String? {
String(data: self, encoding: encoding)
}
public func jsonDictionary() -> [String: Any]? {
try? JSONSerialization.jsonObject(with: self, options: []) as? [String: Any]
}
public func jsonArray() -> [Any]? {
try? JSONSerialization.jsonObject(with: self, options: []) as? [Any]
}
}
extension Array {
public func jsonData() throws -> Data {
try JSONSerialization.data(withJSONObject: self, options: [])
}
public func jsonString(encoding: String.Encoding = .utf8) -> String? {
try? jsonData().string(encoding: encoding)
}
}
extension Dictionary {
public func jsonData() throws -> Data {
try JSONSerialization.data(withJSONObject: self, options: [])
}
public func jsonString(encoding: String.Encoding = .utf8) -> String? {
try? jsonData().string(encoding: encoding)
}
}
<file_sep>/Example/Podfile
platform :ios, "11.0"
use_frameworks!
target 'SiFUtilities_Example' do
pod 'SiFUtilities' , :path => '../'
pod 'SiFUtilities/Localize' , :path => '../'
end
<file_sep>/Localize/UIViewController+Localize.swift
//
// UIViewController+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
// @IBDesignable
extension UIViewController {
@IBInspectable public var titleLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedTitleKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedTitleKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let value = attributes[.localizedTitleKey]?.localized {
title = value
}
}
@objc override open func updateLanguage() {
if let key = titleLocalizedKey {
updateLocalize(attributes: [.localizedTitleKey: key])
}
}
}
<file_sep>/Example/SiFUtilities/ViewController.swift
//
import Localize_Swift
// ViewController.swift
// SiFUtilities
//
// Created by <NAME> on 05/29/2016.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
import SiFUtilities
import UIKit
class Test: KeyValueProtocol {
var name: String?
var address: String?
var mapKeys: [String: String] {
return ["name": "nameMapped"]
}
func transformKey(for mapKey: String) -> String {
return mapKey.snakeCased()
}
}
class Test2: Test {
var age: Int?
override var mapKeys: [String: String] {
var keys = super.mapKeys
keys["age"] = "ageMapped"
return keys
}
}
class AdAttribute: KeyValueProtocol {
var id: String = ""
var scope: String = "XPFeedScope.global.rawValue"
var type: String = "XPFeedType.event.rawValue"
var title: String?
}
class Test3: NSObject, KeyValueProtocol {
var test2 = Test2()
var attr = AdAttribute()
}
protocol NewEndPoint: EndpointProtocol {}
extension NewEndPoint {
public static var base: String { return "https://sif.vn" }
}
// extension EndpointProtocol {
// public static var base: String { return "https://sif.vn" }
// }
public enum APIEndpoint: String, NewEndPoint {
public static var root = String()
case login
enum work: String, NewEndPoint {
public static var root = "work"
case examEp = "exam_ep"
case cool = "cool/%d"
case xxx = "xxx/%@/abc/%d"
}
enum newpp: String, NewEndPoint {
public static var root = "newpp"
static var base: String {
return "ftp://aba.com"
}
case example
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let x = "test_abc_uou"
print(x.camelCased())
print(x.snakeCased())
let test = Test()
test.name = "clgt"
test.address = "HN"
print(test.dictionary)
// print(test.JSONString!)
// let test2 = Test2()
// test2.name = "XXX"
// test2.address = "SG"
//
// let test3 = Test3()
// test3.test2 = test2
// test3.attr = AdAttribute()
//
// print(test3.dictionary)
// print(test3.JSONString!)
print("XXX==> " + APIEndpoint.login.path())
print("New path " + APIEndpoint.work.cool.path(123))
print("XXX path " + APIEndpoint.work.xxx.path("abc", 123))
print("XXX path " + APIEndpoint.work.path())
print("XXX path " + APIEndpoint.newpp.path())
}
override func viewDidDisplay() {
// DispatchQueue.global().async {
// let v = self.value()
// print(v)
// }
// print(typeName)
// print(weakSelf() as Any)
//
print("---> Did Display")
}
override func viewDidResume() {
print("---> Did Resume")
}
override func viewWillDisplay() {
print("---> Will Display")
}
override func viewWillResume() {
print("---> Will Resume")
}
override func viewDidFinishInitialLayout() {
print("---> init layout")
}
override func viewDidFinishRefreshLayout() {
print("---> refresh layout")
}
// func
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("---> Did Appear")
// let blur = UIBlurEffect(style: UIBlurEffectStyle.light)
// let blurView = UIVisualEffectView(effect: blur)
//
// DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
// self.view.showLoading(overlayView: blurView)
// }
// DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
// self.view.hideLoading()
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func value() -> String? {
let keeper = ValueKeeper<String>(defaultValue: "Default") { completion in
DispatchQueue.global().asyncAfter(deadline: .now() + 10) {
completion("Test")
}
}
return keeper.syncValue
}
@IBOutlet var label: UILabel!
@IBAction func tap() {
// let vc = EXViewController.instantiateFromMainStoryboard()
// vc.showOverlay(on: self, animation: { v in
// v.moveInFromLeft()
// })
// present(vc, embedIn: NavViewController.self)
print(Localize.availableLanguages())
Localize.setCurrentLanguage("vi-VN")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
}
}
<file_sep>/Localize/UITextView+Localize.swift
//
// UITextView+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
// @IBDesignable
extension UITextView {
@IBInspectable public var textLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedTextKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedTextKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let text = attributes[.localizedTextKey]?.localized {
self.text = text
}
}
@objc override open func updateLanguage() {
if let key = textLocalizedKey {
updateLocalize(attributes: [.localizedTextKey: key])
}
}
}
<file_sep>/Localize/UITabBarItem+Localize.swift
//
// UITabBarItem+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
// @IBDesignable
extension UITabBarItem {
@IBInspectable public var titleLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedTitleKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedTitleKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let text = attributes[.localizedTitleKey]?.localized {
title = text
}
}
@objc override open func updateLanguage() {
if let key = titleLocalizedKey {
updateLocalize(attributes: [.localizedTitleKey: key])
}
}
}
<file_sep>/Runtime/StoryboardSegue+Sender.swift
//
// StoryboardSegue+Sender.swift
//
//
// Created by <NAME> on 9/15/19.
//
import Foundation
import UIKit
private var senderKey: UInt8 = 11
extension UIStoryboardSegue {
public var sender: Any? {
set {
setAssociatedObject(key: &senderKey, value: newValue)
}
get {
let value: Any? = getAssociatedObject(key: &senderKey)
return value
}
}
}
<file_sep>/UIKit/UIImage++.swift
//
// UIImage++.swift
// SiFUtilities
//
// Created by FOLY on 9/22/18.
//
import Foundation
import UIKit
// MARK: - UIImage from color
extension UIImage {
public class func image(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
// MARK: - UIImage Compression
public enum ImageCompressionType {
case jpeg(quality: Double)
case png
}
public extension UIImage {
func compressedData(type: ImageCompressionType = .jpeg(quality: 0.33), boundary: CGFloat? = 1280) -> Data? {
let size = self.fittedSize(boundary: boundary)
let resizedImage = boundary == nil ? self : self.resized(targetSize: size)
var data: Data?
switch type {
case let .jpeg(quality):
data = resizedImage?.jpegData(compressionQuality: quality)
case .png:
data = resizedImage?.pngData()
}
return data
}
func compressedIfNeeded(type: ImageCompressionType = .jpeg(quality: 0.33), boundary: CGFloat? = 1280) -> UIImage {
guard let data = compressedData(type: type, boundary: boundary) else {
print("⚠️ Image Compression failed ➤ Return original image")
return self
}
guard let image = UIImage(data: data) else {
#if DEBUG
print("⚠️ Image Compression cannot render new image ➤ Return original image")
#endif
return self
}
return image
}
/**
Zoom the picture to the specified size
- parameter newSize: image size
- returns: new image
*/
func resized(targetSize: CGSize) -> UIImage? {
let newRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
var newImage: UIImage?
UIGraphicsBeginImageContext(newRect.size)
newImage = UIImage(cgImage: self.cgImage!, scale: 1, orientation: self.imageOrientation)
newImage?.draw(in: newRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
private func fittedSize(boundary: CGFloat?) -> CGSize {
var width = self.size.width
var height = self.size.height
guard let boundary = boundary else {
return CGSize(width: width, height: height)
}
// width, height <= boundary, Size remains the same
guard width > boundary || height > boundary else {
return CGSize(width: width, height: height)
}
// aspect ratio
let s = max(width, height) / min(width, height)
if s <= 2 {
// Set the larger value to the boundary, the smaller the value of the compression
let x = max(width, height) / boundary
if width > height {
width = boundary
height = height / x
} else {
height = boundary
width = width / x
}
} else {
// width, height > boundary
if min(width, height) >= boundary {
// Set the smaller value to the boundary, and the larger value is compressed
let x = min(width, height) / boundary
if width < height {
width = boundary
height = height / x
} else {
height = boundary
width = width / x
}
}
}
return CGSize(width: width, height: height)
}
}
<file_sep>/UIKit/UIViewController+Access.swift
//
// UIViewController+Top.swift
// SiFUtilities
//
// Created by <NAME> on 8/18/20.
//
import Foundation
import UIKit
extension UITabBarController {
@objc override var topMostViewController: UIViewController {
return presentedViewController?.topMostViewController ?? selectedViewController?.topMostViewController ?? self
}
}
extension UINavigationController {
@objc override var topMostViewController: UIViewController {
return presentedViewController?.topMostViewController ?? topViewController?.topMostViewController ?? self
}
}
extension UIViewController {
@objc var topMostViewController: UIViewController {
return presentedViewController?.topMostViewController ?? self
}
}
extension UIViewController {
public var allPresentedViewControllers: [UIViewController] {
if let presented = presentedViewController {
return presented.allPresentedViewControllers + [presented]
} else {
return []
}
}
public var allPresentingViewControllers: [UIViewController] {
if let presenting = presentingViewController {
return [presenting] + presenting.allPresentingViewControllers
} else {
return []
}
}
public var topPresentedViewController: UIViewController {
tabBarController?.topMostViewController ?? navigationController?.topMostViewController ?? topMostViewController
}
}
extension UINavigationController {
public var rootViewController: UIViewController? {
return viewControllers.first
}
}
extension UIViewController {
public var oldestLineageViewController: UIViewController {
if let parent = self.parent {
return parent.oldestLineageViewController
} else {
return self
}
}
public var allParents: [UIViewController] {
if let parent = self.parent {
return [parent] + parent.allParents
} else {
return []
}
}
public var olderLineageViewControllers: [UIViewController] {
allParents + [self]
}
}
// MARK: - UIApplication
extension UIApplication {
public class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController, !(presented is UIAlertController) {
return topViewController(base: presented)
}
return base
}
}
<file_sep>/Example/SiFUtilities/NavViewController.swift
//
// NavViewController.swift
// SiFUtilities_Example
//
// Created by FOLY on 4/6/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import SiFUtilities
class NavViewController: UINavigationController {
}
<file_sep>/UIKit/UICollectionViewCell++.swift
//
// UICollectionViewCell++.swift
// SiFUtilities
//
// Created by <NAME> on 10/17/21.
//
import UIKit
public extension UICollectionView {
func register<Cell: UICollectionViewCell>(_ nibCellType: Cell.Type) {
let identifier = String(describing: Cell.self)
let nib = UINib(nibName: identifier, bundle: Bundle(for: Cell.self))
self.register(nib, forCellWithReuseIdentifier: identifier)
}
func dequeueReusableCell<Cell: UICollectionViewCell>(_ cellType: Cell.Type = Cell.self, at indexPath: IndexPath) -> Cell {
let identifier = String(describing: Cell.self)
let dequeueCell = self.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
guard let cell = dequeueCell as? Cell else {
preconditionFailure("‼️ Type of cell is incorrect. Expected type is \(identifier) but got \(type(of: dequeueCell)).")
}
return cell
}
}
<file_sep>/Foundation/Codable/Codable+JSON.swift
//
// Codable+JSON.swift
//
//
// Created by <NAME> on 12/18/20.
//
import Foundation
public struct JSONCodingKeys: CodingKey {
public var stringValue: String
public init?(stringValue: String) {
self.stringValue = stringValue
}
public var intValue: Int?
public init?(intValue: Int) {
self.init(stringValue: "\(intValue)")
self.intValue = intValue
}
}
// MARK: - Decoding
extension Decoder {
public func jsonContainer() throws -> KeyedDecodingContainer<JSONCodingKeys> {
try container(keyedBy: JSONCodingKeys.self)
}
}
extension KeyedDecodingContainer {
public func decode(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any] {
let container = try self.nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key)
return try container.decode(type)
}
public func decodeIfPresent(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any]? {
guard contains(key) else {
return nil
}
guard try decodeNil(forKey: key) == false else {
return nil
}
return try self.decode(type, forKey: key)
}
public func decode(_ type: [Any].Type, forKey key: K) throws -> [Any] {
var container = try self.nestedUnkeyedContainer(forKey: key)
return try container.decode(type)
}
public func decodeIfPresent(_ type: [Any].Type, forKey key: K) throws -> [Any]? {
guard contains(key) else {
return nil
}
guard try decodeNil(forKey: key) == false else {
return nil
}
return try self.decode(type, forKey: key)
}
public func decode(_: [String: Any].Type) throws -> [String: Any] {
var dictionary = [String: Any]()
for key in allKeys {
if let boolValue = try? decode(Bool.self, forKey: key) {
dictionary[key.stringValue] = boolValue
} else if let stringValue = try? decode(String.self, forKey: key) {
dictionary[key.stringValue] = stringValue
} else if let intValue = try? decode(Int.self, forKey: key) {
dictionary[key.stringValue] = intValue
} else if let doubleValue = try? decode(Double.self, forKey: key) {
dictionary[key.stringValue] = doubleValue
} else if let nestedDictionary = try? decode([String: Any].self, forKey: key) {
dictionary[key.stringValue] = nestedDictionary
} else if let nestedArray = try? decode([Any].self, forKey: key) {
dictionary[key.stringValue] = nestedArray
}
}
return dictionary
}
}
extension UnkeyedDecodingContainer {
public mutating func decode(_: [Any].Type) throws -> [Any] {
var array: [Any] = []
while isAtEnd == false {
// See if the current value in the JSON array is `null` first and prevent infite recursion with nested arrays.
if try decodeNil() {
continue
} else if let value = try? decode(Bool.self) {
array.append(value)
} else if let value = try? decode(Double.self) {
array.append(value)
} else if let value = try? decode(String.self) {
array.append(value)
} else if let nestedDictionary = try? decode([String: Any].self) {
array.append(nestedDictionary)
} else if let nestedArray = try? decode([Any].self) {
array.append(nestedArray)
}
}
return array
}
public mutating func decode(_ type: [String: Any].Type) throws -> [String: Any] {
let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self)
return try nestedContainer.decode(type)
}
}
// MARK: - Encoding
extension Encoder {
public func jsonContainer() -> KeyedEncodingContainer<JSONCodingKeys> {
container(keyedBy: JSONCodingKeys.self)
}
}
extension KeyedEncodingContainer {
public mutating func encode(_ value: [String: Any], forKey key: K) throws {
var container = self.nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key)
return try container.encode(value)
}
public mutating func encode(_ value: [Any], forKey key: K) throws {
var container = self.nestedUnkeyedContainer(forKey: key)
return try container.encode(value)
}
public mutating func encode(_ value: [String: Any]) throws {
try value.forEach { key, value in
if let codingKey = JSONCodingKeys(stringValue: key) as? K {
if let nestedDictionary = value as? [String: Any] {
try encode(nestedDictionary, forKey: codingKey)
} else if let nestedArray = value as? [Any] {
try encode(nestedArray, forKey: codingKey)
} else if let boolValue = value as? Bool {
try encode(boolValue, forKey: codingKey)
} else if let stringValue = value as? String {
try encode(stringValue, forKey: codingKey)
} else if let intValue = value as? Int {
try encode(intValue, forKey: codingKey)
} else if let doubleValue = value as? Double {
try encode(doubleValue, forKey: codingKey)
}
}
}
}
}
extension UnkeyedEncodingContainer {
public mutating func encode(_ value: [Any]) throws {
try value.forEach { aValue in
if let boolValue = aValue as? Bool {
try encode(boolValue)
} else if let stringValue = aValue as? String {
try encode(stringValue)
} else if let intValue = aValue as? Int {
try encode(intValue)
} else if let doubleValue = aValue as? Double {
try encode(doubleValue)
} else if let nestedDictionary = aValue as? [String: Any] {
var nested = nestedContainer(keyedBy: JSONCodingKeys.self)
try nested.encode(nestedDictionary)
} else if let nestedArray = aValue as? [Any] {
var nested = nestedUnkeyedContainer()
try nested.encode(nestedArray)
}
}
}
}
<file_sep>/Example/SiFUtilities/PushDemoViewController.swift
//
// PushDemoViewController.swift
// SiFUtilities_Example
//
// Created by <NAME> on 8/22/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import SiFUtilities
import UIKit
final class PushDemoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.activeNavigationBar?.setBackgroundImage(UIImage(), for: .default)
self.activeNavigationBar?.shadowImage = UIImage()
self.activeNavigationBar?.titleTextAttributes = [.foregroundColor: UIColor.white]
}
@IBAction private func pushButtonDidTap() {
// let exvc = EXViewController.instantiateFromMainStoryboard()
// pushOverFullScreen(exvc)
}
@IBAction func unwindPop(_ segue: UIStoryboardSegue) {}
}
<file_sep>/UIKit/UIViewController++.swift
//
// UIViewController++.swift
// SiFUtilities
//
// Created by <NAME> on 7/13/19.
//
import Foundation
import UIKit
extension UIViewController {
public var activeNavigationBar: UINavigationBar? {
if let navigator = self as? UINavigationController {
return navigator.navigationBar
} else {
return navigationController?.navigationBar
}
}
}
// MARK: - Navigation
extension UIViewController {
public func setNavigationBarTitle(_ title: String) {
let label = UILabel(frame: .zero)
label.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
label.textColor = activeNavigationBar?.tintColor ?? .black
label.text = title
label.sizeToFit()
navigationItem.titleView = label
}
public func setNavigationBarHighlightedColor(_ color: UIColor) {
activeNavigationBar?.setHighlightColor(color)
activeNavigationBar?.layoutIfNeeded()
}
public func setNavigationBarBackImage(_ image: UIImage) {
activeNavigationBar?.setBackImage(image)
}
public func setNavigationBarBackTitle(_ title: String) {
let backItem = UIBarButtonItem.plainBarButtonItem(title: title)
/// should call before push new item to fix issue previous item back title not set
activeNavigationBar?.topItem?.backBarButtonItem = backItem
navigationItem.backBarButtonItem = backItem
}
public func hideNavigationBarBackTitle() {
setNavigationBarBackTitle("")
}
public func setNavigationBarBorderHidden(_ isHidden: Bool) {
let image = isHidden ? UIImage() : nil
activeNavigationBar?.shadowImage = image
}
}
<file_sep>/Foundation/Dictionary++.swift
//
// Dictionary++.swift
// Pods
//
// Created by FOLY on 9/13/17.
//
//
import Foundation
extension Dictionary {
public mutating func map(key: Key, to newKey: Key, keepOldKey: Bool = false) {
if let value = self[key] {
updateValue(value, forKey: newKey)
if !keepOldKey {
removeValue(forKey: key)
}
}
}
public func mapping(key: Key, to newKey: Key, keepOldKey: Bool = false) -> Self {
var newDict = self
newDict.map(key: key, to: newKey)
return newDict
}
}
<file_sep>/Boardy/Board+Show.swift
//
// Board+Show.swift
// SiFUtilities
//
// Created by <NAME> on 5/26/21.
//
import Boardy
import Foundation
public extension ActivatableBoard where Self: InstallableBoard {
func showDefaultLoading(_ isLoading: Bool, animated: Bool = true) {
guard context != nil else {
#if DEBUG
print("⚠️ \(#function) did perform without the context")
#endif
return
}
if isLoading {
rootViewController.showLoading(animated: animated)
} else {
rootViewController.hideLoading(animated: animated)
}
}
func showErrorAlert(_ error: Error) {
guard context != nil else {
#if DEBUG
print("⚠️ \(#function) with error \(error) did perform without the context")
#endif
return
}
rootViewController.showErrorAlert(error)
}
}
<file_sep>/Helpers/Debouncer.swift
//
// Debouncer.swift
//
//
// Created by <NAME> on 3/2/17.
// Copyright © 2017 [iF] Solution Co., Ltd. All rights reserved.
//
import Foundation
public final class TimerDebouncer {
private var delay: DispatchTimeInterval
private let queue: DispatchQueue
private var work: (() -> Void)?
private var timer: DispatchSourceTimer?
public init(delay: DispatchTimeInterval, queue: DispatchQueue = .main, work: (() -> Void)? = nil) {
self.delay = delay
self.queue = queue
set(work: work)
}
private func set(work: (() -> Void)?) {
if let work = work {
self.work = work
}
}
deinit {
timer?.setEventHandler(handler: nil)
cancel()
}
public func cancel() {
guard let timer = timer else { return }
guard !timer.isCancelled else { return }
timer.cancel()
}
public func perform(work: (() -> Void)? = nil) {
cancel()
set(work: work)
guard let currentWork = self.work else {
#if DEBUG
print("⚠️ [TimerDebouncer] Nothing to perform")
#endif
return
}
let nextTimer = DispatchSource.makeTimerSource(queue: queue)
nextTimer.schedule(deadline: .now() + delay)
nextTimer.setEventHandler(handler: currentWork)
timer = nextTimer
timer?.resume()
}
public func performNow() {
guard let work = self.work else {
#if DEBUG
print("⚠️ [TimerDebouncer] Nothing to perform")
#endif
return
}
work()
}
}
public final class Debouncer {
private var delay: DispatchTimeInterval
private let queue: DispatchQueue
private var work: (() -> Void)?
private var workItem: DispatchWorkItem?
public init(delay: DispatchTimeInterval, queue: DispatchQueue = .main, work: (() -> Void)? = nil) {
self.queue = queue
self.delay = delay
self.work = work
}
private func set(work: (() -> Void)?) {
if let work = work {
self.work = work
}
}
private func newWorkItem() {
if let work = self.work {
workItem = DispatchWorkItem(block: work)
}
}
deinit {
cancel()
}
public func cancel() {
workItem?.cancel()
}
public func perform(work: (() -> Void)? = nil) {
cancel()
set(work: work)
newWorkItem()
guard let workItem = self.workItem else {
#if DEBUG
print("⚠️ [Debouncer] Nothing to perform")
#endif
return
}
queue.asyncAfter(deadline: .now() + delay, execute: workItem)
}
public func performNow() {
cancel()
newWorkItem()
guard let workItem = self.workItem else {
#if DEBUG
print("⚠️ [Debouncer] Nothing to perform")
#endif
return
}
queue.async(execute: workItem)
}
}
<file_sep>/Foundation/Date+Utils.swift
//
// Date+Utils.swift
// SiFUtilities
//
// Created by FOLY on 2/4/17.
// Copyright © 2017 [iF] Solution. All rights reserved.
//
import Foundation
public enum DateFormat {
public static let regular1 = "dd/MM/yyyy"
public static let regular2 = "MM/dd/yyyy"
public static let regular3 = "yyyy/MM/dd"
public static let simple1 = "dd-MM-yyyy"
public static let simple2 = "MM-dd-yyyy"
public static let simple3 = "yyyy-MM-dd"
public static let simpleDot1 = "dd.MM.yyyy"
public static let simpleDot2 = "MM.dd.yyyy"
public static let simpleDot3 = "yyyy.MM.dd"
public static let shortMonth = "MMM dd, yyyy"
public static let longMonth = "MMMMM dd, yyyy"
public static let detailSimple = "dd-MMM-yyyy HH:mm"
public static let detailSimpleH = "dd-MM-yyyy HH'h'mm"
public static let detailSimpleHMin = "dd-MM-yyyy HH'h'MM'min'"
public static let detailRegular = "dd/MM/yyyy HH:mm"
public static let detailRegularH = "dd/MM/yyyy HH'h'mm"
public static let detailRegularZ = "dd/MM/yyyy HH:mm zzz"
public static let detailRegularAZ = "dd/MM/yyyy hh:mm a zzz"
public static let detailRegularS = "dd/MM/yyyy HH:mm:ss"
public static let detailRegularSZ = "dd/MM/yyyy HH:mm:ss zzz"
public static let detailRegularSAZ = "dd/MM/yyyy hh:mm:ss a zzz"
public static let detailLongMonthAZ = "MMMMM dd, yyyy hh:mm a zzz"
}
extension TimeZone {
public static var gmt: TimeZone {
TimeZone(secondsFromGMT: 0) ?? .current
}
}
extension Date {
public func toString(format: String? = DateFormat.detailRegular,
timeZone: TimeZone? = .current) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = timeZone
let internalFormat = format
dateFormatter.dateFormat = internalFormat
return dateFormatter.string(from: self)
}
public var localDateFromGMT: Date {
let timezone = TimeZone.current
let seconds = timezone.secondsFromGMT(for: self)
return Date(timeInterval: TimeInterval(seconds), since: self)
}
public var gmtDateFromLocal: Date {
let timezone = TimeZone.current
let seconds = timezone.secondsFromGMT(for: self)
return Date(timeInterval: TimeInterval(-seconds), since: self)
}
}
extension Date {
var calendar: Calendar { .current }
public func dateAfterDays(_ days: Int) -> Date {
return calendar.date(byAdding: .day, value: days, to: self)!
}
public var startOfDay: Date {
return calendar.startOfDay(for: self)
}
public var endOfDay: Date {
var components = DateComponents()
components.day = 1
components.second = -1
return calendar.date(byAdding: components, to: startOfDay)!
}
public var startOfWeek: Date {
let sunday = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
return calendar.date(byAdding: .day, value: 1, to: sunday)!
}
public var endOfWeek: Date {
let sunday = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
return sunday
}
public var startOfNextWeek: Date {
return calendar.date(byAdding: .day, value: 7, to: self)!.startOfWeek
}
public var startOfMonth: Date! {
let components = calendar.dateComponents([.year, .month], from: startOfDay)
return calendar.date(from: components)!
}
public var endOfMonth: Date {
var components = DateComponents()
components.month = 1
components.second = -1
return calendar.date(byAdding: components, to: startOfMonth!)!
}
public var nextMonth: Date {
return calendar.date(byAdding: .month, value: 1, to: self)!
}
public var previousMonth: Date {
return calendar.date(byAdding: .month, value: -1, to: self)!
}
public var startOfNextMonth: Date {
let firstDate = calendar.date(from: calendar.dateComponents([.year, .month], from: calendar.startOfDay(for: self)))!
return calendar.date(byAdding: .month, value: 1, to: firstDate)!
}
public var startOfYear: Date {
let components = calendar.dateComponents([.year], from: startOfDay)
return calendar.date(from: components)!
}
public var endOfYear: Date {
// Get the current year
let year = calendar.component(.year, from: self)
let firstOfNextYear = calendar.date(from: DateComponents(year: year + 1, month: 1, day: 1))!
return calendar.date(byAdding: .day, value: -1, to: firstOfNextYear)!
}
public var nextYear: Date {
return calendar.date(byAdding: .year, value: 1, to: self)!
}
public var previousYear: Date {
return calendar.date(byAdding: .year, value: -1, to: self)!
}
}
extension Date {
public func isSameDate(_ comparisonDate: Date) -> Bool {
let order = calendar.compare(self, to: comparisonDate, toGranularity: .day)
return order == .orderedSame
}
public func isBeforeDate(_ comparisonDate: Date) -> Bool {
let order = calendar.compare(self, to: comparisonDate, toGranularity: .day)
return order == .orderedAscending
}
public func isAfterDate(_ comparisonDate: Date) -> Bool {
let order = calendar.compare(self, to: comparisonDate, toGranularity: .day)
return order == .orderedDescending
}
}
extension Date {
public var numberOfDaysInMonth: Int {
let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
return numDays
}
}
extension Date {
public var age: Int {
return calendar.dateComponents([.year], from: self, to: Date()).year!
}
}
public extension Date {
/// The `year` date component of `self`. The time zone used is equal to the `Calendar.current.timeZone`.
var year: Int {
return Calendar.current.component(.year, from: self)
}
/// The `month` date component of `self`. The time zone used is equal to the `Calendar.current.timeZone`.
var month: Int {
return Calendar.current.component(.month, from: self)
}
/// The `day` date component of `self`. The time zone used is equal to the `Calendar.current.timeZone`.
var day: Int {
return Calendar.current.component(.day, from: self)
}
/// The `hour` date component of `self`. The time zone used is equal to the `Calendar.current.timeZone`.
var hour: Int {
return Calendar.current.component(.hour, from: self)
}
/// The `minute` date component of `self`. The time zone used is equal to the `Calendar.current.timeZone`.
var minute: Int {
return Calendar.current.component(.minute, from: self)
}
/// The `second` date component of `self`. The time zone used is equal to the `Calendar.current.timeZone`.
var second: Int {
return Calendar.current.component(.second, from: self)
}
}
<file_sep>/Localize/UIImageView+Localize.swift
//
// UIImageView++.swift
// SiFUtilities
//
// Created by FOLY on 9/10/18.
//
import Foundation
// @IBDesignable
extension UIImageView {
@IBInspectable public var imageNameLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedImageNameKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedImageNameKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let imageName = attributes[.localizedImageNameKey]?.localized {
let assetImage = UIImage(named: imageName)
image = assetImage
}
}
@objc override open func updateLanguage() {
if let key = imageNameLocalizedKey {
updateLocalize(attributes: [.localizedImageNameKey: key])
}
}
}
<file_sep>/UIKit/UITextField++.swift
//
// UITextField++.swift
// Pods-SiFUtilities_Example
//
// Created by FOLY on 4/6/18.
//
import Foundation
// @IBDesignable
extension UITextField {
@IBInspectable open var leftPadding: CGFloat {
get {
return leftView?.frame.size.width ?? 0
}
set {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
leftView = paddingView
leftViewMode = .always
}
}
@IBInspectable open var rightPadding: CGFloat {
get {
return rightView?.frame.size.width ?? 0
}
set {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
rightView = paddingView
rightViewMode = .always
}
}
}
<file_sep>/Loading/UIViewController+NavigationIndicator.swift
//
// UIViewController+NavigationIndicator.swift
// SiFUtilities
//
// Created by <NAME> on 9/28/21.
// Copyright © 2021 [iF] Solution. All rights reserved.
//
import Foundation
import UIKit
private var rightItemsKey: UInt8 = 70
private var titleViewKey: UInt8 = 71
extension UIViewController {
private var rightItems: [UIBarButtonItem]? {
get {
getAssociatedObject(key: &rightItemsKey)
}
set {
setAssociatedObject(key: &rightItemsKey, value: newValue)
}
}
private var titleView: UIView? {
get {
getAssociatedObject(key: &titleViewKey)
}
set {
setAssociatedObject(key: &titleViewKey, value: newValue)
}
}
public enum NavigationLoadingStyle {
case right
case center
}
public func showNavigationLoading(style: NavigationLoadingStyle = .center, animated: Bool = true) {
var indicatorStyle: UIActivityIndicatorView.Style
if #available(iOS 13, *) {
indicatorStyle = .medium
} else {
indicatorStyle = .gray
}
let activityIndicator = UIActivityIndicatorView(style: indicatorStyle)
activityIndicator.tintColor = .darkGray
switch style {
case .right:
rightItems = navigationItem.rightBarButtonItems
let barButtonItem = UIBarButtonItem(customView: activityIndicator)
navigationItem.setRightBarButton(barButtonItem, animated: animated)
case .center:
titleView = navigationItem.titleView
navigationItem.titleView = activityIndicator
}
activityIndicator.startAnimating()
}
public func hideNavigationLoading(style: NavigationLoadingStyle = .center, animated: Bool = true) {
switch style {
case .right:
navigationItem.setRightBarButtonItems(rightItems, animated: animated)
rightItems = nil
case .center:
navigationItem.titleView = titleView
titleView = nil
}
}
}
<file_sep>/Foundation/Number+Format.swift
//
// Number+Format.swift
// SiFUtilities
//
// Created by <NAME> on 8/17/21.
//
import Foundation
extension Numeric {
public func formatted(separator: String? = nil,
numberStyle: NumberFormatter.Style = .decimal,
localeIdentifier: String? = "vn_VN") -> String {
var locale = Locale.current
if let localeID = localeIdentifier {
locale = Locale(identifier: localeID)
}
let separator = separator ?? locale.decimalSeparator ?? ","
let formatter = NumberFormatter(separator: separator, numberStyle: numberStyle)
formatter.locale = locale
return formatter.string(for: self) ?? "\(self)"
}
}
extension NumberFormatter {
public convenience init(separator: String, numberStyle: NumberFormatter.Style) {
self.init()
self.usesGroupingSeparator = true
self.groupingSize = 3
self.currencyGroupingSeparator = separator
self.groupingSeparator = separator
self.numberStyle = numberStyle
}
}
extension Locale {
public static var vietnam: Locale {
return Locale(identifier: "vn_VN")
}
}
<file_sep>/UIKit/UIView+Tap.swift
//
// UIView+Tap.swift
// DadMisc
//
// Created by <NAME> on 6/2/21.
//
import Foundation
import UIKit
private var tapHandlerKey: UInt = 1881
extension UIView {
public func addTapGestureRecognizer(_ handler: @escaping () -> Void) {
objc_setAssociatedObject(self, &tapHandlerKey, handler, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let tapGestureReg = UITapGestureRecognizer(target: self, action: #selector(tapDetected(_:)))
tapGestureReg.numberOfTouchesRequired = 1
tapGestureReg.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureReg)
isUserInteractionEnabled = true
}
@objc
private func tapDetected(_ reg: UITapGestureRecognizer) {
let handler = objc_getAssociatedObject(self, &tapHandlerKey) as? () -> Void
tapAnimate {
handler?()
}
}
}
public extension UIView {
func tapAnimate(_ completionBlock: @escaping () -> Void) {
isUserInteractionEnabled = false
UIView.animate(
withDuration: 0.1,
delay: 0,
options: .curveLinear,
animations: { [weak self] in
self?.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
}
) { _ in
UIView.animate(
withDuration: 0.1,
delay: 0,
options: .curveLinear,
animations: { [weak self] in
self?.transform = .identity
}
) { [weak self] _ in
self?.isUserInteractionEnabled = true
completionBlock()
}
}
}
}
<file_sep>/UIKit/UIKit++.swift
//
// UIColor+Extensions.swift
// SiFUtilities
//
// Created by <NAME> on 6/10/16.
// Copyright © 2016 [iF] Solution. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIColor
extension UIColor {
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 100) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a/100)
}
public class func random(alpha: CGFloat = 1) -> UIColor {
let randomRed = CGFloat(drand48())
let randomGreen = CGFloat(drand48())
let randomBlue = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha)
}
}
<file_sep>/UIKit/UIApplication++.swift
//
// UIApplication++.swift
// SiFUtilities
//
// Created by <NAME> on 03/03/2023.
//
import Foundation
import UIKit
public extension UIApplication {
var currentWindow: UIWindow? {
let legacyWindow = keyWindow ?? windows.first(where: { $0.isKeyWindow }) ?? windows.last
if #available(iOS 13.0, *) {
let sceneWindow = connectedScenes
.filter { $0.activationState == .foregroundActive }
.compactMap { $0 as? UIWindowScene }
.first?.windows
.first(where: { $0.isKeyWindow })
return sceneWindow ?? legacyWindow
} else {
return legacyWindow
}
}
}
<file_sep>/Show/UIWindow+Animation.swift
//
// UIWindow+Animation.swift
// Pods
//
// Created by <NAME> on 8/22/20.
//
import Foundation
import UIKit
extension UIWindow {
public func setRootViewController(_ rootViewController: UIViewController, animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
if let presented = self.rootViewController?.presentedViewController {
presented.modalTransitionStyle = .crossDissolve
self.rootViewController?.dismiss(animated: animated, completion: {
self.setRootViewController(rootViewController, animated: animated, completion: completion)
})
return
}
if animated {
transitRootViewController(rootViewController, duration: 0.3, options: .transitionCrossDissolve)
} else {
self.rootViewController = rootViewController
}
}
public func transitRootViewController(_ rootViewController: UIViewController, duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)? = nil) {
self.rootViewController = rootViewController
UIView.transition(with: self,
duration: duration,
options: options,
animations: {},
completion: completion)
}
}
<file_sep>/Example/SiFUtilities/AppDelegate.swift
//
// AppDelegate.swift
// SiFUtilities
//
// Created by <NAME> on 05/29/2016.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
import SiFUtilities
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let debouncer: Debouncer? = Debouncer(delay: .seconds(2)) { print("XX") }
private var timerDebouncer: TimerDebouncer? = TimerDebouncer(delay: .seconds(2))
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
self.debouncer?.perform()
}
DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
self.debouncer?.perform()
}
DispatchQueue.global().asyncAfter(deadline: .now() + 4.1) {
self.debouncer?.perform()
}
timerDebouncer?.performNow()
DispatchQueue.global().asyncAfter(deadline: .now() + 7) {
self.timerDebouncer = nil
}
let dict = ["abc": "abc", "def": "def"]
let newDict = dict.mapping(key: "abc", to: "ABC")
print(newDict)
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {}
}
<file_sep>/Localize/UISearchBar+Localize.swift
//
// UISearchBar+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
// @IBDesignable
extension UISearchBar {
@IBInspectable public var placeholderLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedPlaceholderTextKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedPlaceholderTextKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let text = attributes[.localizedPlaceholderTextKey]?.localized {
placeholder = text
}
}
@objc override open func updateLanguage() {
if let key = placeholderLocalizedKey {
updateLocalize(attributes: [.localizedPlaceholderTextKey: key])
}
}
}
<file_sep>/SiFUtilities.podspec
Pod::Spec.new do |s|
s.name = "SiFUtilities"
s.version = "4.28.0"
s.summary = "A set of utilities for your app."
s.swift_version = "5"
s.description = <<-DESC
- Get instance view controller from Storyboard shortly
- Handle viewController did finished layout at first time
- Configure status bar quickly
- More extensions
DESC
s.homepage = "https://github.com/congncif/SiFUtilities"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/congncif/SiFUtilities.git", :tag => s.version.to_s }
s.social_media_url = "https://twitter.com/congncif"
s.ios.deployment_target = "10.0"
# s.frameworks = 'UIKit', 'Foundation', 'AVFoundation', 'CoreData'
s.default_subspec = "Default"
s.subspec "Foundation" do |co|
co.source_files = "Foundation/**/*"
end
s.subspec "UIKit" do |co|
co.source_files = "UIKit/**/*.swift"
end
s.subspec "Media" do |co|
co.source_files = "Media/**/*.swift"
end
s.subspec "Endpoint" do |co|
co.source_files = "Endpoint/**/*"
end
s.subspec "Helpers" do |co|
co.source_files = "Helpers/**/*"
end
s.subspec "IBDesignable" do |co|
co.source_files = "IBDesignable/**/*"
co.dependency "SiFUtilities/UIKit"
end
s.subspec "KeyValue" do |co|
co.source_files = "KeyValue/**/*"
end
s.subspec "Loading" do |co|
co.source_files = "Loading/**/*"
co.dependency "SiFUtilities/Foundation"
end
s.subspec "Localize" do |co|
co.source_files = "Localize/**/*.swift"
co.preserve_paths = "Localize/localizable2appstrings"
co.dependency "SiFUtilities/Foundation"
co.dependency "SiFUtilities/UIKit"
co.dependency "SiFUtilities/Foundation"
co.dependency "Localize-Swift/LocalizeSwiftCore"
end
s.subspec "Nib" do |co|
co.source_files = "Nib/**/*"
co.dependency "SiFUtilities/Foundation"
end
s.subspec "Runtime" do |co|
co.source_files = "Runtime/**/*"
co.dependency "SiFUtilities/Foundation"
end
s.subspec "Show" do |co|
co.source_files = "Show/**/*"
co.dependency "SiFUtilities/UIKit"
end
s.subspec "WeakObject" do |co|
co.source_files = "WeakObject/**/*"
end
s.subspec "Boardy" do |co|
co.source_files = "Boardy/**/*.swift"
co.dependency "SiFUtilities/Show"
co.dependency "SiFUtilities/Loading"
co.dependency "Boardy/ComponentKit"
end
s.subspec "Default" do |co|
co.dependency "SiFUtilities/Foundation"
co.dependency "SiFUtilities/UIKit"
co.dependency "SiFUtilities/Media"
co.dependency "SiFUtilities/Endpoint"
co.dependency "SiFUtilities/Helpers"
co.dependency "SiFUtilities/IBDesignable"
co.dependency "SiFUtilities/KeyValue"
co.dependency "SiFUtilities/Loading"
# co.dependency "SiFUtilities/Localize"
co.dependency "SiFUtilities/Nib"
co.dependency "SiFUtilities/Runtime"
co.dependency "SiFUtilities/Show"
co.dependency "SiFUtilities/WeakObject"
co.dependency "SiFUtilities/Boardy"
end
s.subspec "CommandLineTool" do |co|
co.preserve_paths = "CommandLineTool/localizable2appstrings"
end
end
<file_sep>/Foundation/DefaultValue.swift
//
// DefaultValueRepresentable.swift
//
//
// Created by <NAME> on 12/21/20.
//
import Foundation
public protocol DefaultValueRepresentable {
static var `default`: Self { get }
}
extension Optional where Wrapped: DefaultValueRepresentable {
public var `default`: Wrapped {
switch self {
case let .some(value):
return value
default:
return Wrapped.default
}
}
public func unwrapped(_ default: Wrapped = .default) -> Wrapped {
return self ?? `default`
}
}
extension String: DefaultValueRepresentable {
public static var `default`: String { "" }
}
extension Array: DefaultValueRepresentable {
public static var `default`: [Element] { [] }
}
extension Dictionary: DefaultValueRepresentable {
public static var `default`: [Key: Value] { [:] }
}
<file_sep>/Example/SiFUtilities/EXViewController.swift
//
// EXViewController.swift
// SiFUtilities_Example
//
// Created by FOLY on 3/20/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import Localize_Swift
import SiFUtilities
class EXViewController: UIViewController {
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0, y: 100, width: 100, height: 50))
label.textLocalizedKey = "Hello"
view.addSubview(label)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
private var flag: Bool = true
@IBAction func tap() {
// self.hideOverlay()
flag = !flag
let lang = flag ? "en" : "vi-VN"
Localize.setCurrentLanguage(lang)
}
@IBAction func tap2() {
button.normalTitleLocalizedKey = "dcm"
}
override func didRemoveFromParent() {
print("Backing from prarent")
}
}
<file_sep>/UIKit/Notification+Keyboard.swift
//
// Notification+Keyboard.swift
// SiFUtilities
//
// Created by <NAME> on 5/12/21.
//
import Foundation
import UIKit
public extension Notification {
var keyboardFrame: CGRect? {
userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
}
var keyboardHeight: CGFloat? {
keyboardFrame?.height
}
var keyboardAnimationDuration: CGFloat? {
userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? CGFloat
}
}
public struct KeyboardInfo {
public let visible: Bool
public let height: CGFloat
public let diff: CGFloat
public let animationDuration: TimeInterval
}
public final class KeyboardAppearanceObserver {
private let handler: (KeyboardInfo) -> Void
public init(handler: @escaping (_ info: KeyboardInfo) -> Void) {
self.handler = handler
}
public func startObserving() {
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: OperationQueue.main, using: { [weak self] notification in
self?.didChange(notification)
})
}
public func stopObserving() {
NotificationCenter.default.removeObserver(self)
}
deinit {
stopObserving()
}
func didChange(_ notification: Notification) {
var isKeyBoardShowing = false
let isPortrait = UIApplication.shared.statusBarOrientation.isPortrait
// get the keyboard & window frames
let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect ?? .zero
// keyboardHeightDiff used when user is switching between different keyboards that have different heights
var keyboardFrameBegin = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect ?? .zero
// hack for bug in iOS 11.2
let keyboardFrameEnd = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect ?? .zero
if keyboardFrameEnd.size.height > keyboardFrameBegin.size.height {
keyboardFrameBegin = CGRect(x: keyboardFrameBegin.origin.x, y: keyboardFrameBegin.origin.y, width: keyboardFrameBegin.size.width, height: keyboardFrameEnd.size.height)
}
var keyboardHeightDiff: CGFloat = 0.0
if keyboardFrameBegin.size.height > 0 {
keyboardHeightDiff = keyboardFrameBegin.size.height - keyboardFrame.size.height
}
let screenSize = UIScreen.main.bounds.size
// let animationCurve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int ?? 0
// let animationOptions = animationCurve << 16
// if split keyboard is being dragged, then skip notification
if keyboardFrame.size.height == 0, UIDevice.current.userInterfaceIdiom == .pad {
if isPortrait, keyboardFrameBegin.origin.y + keyboardFrameBegin.size.height == screenSize.height {
return
} else if !isPortrait, keyboardFrameBegin.origin.x + keyboardFrameBegin.size.width == screenSize.width {
return
}
}
// calculate if we are to move up the avoiding view
if !keyboardFrame.isEmpty, keyboardFrame.origin.y == 0 || (keyboardFrame.origin.y + keyboardFrame.size.height == screenSize.height) {
isKeyBoardShowing = true
}
// get animation duration
var animationDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0
if animationDuration == 0 {
// custom keyboards often don't animate, its too clanky so have to manually set this
animationDuration = 0.1
}
let info = KeyboardInfo(visible: isKeyBoardShowing, height: keyboardFrame.height, diff: keyboardHeightDiff, animationDuration: animationDuration)
handler(info)
}
}
public final class KeyboardAppearanceScrollObserver {
private weak var scrollView: UIScrollView?
private var initialContentInset: UIEdgeInsets?
public init(scrollView: UIScrollView) {
self.scrollView = scrollView
}
private lazy var observer = KeyboardAppearanceObserver { [weak self] info in
if self?.initialContentInset == nil {
self?.initialContentInset = self?.scrollView?.contentInset
}
guard let scrollView = self?.scrollView, let initialContentInset = self?.initialContentInset else { return }
var contentInset = initialContentInset
contentInset.bottom = initialContentInset.bottom + (info.visible ? info.height : 0)
scrollView.contentInset = contentInset
if let activeView = scrollView.firstResponder, info.visible {
let rect = activeView.convert(activeView.bounds, to: scrollView)
let bounds = UIScreen.main.bounds
let activeViewMaxY = rect.maxY + scrollView.frame.minY + scrollView.contentInset.top - scrollView.contentOffset.y
let visibleMaxY = bounds.height - info.height
let missingDistance = activeViewMaxY - visibleMaxY
if missingDistance > 0 {
var contentOffset = scrollView.contentOffset
contentOffset.y = scrollView.contentOffset.y + missingDistance + 20
scrollView.contentOffset = contentOffset
}
}
}
public func startObserving() {
observer.startObserving()
}
public func stopObserving() {
observer.stopObserving()
}
}
<file_sep>/Show/UIViewController+Return.swift
//
// UIViewController+Return.swift
// SiFUtilities
//
// Created by <NAME> on 8/18/20.
//
import Foundation
import UIKit
extension UIViewController {
public func returnHere(animated: Bool = true, completion: (() -> Void)? = nil) {
if self.presentedViewController != nil {
self.dismiss(animated: animated, completion: completion)
self.popToShowIfNeeded(animated: animated, completion: nil)
} else {
self.popToShowIfNeeded(animated: animated, completion: completion)
}
}
private func popToShowIfNeeded(animated: Bool, completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
if let nav = navigationController, let foundTarget = findParentViewController(in: nav) {
nav.popToViewController(foundTarget, animated: animated)
}
CATransaction.commit()
}
private func findParentViewController(in navigationController: UINavigationController) -> UIViewController? {
if navigationController.viewControllers.contains(self) {
return self
} else {
return allParents.first { navigationController.viewControllers.contains($0) }
}
}
}
<file_sep>/Show/UIViewController+PushOver.swift
//
// UIViewController+PushOver.swift
// SiFUtilities
//
// Created by <NAME> on 8/18/20.
//
import Foundation
import UIKit
public extension UIViewController {
func pushOverFullScreen(_ viewController: UIViewController,
navigationType: UINavigationController.Type? = nil,
animated: Bool = true) {
let contentView = topMostViewController.oldestLineageViewController.view.snapshotView(afterScreenUpdates: true)
let rootViewController = ResumeDismissViewController(contentView: contentView)
let navigationController = UINavigationController(rootViewController: rootViewController)
navigationController.view.backgroundColor = .clear
let configuration = PresentationConfiguration.default.apply {
$0.style = .present(PresentConfiguration(navigationType: navigationType, modalPresentationStyle: .fullScreen, modalTransitionStyle: .crossDissolve, isModalInPresentation: false))
$0.animated = false
}
topMostViewController.show(navigationController, configuration: configuration) {
navigationController.pushViewController(viewController, animated: animated)
}
}
func popOverFullScreen(animated: Bool = true, completion: (() -> Void)? = nil) {
let presentedNavigation = presentedViewController as? UINavigationController
guard let foundNavigation = presentedNavigation ?? navigationController ?? self as? UINavigationController, let rootViewController = foundNavigation.rootViewController as? ResumeDismissViewController else {
assertionFailure("Cannot detect Over Full Screen")
return
}
rootViewController.dismissHandler = completion
foundNavigation.popToRootViewController(animated: animated)
}
}
// MARK: - Segues
public final class PushOverFullScreenSegue: UIStoryboardSegue {
override public func perform() {
let animated = UIView.areAnimationsEnabled
source.pushOverFullScreen(destination, animated: animated)
}
}
public final class UnwindPopOverFullScreenSegue: UIStoryboardSegue {
override public func perform() {
let animated = UIView.areAnimationsEnabled
destination.popOverFullScreen(animated: animated)
}
}
// MARK: - Internal ResumeDismissViewController
final class ResumeDismissViewController: UIViewController {
private var appearCount: Int = 0
private let contentView: UIView
var dismissHandler: (() -> Void)?
init(contentView: UIView?) {
self.contentView = contentView ?? UIView()
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = contentView
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let backItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backItem
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard appearCount == 0 else {
dismiss(animated: false, completion: dismissHandler)
return
}
appearCount += 1
}
}
<file_sep>/Show/UIViewController+Show.swift
//
// UIViewController+Show.swift
// Pods
//
// Created by FOLY on 7/14/17.
//
//
import Foundation
import UIKit
public struct PresentConfiguration {
public let navigationType: UINavigationController.Type?
public let modalPresentationStyle: UIModalPresentationStyle
public let modalTransitionStyle: UIModalTransitionStyle
public let isModalInPresentation: Bool // iOS 13 only
public init(navigationType: UINavigationController.Type?,
modalPresentationStyle: UIModalPresentationStyle,
modalTransitionStyle: UIModalTransitionStyle,
isModalInPresentation: Bool) {
self.navigationType = navigationType
self.modalPresentationStyle = modalPresentationStyle
self.modalTransitionStyle = modalTransitionStyle
self.isModalInPresentation = isModalInPresentation
}
public static var embeddedInNavigation: PresentConfiguration {
if #available(iOS 13.0, *) {
return PresentConfiguration(navigationType: UINavigationController.self, modalPresentationStyle: .automatic, modalTransitionStyle: .coverVertical, isModalInPresentation: true)
} else {
return PresentConfiguration(navigationType: UINavigationController.self, modalPresentationStyle: .fullScreen, modalTransitionStyle: .coverVertical, isModalInPresentation: true)
}
}
public static var embeddedInNavigationFullScreen: PresentConfiguration {
PresentConfiguration(navigationType: UINavigationController.self, modalPresentationStyle: .fullScreen, modalTransitionStyle: .coverVertical, isModalInPresentation: true)
}
public static var `default`: PresentConfiguration {
if #available(iOS 13.0, *) {
return PresentConfiguration(navigationType: nil, modalPresentationStyle: .automatic, modalTransitionStyle: .coverVertical, isModalInPresentation: true)
} else {
return PresentConfiguration(navigationType: nil, modalPresentationStyle: .fullScreen, modalTransitionStyle: .coverVertical, isModalInPresentation: true)
}
}
public static var defaultFullScreen: PresentConfiguration {
return PresentConfiguration(navigationType: nil, modalPresentationStyle: .fullScreen, modalTransitionStyle: .coverVertical, isModalInPresentation: true)
}
}
public enum NavigateConfiguration {
case push
case replace
case replaceAll
}
public enum PresentationStyle {
case navigate(NavigateConfiguration)
case present(PresentConfiguration)
public static var defaultPresent: PresentationStyle {
return .present(.embeddedInNavigation)
}
}
public final class PresentationConfiguration {
public var style: PresentationStyle? // default is nil, auto detect presentation style
public var animated: Bool = true
public var backTitle: String?
public var hidesBottomBarWhenPushed: Bool = true
private init() {}
public static var `default`: PresentationConfiguration { PresentationConfiguration() }
public func apply(_ configurationBlock: (PresentationConfiguration) -> Void = { _ in }) -> PresentationConfiguration {
configurationBlock(self)
return self
}
}
public extension UIViewController {
func show(_ viewController: UIViewController,
configurations: (PresentationConfiguration) -> Void,
completion: (() -> Void)? = nil) {
let configs = PresentationConfiguration.default.apply(configurations)
show(viewController, configuration: configs, completion: completion)
}
func show(_ viewController: UIViewController,
configuration: PresentationConfiguration = .default,
completion: (() -> Void)? = nil) {
viewController.hidesBottomBarWhenPushed = configuration.hidesBottomBarWhenPushed
if let backTitle = configuration.backTitle {
viewController.setNavigationBarBackTitle(backTitle)
}
let source: UIViewController = self
var destination: UIViewController
let targetIsNavigation = viewController is UINavigationController
let sourceIsNavigation = self is UINavigationController
var presentationStyle: PresentationStyle
if let style = configuration.style {
presentationStyle = style
} else {
if targetIsNavigation {
presentationStyle = .present(.defaultFullScreen)
} else if sourceIsNavigation {
presentationStyle = .navigate(.push)
} else if navigationController != nil {
presentationStyle = .navigate(.push)
} else {
presentationStyle = .present(.embeddedInNavigationFullScreen)
}
}
switch presentationStyle {
case let .navigate(configs):
switch configs {
case .push:
destination = viewController
source.navigator?.pushViewController(destination, animated: configuration.animated)
case .replace:
destination = viewController
let viewControllers = source.navigator?.viewControllers ?? []
let droppedViewControllers = Array(viewControllers.dropLast())
if droppedViewControllers.isEmpty {
destination.showCloseButton(at: .left)
}
let newViewControllers = droppedViewControllers + [destination]
source.navigator?.setViewControllers(newViewControllers, animated: configuration.animated)
case .replaceAll:
destination = viewController
destination.showCloseButton(at: .left)
source.navigator?.setViewControllers([destination], animated: configuration.animated)
}
if let completion = completion, configuration.animated {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: completion)
} else {
completion?()
}
case let .present(configs):
if let navigationType = configs.navigationType {
if let nav = viewController as? UINavigationController {
nav.viewControllers.first?.showCloseButton(at: .left)
destination = nav
} else {
viewController.showCloseButton(at: .left)
destination = navigationType.init(rootViewController: viewController)
}
} else {
if let nav = viewController as? UINavigationController {
nav.viewControllers.first?.showCloseButton(at: .left)
}
destination = viewController
}
destination.modalPresentationStyle = configs.modalPresentationStyle
destination.modalTransitionStyle = configs.modalTransitionStyle
if #available(iOS 13.0, *) {
destination.isModalInPresentation = configs.isModalInPresentation
}
source.topPresentedViewController.present(destination, animated: configuration.animated, completion: completion)
}
}
private var navigator: UINavigationController? {
if let nav = self as? UINavigationController {
return nav
} else {
return navigationController
}
}
}
public extension UIViewController {
func backToPrevious(animated: Bool = true, completion: (() -> Void)? = nil) {
if let navigation = navigationController {
if navigation.viewControllers.first != self {
navigation.popViewController(animated: animated)
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: completion)
}
} else {
if let _ = navigation.presentingViewController {
navigation.dismiss(animated: animated, completion: completion)
} else {
assertionFailure("Previous page not found")
}
}
} else if let _ = presentingViewController {
dismiss(animated: animated, completion: completion)
} else {
assertionFailure("Previous page not found")
}
}
func forceDismiss(animated: Bool = true, completion: (() -> Void)? = nil) {
if let presenting = presentingViewController {
presenting.dismiss(animated: animated, completion: completion)
} else if let navigation = navigationController, let presenting = navigation.presentingViewController {
presenting.dismiss(animated: animated, completion: completion)
} else {
dismiss(animated: animated, completion: completion)
}
}
}
public extension UIViewController {
enum CloseButtonPosition {
case left
case right
}
func showCloseButton(_ barButtonItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop), at position: CloseButtonPosition = .left) {
barButtonItem.action = #selector(dismissButtonDidTap(_:))
barButtonItem.target = self
switch position {
case .left:
navigationItem.leftBarButtonItem = barButtonItem
case .right:
navigationItem.rightBarButtonItem = barButtonItem
}
}
func showCloseButtonIfNeeded(_ barButtonItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop), at position: CloseButtonPosition = .left) {
if isPresentedInNavigation, isRootOfNavigation {
showCloseButton(barButtonItem, at: position)
}
}
@objc private func dismissButtonDidTap(_ sender: Any) {
forceDismiss()
}
var isRootOfNavigation: Bool {
return navigationController?.viewControllers.first == self
}
var isPresentedInNavigation: Bool {
return navigationController?.presentingViewController != nil
}
}
// MARK: - Segues + Show
public final class ShowSegue: UIStoryboardSegue {
override public func perform() {
let animated = UIView.areAnimationsEnabled
source.show(destination, configurations: { $0.animated = animated })
}
}
// MARK: - Deprecated
public extension UIViewController {
@available(*, deprecated, message: "This method was replaced by method show(_:configuration:completion)")
func show(on baseViewController: UIViewController,
embedIn NavigationType: UINavigationController.Type = UINavigationController.self,
closeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop),
position: CloseButtonPosition = .left,
animated: Bool = true,
completion: (() -> Void)? = nil) {
if let navigation = baseViewController as? UINavigationController {
navigation.pushViewController(self, animated: animated)
if let completion = completion {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: completion)
}
} else {
baseViewController.present(self, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
}
}
@available(*, deprecated, message: "This method was replaced by method show(_:configuration:completion)")
func show(viewController: UIViewController,
from baseViewController: UIViewController? = nil,
embedIn NavigationType: UINavigationController.Type = UINavigationController.self,
closeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop),
position: CloseButtonPosition = .left,
animated: Bool = true,
completion: (() -> Void)? = nil) {
guard let base = baseViewController else {
if let navigation = navigationController {
viewController.show(on: navigation, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
} else {
viewController.show(on: self, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
}
return
}
viewController.show(on: base, embedIn: NavigationType, closeButton: closeButton, position: position, animated: animated, completion: completion)
}
@available(*, deprecated, message: "This method was replaced by method show(_:configuration:completion)")
func present(_ vc: UIViewController, embedIn navigationType: UINavigationController.Type = UINavigationController.self, closeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop), position: CloseButtonPosition = .left, animated: Bool = true, completion: (() -> Void)? = nil) {
if let nav = vc as? UINavigationController {
nav.topViewController?.showCloseButton(closeButton, at: position)
present(nav, animated: animated, completion: completion)
} else {
vc.showCloseButton(at: position)
let nav = navigationType.init(rootViewController: vc)
present(nav, animated: animated, completion: completion)
}
}
}
<file_sep>/Foundation/String++.swift
//
// String++.swift
// SiFUtilities
//
// Created by FOLY on 1/11/17.
// Copyright © 2017 [iF] Solution. All rights reserved.
//
import Foundation
// MARK: - ID
extension String {
public static func random(length: Int = 16) -> String {
let letters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = String()
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
public static func uuid() -> String {
return UUID().uuidString
}
public static func uniqueIdentifier() -> String {
return self.uuid().lowercased()
}
}
// MARK: - Date
extension String {
public func toDate(format: String? = DateFormat.detailRegular,
timeZone: TimeZone? = .current) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = timeZone
let internalFormat = format
dateFormatter.dateFormat = internalFormat
return dateFormatter.date(from: self)
}
}
// MARK: - Transform
extension String {
public var trimmingWhiteSpaces: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
public func removingCharacters(_ characters: CharacterSet) -> String {
return components(separatedBy: characters).joined()
}
public var removingWhiteSpaces: String {
return self.removingCharacters(.whitespacesAndNewlines)
}
public var words: [String] {
return components(separatedBy: .punctuationCharacters)
.joined()
.components(separatedBy: .whitespaces)
.filter { !$0.isEmpty }
}
public var replacingWhiteSpacesByNonbreakingSpaces: String {
return replacingOccurrences(of: " ", with: "\u{00a0}")
}
public var capitalizingFirstLetter: String {
return prefix(1).uppercased() + dropFirst()
}
public var lowercasingFirstLetter: String {
return prefix(1).lowercased() + dropFirst()
}
public mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter
}
public mutating func lowercaseFirstLetter() {
self = self.lowercasingFirstLetter
}
public func snakeCased() -> String {
let pattern = "([a-z0-9])([A-Z])"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: self.count)
return regex?.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "$1_$2").lowercased() ?? self
}
public func camelCased(separator: String = "_", skipFirstLetter: Bool = true) -> String {
let components = self.components(separatedBy: separator)
var newComponents: [String] = []
for (idx, word) in components.enumerated() {
if idx == 0, skipFirstLetter {
newComponents.append(word.lowercased())
} else {
newComponents.append(word.lowercased().capitalizingFirstLetter)
}
}
if newComponents.count <= 1 {
return self
}
return newComponents.joined()
}
}
// MARK: - Checking
extension String {
public var isAlphanumerics: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
public var digitsOnly: String {
return replacingOccurrences(of: "[^\\d+]", with: "", options: [.regularExpression])
}
public func insensitiveContains(_ subString: String) -> Bool {
return range(of: subString, options: [.caseInsensitive, .diacriticInsensitive]) != nil
}
}
// MARK: - Format
extension String {
public func formatted(defaultAttributes: [NSAttributedString.Key: Any], attributedStrings: NSAttributedString...) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self, attributes: defaultAttributes)
for subString in attributedStrings {
let range = (self as NSString).range(of: subString.string)
attributedString.replaceCharacters(in: range, with: subString)
}
return attributedString
}
}
<file_sep>/Example/SiFUtilities/UnwindPopViewController.swift
//
// UnwindPopViewController.swift
// SiFUtilities_Example
//
// Created by <NAME> on 8/22/20.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import SiFUtilities
import UIKit
class Push1ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Push 1 view controller"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let color = UIImage.image(color: .white)
navigationController?.setNavigationBarHidden(false, animated: true)
self.activeNavigationBar?.setBackgroundImage(color, for: .default)
self.activeNavigationBar?.shadowImage = UINavigationBar().shadowImage
self.activeNavigationBar?.titleTextAttributes = [.foregroundColor: UIColor.black]
}
}
class UnwindPopViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
<file_sep>/UIKit/UICollectionView+GridLayout.swift
//
// UICollectionView+GridLayout.swift
// SiFUtilities
//
// Created by <NAME> on 8/17/21.
//
import CoreGraphics
import Foundation
import UIKit
public extension UICollectionView {
func gridItemSize(numberOfColumns: Int, heightWidthRatio: CGFloat) -> CGSize {
let guardRatio = heightWidthRatio == 0 ? 1 : heightWidthRatio
return gridItemSize(numberOfColumns: numberOfColumns, ratio: 1 / guardRatio)
}
/// Parameter: ratio equals width / height, default is 1
func gridItemSize(numberOfColumns: Int, ratio: CGFloat = 1) -> CGSize {
let guardRatio = ratio == 0 ? 1 : ratio
guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else {
assertionFailure("‼️ The current layout is of type \(type(of: collectionViewLayout)) but the function gridItemSize(numberOfColumns:ratio:) only apply for type UICollectionViewFlowLayout.")
return .zero
}
layout.estimatedItemSize = .zero
let containerWidth = bounds.width
let contentInsets = contentInset
let sectionInsets = layout.sectionInset
let totalInsetsHorizontalSpace = contentInsets.left + contentInsets.right + sectionInsets.left + sectionInsets.right
let columns = CGFloat(numberOfColumns)
let width = (containerWidth - totalInsetsHorizontalSpace - (columns - 1) * layout.minimumInteritemSpacing) / columns
let height = width / guardRatio
let calculatedItemSize = CGSize(width: width, height: height)
return calculatedItemSize
}
}
<file_sep>/Loading/UIViewController+Loading.swift
//
// UIViewController+Loading.swift
// SiFUtilities
//
// Created by FOLY on 9/22/18.
//
import Foundation
import UIKit
extension UIViewController {
// MARK: - Loading
@objc open func showLoading(animated: Bool = false) {
self.view.showLoading(animated: animated)
}
@objc open func hideLoading(animated: Bool = false) {
self.view.hideLoading(animated: animated)
}
}
<file_sep>/Localize/UILabel+Localize.swift
//
// UIControl+Localize.swift
// SiFUtilities
//
// Created by FOLY on 11/17/18.
//
import Foundation
import UIKit
// @IBDesignable
extension UILabel {
@IBInspectable open var textLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedTextKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedTextKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
text = attributes[.localizedTextKey]?.localized
}
@objc override open func updateLanguage() {
if let key = textLocalizedKey {
updateLocalize(attributes: [.localizedTextKey: key])
}
}
}
<file_sep>/UIKit/UIView++.swift
//
// UIView++.swift
// SiFUtilities
//
// Created by <NAME> on 3/4/21.
//
import Foundation
import UIKit
public extension UIView {
func fillSubview(_ subview: UIView,
below topView: UIView? = nil,
back leftView: UIView? = nil,
above bottomView: UIView? = nil,
front rightView: UIView? = nil,
edgeInsets: UIEdgeInsets = .zero) {
subview.translatesAutoresizingMaskIntoConstraints = false
addSubview(subview)
NSLayoutConstraint.activate([
subview.leadingAnchor.constraint(equalTo: leftView?.trailingAnchor ?? leadingAnchor, constant: edgeInsets.left),
subview.trailingAnchor.constraint(equalTo: rightView?.leadingAnchor ?? trailingAnchor, constant: -edgeInsets.right),
subview.topAnchor.constraint(equalTo: topView?.bottomAnchor ?? topAnchor, constant: edgeInsets.top),
subview.bottomAnchor.constraint(equalTo: bottomView?.topAnchor ?? bottomAnchor, constant: -edgeInsets.bottom),
])
}
func fillSubview(_ subview: UIView,
below topAnchor: NSLayoutYAxisAnchor?,
back leadingAnchor: NSLayoutXAxisAnchor?,
above bottomAnchor: NSLayoutYAxisAnchor?,
front trailingAnchor: NSLayoutXAxisAnchor?,
edgeInsets: UIEdgeInsets = .zero) {
subview.translatesAutoresizingMaskIntoConstraints = false
addSubview(subview)
NSLayoutConstraint.activate([
subview.leadingAnchor.constraint(equalTo: leadingAnchor ?? self.leadingAnchor, constant: edgeInsets.left),
subview.trailingAnchor.constraint(equalTo: trailingAnchor ?? self.trailingAnchor, constant: -edgeInsets.right),
subview.topAnchor.constraint(equalTo: topAnchor ?? self.topAnchor, constant: edgeInsets.top),
subview.bottomAnchor.constraint(equalTo: bottomAnchor ?? self.bottomAnchor, constant: -edgeInsets.bottom),
])
}
}
public extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
for subview in subviews {
if let firstResponder = subview.firstResponder {
return firstResponder
}
}
return nil
}
}
<file_sep>/Localize/UISegmentControl+Localize.swift
//
// UISegmentControl+Localize.swift
// SiFUtilities
//
// Created by FOLY on 12/8/18.
//
import Foundation
import UIKit
/// The segment titles are separated by single character ',' (no space). For example: 'title1,title2,title3'
// @IBDesignable
extension UISegmentedControl {
@IBInspectable public var titlesLocalizedKey: String? {
get {
return getStringValue(by: &RunTimeKey.localizedArrayKey)
}
set {
setStringValue(newValue, forRuntimeKey: &RunTimeKey.localizedArrayKey)
}
}
@objc override open func updateLocalize(attributes: [LocalizedKey: String]) {
if let value = attributes[.localizedTitleKey] {
let components = value.components(separatedBy: ",")
for i in 0 ..< numberOfSegments {
if i < components.count {
let title = components[i]
setTitle(title.localized, forSegmentAt: i)
}
}
}
}
@objc override open func updateLanguage() {
if let key = titlesLocalizedKey {
updateLocalize(attributes: [.localizedTitleKey: key])
}
}
}
|
2a0b1c5fdf7759b295c1dd95a59ead5e8febe71b
|
[
"Swift",
"Ruby",
"Markdown"
] | 49 |
Swift
|
congncif/SiFUtilities
|
1045d5198d063d19d3fd0c4d11dbf6c0bf912567
|
f707680b167482fa638e347acf35c6e468d1a1df
|
refs/heads/master
|
<file_sep>
import {expect} from 'chai';
import 'aurelia-polyfills';
import {TodoView} from './../../src/views/todo-view/todo-view';
describe('TodoView Tests', function() {
let todoView;
/*
beforeEach(function() {
todoView = new TodoView ();
});
it('constructor', function() {
expect(todoView).to.not.be.null;
});
it('not constructor', function() {
expect(() => TodoView()).to.throw("Cannot call a class as a function");
}); */
})
<file_sep>import {DataStore} from './../../lib/data-store';
import {DomManager} from './../../lib/dom-manager';
import {TodoModel} from './../../lib/todo-model';
/**
* Class that uses the other classes to preform relevant actions
*/
export class TodoView {
constructor(){
this.todoListId = "orderList";
this.todoInputId = "todoItemInput";
this.searchInputId = "search";
console.log(document);
this.datastore = new DataStore("todoItems");
this.domManager = new DomManager(this.todoListId, this.todoInputId, this.searchInputId, document);
this.domManager.buildListForDisplay(this.datastore.items);
this.addTodoItemHandler = this.domManager.registerEvent("addToList", "click", this.addTodoItem.bind(this));
this.removeCheckedItemsFromListHandler = this.domManager.registerEvent("removeItemsFromList", "click", this.removeCheckedItemsFromList.bind(this));
this.completeCheckedItemsFromListHandler = this.domManager.registerEvent("completeItems", "click", this.completeCheckedItemsFromList.bind(this));
this.searchKeyUpHandler = this.domManager.registerEvent("search", "keyup", this.searchKeyUp.bind(this));
this.comboBoxHandler = this.comboBoxChecked.bind(this);
this.domManager.list.addEventListener("comboBoxChecked", this.comboBoxHandler, false);
}
dispose(){
this.domManager.unregisterEvent("addToList", "click", this.addTodoItemHandler);
this.domManager.unregisterEvent("removeItemsFromList", "click", this.removeCheckedItemsFromListHandler);
this.domManager.unregisterEvent("completeItems", "click", this.completeCheckedItemsFromListHandler);
this.domManager.unregisterEvent("search", "keyup", this.searchKeyUpHandler);
this.domManager.list.removeEventListener("comboBoxChecked", this.comboBoxHandler);
this.comboBoxHandler = null;
this.datastore.dispose();
this.datastore = null;
this.domManager.dispose();
this.domManager = null;
}
/**
* combobox checked/unchecked event
* @param args
*/
comboBoxChecked(args){
this.datastore.selectItem(args.detail.id, args.detail.isChecked);
}
/**
* trigger filter based on newest value in searchbox
*/
searchKeyUp(){
let searchValue = this.domManager.searchInput.value;
this.domManager.buildListForDisplay(this.datastore.filterItems(searchValue));
}
/**
* Add new Li item based on text in textbox
*/
addTodoItem(){
let newToDoValue = this.domManager.todoInput.value;
let newItem = this.datastore.addItem(new TodoModel(newToDoValue));
this.domManager.addLiItem(newItem);
}
/**
* loop through checked items and remove them from list
*/
removeCheckedItemsFromList(){
let selectedIds = this.datastore.getSelectedItemsIdCollection();
this.domManager.removeSelectedItems(selectedIds);
this.datastore.removeSelectedItems();
}
/**
* loop through checked items and complete them from list
*/
completeCheckedItemsFromList(){
let selectedIds = this.datastore.getSelectedItemsIdCollection();
this.domManager.completeSelectedItems(selectedIds);
this.datastore.completeSelectedItems();
}
}
<file_sep>import {expect, assert} from 'chai';
import {Hello} from './../../src/lib/hello.js';
describe('Hello Tests', function() {
let instance;
beforeEach(function() {
instance = new Hello();
});
it('constructor', function() {
// Assert
expect(instance).to.not.be.null;
});
it('not constructor', function() {
// Assert
expect(() => Hello()).to.throw("Cannot call a class as a function");
});
it('dispose', function() {
// Act
instance.dispose();
// Assert
// .. put your code here
});
});<file_sep>
import {expect, assert} from 'chai';
import * as sinon from 'sinon';
import 'aurelia-polyfills';
import {DataStore} from './../../src/lib/data-store';
import {TodoModel} from './../../src/lib/todo-model';
import './../mock/storage-mock';
describe('DataStore Tests', function() {
let dataStore;
beforeEach(function() {
dataStore = new DataStore ('storeId');
dataStore.clearStore();
});
afterEach(function() {
});
it('constructor', function() {
expect(dataStore).to.not.be.null;
});
it('not constructor', function() {
expect(() => DataStore()).to.throw("Cannot call a class as a function");
});
describe('getNextId', function() {
it('returns 1 at default', function() {
expect(dataStore.getNextId()).to.equal(1);
});
it('returns 4 when setting current id to 3', function() {
dataStore.currentId = 3;
expect(dataStore.getNextId()).to.equal(4);
});
it('returns items length plus one when current id 0', function() {
dataStore.currentId = 0;
dataStore.items = [{id: 1}, {id:44}];
expect(dataStore.getNextId()).to.equal(45);
});
});
describe('getSelectedItemsIdCollection', function() {
it('none selected returns empty array', function() {
dataStore.items = [{isSelected:false}, {isSelected:false}];
expect(dataStore.getSelectedItemsIdCollection()).to.eql([]);
});
it('only 1 selected returns single element', function() {
dataStore.items = [{isSelected:true, id:1}, {isSelected:false, id:4}];
expect(dataStore.getSelectedItemsIdCollection()).to.eql([1]);
});
it('more than 1 selected returns all elements', function() {
dataStore.items = [{isSelected:true, id:1},
{isSelected:true, id:6},
{isSelected:false, id:3},
{isSelected:false, id:4}];
expect(dataStore.getSelectedItemsIdCollection()).to.eql([1,6]);
});
});
describe('getIndex', function() {
it('find id returns index', function() {
dataStore.items = [{id:1}, {id:7}, {id:11}];
expect(dataStore.getIndex(7)).to.eql(1);
});
it('id not found returns -1', function() {
dataStore.items = [{id:1}, {id:7}, {id:11}];
expect(dataStore.getIndex(4)).to.eql(-1);
});
});
describe('getItem', function() {
it('get Item returns item', function() {
dataStore.items = [{id:1}, {id:7}, {id:11}];
expect(dataStore.getItem(7)).to.eql({id:7});
});
it('get Item not found returns NaN', function() {
dataStore.items = [{id:1}, {id:7}, {id:11}];
expect(dataStore.getItem(4)).to.equal(undefined);
});
});
describe('filterItems', function() {
it('filter phrase match one item', function() {
dataStore.items = [{value:'test'}, {value:'fail'}, {value:'one'}];
expect(dataStore.filterItems('o')).to.eql([{value:'one'}]);
});
it('filter phrase match multiple items', function() {
dataStore.items = [{value:'test'}, {value:'son'}, {value:'one'}];
expect(dataStore.filterItems('on')).to.eql([{value:'son'},{value:'one'}]);
});
it('filter phrase match no items', function() {
dataStore.items = [{value:'test'}, {value:'son'}, {value:'one'}];
expect(dataStore.filterItems('ons')).to.eql([]);
});
});
describe('addItem', function() {
it('add item success', function() {
//Arrange
const saveSpy = sinon.spy(dataStore, 'saveStore');
const todoModel = new TodoModel('test');
//Act
dataStore.addItem(todoModel);
//Assert
expect(dataStore.items.length).to.equal(1);
expect(dataStore.items[0]).to.eql(todoModel);
assert(saveSpy.calledOnce, 'saveStore should be called at least once');
saveSpy.restore();
});
});
describe('selectItem', function() {
beforeEach(function() {
dataStore = new DataStore ('storeId');
dataStore.clearStore();
});
it('item selected when sending true', function() {
//Arrange
const saveSpy = sinon.spy(dataStore, 'saveStore');
const getIndexSpy = sinon.spy(dataStore, 'getIndex');
const todoModel = new TodoModel('test');
todoModel.id = 1;
dataStore.items.push(todoModel);
console.log(dataStore.items);
expect(dataStore.items[0].isSelected).to.equal(false);
//Act
dataStore.selectItem(1, true);
//Assert
expect(dataStore.items[0].isSelected).to.equal(true);
assert(getIndexSpy.calledOnce, 'getIndexSpy should be called at least once');
assert(saveSpy.calledOnce, 'saveStore should be called at least once');
saveSpy.restore();
});
it('item deselected when sending false', function() {
//Arrange
const saveSpy = sinon.spy(dataStore, 'saveStore');
const getIndexSpy = sinon.spy(dataStore, 'getIndex');
const todoModel = new TodoModel('test');
todoModel.id = 1;
todoModel.isSelected = true;
dataStore.items.push(todoModel);
expect(dataStore.items[0].isSelected).to.equal(true);
//Act
dataStore.selectItem(1, false);
//Assert
expect(dataStore.items[0].isSelected).to.equal(false);
assert(getIndexSpy.calledOnce, 'getIndexSpy should be called at least once');
assert(saveSpy.calledOnce, 'saveStore should be called at least once');
saveSpy.restore();
});
it('item not found save store not called', function() {
//Arrange
const saveSpy = sinon.spy(dataStore, 'saveStore');
const getIndexSpy = sinon.spy(dataStore, 'getIndex');
const todoModel = new TodoModel('test');
todoModel.id = 2;
dataStore.items.push(todoModel);
expect(dataStore.items[0].isSelected).to.equal(false);
console.log(dataStore.items);
//Act
dataStore.selectItem(1, true);
//Assert
expect(dataStore.items[0].isSelected).to.equal(false);
assert(getIndexSpy.calledOnce, 'getIndexSpy should be called at least once');
expect(saveSpy.callCount).to.equal(0);
saveSpy.restore();
});
});
describe('completeSelectedItems', function() {
beforeEach(function() {
dataStore = new DataStore ('storeId');
dataStore.clearStore();
});
it('one item completed', function() {
//Arrange
addItemToDataStore(0, 'test', true);
//Act
dataStore.completeSelectedItems();
//Assert
expect(dataStore.items[0].isComplete).to.equal(true);
});
it('multiple items completed', function() {
//Arrange
addItemToDataStore(0, 'test', true);
addItemToDataStore(1, 'test', true);
//Act
dataStore.completeSelectedItems();
//Assert
expect(dataStore.items[0].isComplete).to.equal(true);
expect(dataStore.items[1].isComplete).to.equal(true);
});
it('only selected items completed', function() {
//Arrange
addItemToDataStore(0, 'test', false);
addItemToDataStore(1, 'test', true);
//Act
dataStore.completeSelectedItems();
//Assert
expect(dataStore.items[0].isComplete).to.equal(false);
expect(dataStore.items[1].isComplete).to.equal(true);
});
});
describe('removeSelectedItems', function() {
beforeEach(function() {
dataStore = new DataStore ('storeId');
dataStore.clearStore();
});
it('one item removed', function() {
//Arrange
addItemToDataStore(0, 'test', true);
expect(dataStore.items.length).to.equal(1);
//Act
dataStore.removeSelectedItems();
//Assert
expect(dataStore.items.length).to.equal(0);
});
it('multiple items removed', function() {
//Arrange
addItemToDataStore(0, 'test', true);
addItemToDataStore(1, 'test', true);
expect(dataStore.items.length).to.equal(2);
//Act
dataStore.removeSelectedItems();
//Assert
expect(dataStore.items.length).to.equal(0);
});
it('only selected items removed', function() {
//Arrange
addItemToDataStore(0, 'test', false);
addItemToDataStore(1, 'test', true);
expect(dataStore.items.length).to.equal(2);
//Act
dataStore.removeSelectedItems();
//Assert
expect(dataStore.items.length).to.equal(1);
});
});
function addItemToDataStore(id = 0, value = 'test', isSelected = false, isCompleted = false){
const todoModel = new TodoModel(value);
todoModel.isSelected = isSelected;
todoModel.isComplete = isCompleted;
todoModel.id = id;
dataStore.items.push(todoModel);
}
})
<file_sep>/**
* Class responsible for saving and retrieving data from local storage.
*/
export class DataStore {
constructor(storeId) {
this.storeId = storeId;
this.items = this.loadStore();
this.currentId = 0;
}
/**
* Manage the id system and give me the next id when requested
*/
getNextId() {
if(this.currentId == 0 && this.items.length > 0) {
this.currentId = this.items[this.items.length - 1].id;
}
this.currentId++;
return this.currentId;
}
/**
* On startup if I exist load me
*/
loadStore() {
let storeItem = localStorage.getItem(this.storeId);
if(storeItem === null){
return [];
}
return JSON.parse(storeItem);
}
/**
* Save store
*/
saveStore() {
return localStorage.setItem(this.storeId, JSON.stringify(this.items));
}
clearStore() {
localStorage.clear();
}
/**
* get items in data store that are selected
* @returns {Array}
*/
getSelectedItemsIdCollection() {
return this.items.filter(item => item.isSelected).map(item => item.id);
}
/**
* add new item to datastore
* */
addItem(model) {
model.id = this.getNextId();
this.items.push(model);
this.saveStore();
return model;
}
/**
* remove selected items from data store
*/
removeSelectedItems() {
this.processSelectedItems(index => this.items.splice(index, 1));
}
/**
* complete selected items from data store
*/
completeSelectedItems() {
this.processSelectedItems(index => this.items[index].isComplete = true);
}
/**
* process selected items
* @param callback
*/
processSelectedItems(callback){
let selectedItems = this.getSelectedItemsIdCollection();
for(let i = 0; i < selectedItems.length; i++){
let index = this.items.findIndex(el => el.id === selectedItems[i]);
if(index > -1) {
callback(index);
}
}
this.saveStore();
}
/**
* mark item as selected or deselected
* @param id
* @param isSelected
*/
selectItem(id, isSelected){
const index = this.getIndex(id);
if(index > -1){
this.items[index].isSelected = isSelected;
this.saveStore();
}
}
/**
* return index of id
* @param id
* @returns {number}
*/
getIndex(id){
return this.items.findIndex(el => el.id == id);
}
/**
* find and return stored item
* @param id
* @returns {*}
*/
getItem(id) {
return this.items.find(el => el.id == id);
}
/**
* filter datastore based on search text*/
filterItems(filterPhrase) {
return this.items.filter(el => el.value.includes(filterPhrase));
}
}<file_sep>class LocalStorage {
constructor(){
this.items = new Map();
}
setItem(key, value){
this.items.set(key, value);
}
getItem(key){
if(this.items.has(key)){
return this.items.get(key);
}
return null;
}
clear(){
this.items.clear();
}
}
global.localStorage = new LocalStorage();<file_sep>
import {expect} from 'chai';
import 'aurelia-polyfills';
import {DomManager} from './../../src/lib/dom-manager';
import {TodoModel} from './../../src/lib/todo-model';
import {ElementMockup} from './../mock/element-mockup';
import './../mock/document-mockup';
describe('DomManager Tests', function() {
let domManager;
let element;
beforeEach(function() {
createAndAppendElement('orderList', 'unordered-list');
createAndAppendElement('todoItemInput', 'input');
createAndAppendElement('search', 'input');
domManager = new DomManager ("orderList", "todoItemInput", "search");
});
function createAndAppendElement(id, type) {
element = global.document.createElement(type);
element.id = id;
global.document.appendChild(element);
}
it('constructor', function() {
expect(domManager).to.not.be.null;
});
it('not constructor', function() {
expect(() => DomManager()).to.throw("Cannot call a class as a function");
});
describe('createLiItem', function() {
it('create new item values set and created', function() {
//Arrange
let value = 'test';
let model = new TodoModel(value);
//Act
let item = domManager.createLiItem(model);
//Assert
expect(item.children[0].innerText).to.equal(value);
expect(item.children[0].id).to.equal(`li${model.id}`);
expect(item.children[0].style.textDecoration).to.equal(undefined);
expect(item.children[0].nodeType).to.equal('li');
expect(item.children[0].children[0].nodeType).to.equal('input');
expect(item.children[0].children[0].id).to.equal(`li${model.id}_checkbox`);
});
it('create new item values set and created', function() {
//Arrange
let value = 'test';
let model = new TodoModel(value);
model.isComplete = true;
//Act
let item = domManager.createLiItem(model);
//Assert
expect(item.children[0].innerText).to.equal(value);
expect(item.children[0].id).to.equal(`li${model.id}`);
expect(item.children[0].style.textDecoration).to.equal(`line-through`);
expect(item.children[0].nodeType).to.equal('li');
expect(item.children[0].children[0].nodeType).to.equal('input');
expect(item.children[0].children[0].id).to.equal(`li${model.id}_checkbox`);
});
});
describe('addLiItem', function() {
it('add li item, item added', function() {
//Arrange
let value = 'test';
let model = new TodoModel(value);
expect(domManager.list.children.length).to.equal(0);
//Act
let item = domManager.addLiItem(model);
//Assert
expect(domManager.list.children.length).to.equal(1);
});
});
describe('buildListForDisplay', function() {
beforeEach(function() {
while(domManager.list.children.length > 0){
domManager.list.children.pop();
}
});
it('all items added correctly', function() {
//Arrange
let modelArray = [new TodoModel('buildItem1'),new TodoModel('buildItem2'),new TodoModel('buildItem3')];
expect(domManager.list.children.length).to.equal(0);
let fragment = document.createDocumentFragment();
fragment.appendChild(document.createElement('li'));
domManager.list.appendChild(fragment);
expect(domManager.list.children.length).to.equal(1);
//Act
domManager.buildListForDisplay(modelArray);
//Assert
expect(domManager.list.children.length).to.equal(3);
});
});
})
<file_sep>/**
* Class responsible for manipulating the DOM
*/
export class DomManager {
constructor(listId, todoId, searchId, document){
this.listId = listId;
this.document = document;
this.list = this.document.getElementById(listId);
this.todoInput = this.document.getElementById(todoId);
this.searchInput = this.document.getElementById(searchId);
console.log(this.list);
console.log(this.todoInput);
console.log(this.searchInput);
this.raiseEventHandler = this.registerEvent(listId, "click", this.raiseEvent.bind(this));
}
dispose() {
this.unregisterEvent(this.listId, "click", this.raiseEventHandler);
this.list = null;
this.todoInput = null;
this.searchInput = null;
}
registerEvent(id, event, handler) {
this.document.getElementById(id).addEventListener(event, handler);
return handler;
}
unregisterEvent(id, event, handler) {
this.document.getElementById(id).removeEventListener(event, handler);
handler = null;
}
/**
* remove selected items from DOM
* @param ids* <li id="li1><input type="checkbox" id="li1_checkbox"
*/
removeSelectedItems(ids) {
this.processDomItems(ids, item => this.list.removeChild(item));
}
/**
* complete selected items from DOM
* @param ids
*/
completeSelectedItems(ids) {
this.processDomItems(ids, item => item.style.textDecoration = "line-through");
}
/**
* process dom items
* @param ids
* @param callback
*/
processDomItems(ids, callback) {
while(ids.length > 0){
const query = `#li${ids[0]}`;
let liItem = this.list.querySelector(query);
callback(liItem);
ids.shift();
}
}
/**
* Method to create li item with check box
*/
createLiItem(newItem){
let fragment = this.document.createDocumentFragment();
let item = this.document.createElement("li");
item.innerText = newItem.value;
item.id = `li${newItem.id}`;
if(newItem.isComplete){
item.style.textDecoration = "line-through";
}
let checkbox = this.document.createElement("input");
checkbox.id = `li${newItem.id}_checkbox`;
checkbox.type = "checkbox";
checkbox.className = "check";
checkbox.checked = newItem.isSelected;
item.appendChild(checkbox);
fragment.appendChild(item);
return fragment;
}
/**
* raise combobox checked event
* @param event
*/
raiseEvent(event){
if(event.target.className == "check") {
let cusevent = new CustomEvent(
"comboBoxChecked",
{
detail: {
id: event.target.parentNode.id.substr(2),
isChecked: event.target.checked
},
bubbles: true,
cancelable: true
}
);
event.target.dispatchEvent(cusevent);
}
}
/**
* Add new Li item based on text in textbox
*/
addLiItem(newModel){
let fragment = this.createLiItem(newModel);
this.list.appendChild(fragment);
}
/**
* Build unordered list based on data store items (for large lists you would use a checksum, for this size it does not need that complexity)
*/
buildListForDisplay(items){
while(this.list.firstChild() ){
this.list.removeChild(this.list.firstChild());
}
for (let i = 0, len = items.length; i < len; i++) {
let fragment = this.createLiItem(items[i]);
this.list.appendChild(fragment);
}
}
}
<file_sep>/**
* Class responsible for to do object properties and methods related to model
*/
import {bindable} from "aurelia-framework";
export class TodoModel {
id;
@bindable value;
@bindable isComplete;
@bindable isSelected;
constructor(value) {
this.id = 0;
this.value = value;
this.isComplete = false;
this.isSelected = false;
}
isSelectedChanged(){
console.log(this.isSelected);
}
}
<file_sep>export class App {
router = null;
configureRouter(config, router) {
config.title = 'Pragma Products';
config.map([
{route: ['', 'todo-view-auerelia'], name: 'todo-view-auerelia', moduleId: 'views/todo-view/todo-view-auerelia', nav: true, title: 'Todo View'},
]);
this.router = router;
}
}<file_sep>
import {expect} from 'chai';
import 'aurelia-polyfills';
import {TodoModel} from './../../src/lib/todo-model';
describe('TodoModel Tests', function() {
let todoModel;
beforeEach(function() {
todoModel = new TodoModel ('test');
});
it('constructor', function() {
expect(todoModel).to.not.be.null;
});
it('not constructor', function() {
expect(() => TodoModel()).to.throw("Cannot call a class as a function");
});
it('default values set', function(){
expect(todoModel.id).to.be.equal(0);
expect(todoModel.isComplete).to.be.equal(false);
expect(todoModel.isSelected).to.be.equal(false);
expect(todoModel.value).to.be.equal('test');
})
})
|
20cbe472cb4e66ae4b8e861fffa4bc9682aacc46
|
[
"JavaScript"
] | 11 |
JavaScript
|
carlsimonvg/auerlia-todo
|
16c99643a2d522573b13b9d6a1d4cacde3053ce9
|
99d100df9007c78e1b99fee9229697056022c6e1
|
refs/heads/master
|
<repo_name>arifbudimanarrosyid/ExerciseSqlite<file_sep>/app/src/main/java/com/example/exercisesqlite/tambah_data.java
package com.example.exercisesqlite;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class tambah_data extends AppCompatActivity {
int id_To_Update = 0;
private DBHelper mydb;
EditText etNama, etPhone, etEmail, etAlamat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tambah_data);
etNama = (EditText) findViewById(R.id.addnama);
etPhone = (EditText) findViewById(R.id.addNoTelp);
etEmail = (EditText) findViewById(R.id.addEmail);
etAlamat = (EditText) findViewById(R.id.addAlamat);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras != null){
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String name = rs.getString(rs.getColumnIndex(DBHelper.COLUMN_NAMA));
String phone = rs.getString(rs.getColumnIndex(DBHelper.COLUMN_PHONE));
String email = rs.getString(rs.getColumnIndex(DBHelper.COLUMN_EMAIL));
String alamat = rs.getString(rs.getColumnIndex(DBHelper.COLUMN_ALAMAT));
if (!rs.isClosed()){
rs.close();
}
Button btnSimpan = (Button) findViewById(R.id.btn1);
btnSimpan.setVisibility(View.INVISIBLE);
etNama.setText((CharSequence)name);
etNama.setFocusable(false);
etNama.setClickable(false);
etPhone.setText((CharSequence)phone);
etPhone.setFocusable(false);
etPhone.setClickable(false);
etEmail.setText((CharSequence)email);
etEmail.setFocusable(false);
etEmail.setClickable(false);
etAlamat.setText((CharSequence)alamat);
etAlamat.setFocusable(false);
etAlamat.setClickable(false);
}
}
}
public void run(View view){
if (etNama.getText().toString().equals("")||
etPhone.getText().toString().equals("")||
etEmail.getText().toString().equals("")||
etAlamat.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Data Harus Diisi Semua!", Toast.LENGTH_LONG).show();
}else{
mydb.insertContact(etNama.getText().toString(), etPhone.getText().toString(), etEmail.getText().toString(), etAlamat.getText().toString());
Toast.makeText(getApplicationContext(), "Insert Data Berhasil", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
}
|
6eddd7139c7f279b20c21ab18d360abe34c2c0f3
|
[
"Java"
] | 1 |
Java
|
arifbudimanarrosyid/ExerciseSqlite
|
09315580cc201c992adc1a79fd4085cfd718b5fe
|
da7068530dcf2cbde756d93bfc75917915614d0a
|
refs/heads/master
|
<repo_name>klwilson23/StatisticalRethinking<file_sep>/Week 4/Week 4 - in class.R
library(rethinking)
library(MASS)
options(mc.cores = 4)
rstan_options(auto_write = TRUE)
Sys.setenv(LOCAL_CPPFLAGS = '-march=native')
## load the dataset milk
# does brain composition explain milk energy
data(milk)
milk
# use complete.cases()
milk_c <- milk[complete.cases(milk),]
# look at the data - check for correlation
pairs(data=milk_c, ~ kcal.per.g + neocortex.perc + mass,lower.panel=panel.smooth)
cor(milk_c$neocortex.perc, milk_c$mass)
# STAN code
stan_model <- "
data{
int N;
vector[N] kcal_per_g;
vector[N] neocortex_c; // centering the data
}
parameters {
real a; // intercept
real b_neo; // slope with neocortex
real sigma; // variance with kcal_per_g
}
model{
vector[N] mu = a + b_neo*neocortex_c; // mean response in kcal
kcal_per_g ~ normal(mu, sigma); // likelihood
a ~ normal(mean(kcal_per_g), sd(kcal_per_g)); // prior on alpha
b_neo ~ normal(0, 1); // prior on slope
sigma ~ cauchy(0, 1); // half-t distribution for variance
}
"
dat_centered <- list("N"=nrow(milk_c),
"kcal_per_g"=milk_c$kcal.per.g,
"neocortex_c"=milk_c$neocortex.perc-mean(milk_c$neocortex.perc))
milk_fit <- stan(model_code=stan_model,
data=dat_centered,
chains=2,iter=2000,pars=c("a","b_neo","sigma"))
apply(summary(milk_fit)$summary,2,round,3)
# plot our model of kcal_per_g ~ neocortex_c
layout(matrix(1:4,nrow=2,ncol=2,byrow=T))
# get the posterior as a data.frame
post1 <- as.data.frame(milk_fit)
dim(post1)
# make the plot
plot(kcal_per_g~neocortex_c,data=dat_centered,pch=21,bg="dodgerblue",main="~ %Neocortex")
invisible(sapply(1:250, function(i){
curve(post1[i,"a"]+post1[i,"b_neo"]*x,min=-15,max=15,add=T,lwd=2,col=adjustcolor("grey",alpha=0.2))}))
curve(mean(post1[,"a"])+mean(post1[,"b_neo"])*x,lwd=2,add=T,col="black")
# posterior predictive distribution
neocortex_seq <- seq(from=-20,to=20,by=1)
post_pred <- matrix(NA, nrow=nrow(post1),ncol=length(neocortex_seq))
for(i in 1:nrow(post1))
{
post_pred[i,] <- rnorm(length(neocortex_seq),mean=post1[i,"a"]+post1[i,"b_neo"]*neocortex_seq,sd=post1[i,"sigma"])
}
mn_ppd <- colMeans(post_pred)
ci_ppd <- apply(post_pred,2,HPDI,0.89)
plot(kcal_per_g~neocortex_c,data=dat_centered,pch=21,bg="dodgerblue", main="Posterior predictive distribution",ylim=c(0,1))
lines(neocortex_seq,mn_ppd,lwd=2)
rethinking::shade(ci_ppd,neocortex_seq,0.89)
# multiple regression. MORE PREDICTORS!!!
# kcal_per_g ~ neocortex_c + logmass_c
stan_code2 <- "
data{
int N;
vector [N] kcal_per_g;
vector[N] neocortex_c;
vector[N] logmass_c;
}
parameters{
real a;
real b_neo;
real b_mass;
real sigma;
}
model{
vector[N] mu = a + b_neo*neocortex_c + b_mass*logmass_c;
kcal_per_g ~ normal(mu,sigma);
a ~ normal(0,100);
b_neo ~ normal(0,100);
b_mass ~ normal(0,100);
sigma ~ cauchy(0,1);
}
"
dat_Multi <- list("N"=nrow(milk_c),
"kcal_per_g"=milk_c$kcal.per.g,
"neocortex_c"=milk_c$neocortex.perc-mean(milk_c$neocortex),
"logmass_c"=log(milk_c$mass)-mean(log(milk_c$mass)))
fit <- stan(model_code=stan_code2,data=dat_Multi,iter=2000,chains=2,pars=c("a","b_neo","b_mass","sigma"))
apply(summary(fit)$summary,2,round,3)
post2 <- as.data.frame(fit)
post_pred <- matrix(NA, nrow=nrow(post2),ncol=nrow(milk_c))
for(i in 1:nrow(post2))
{
post_pred[i,] <- rnorm(nrow(milk_c),mean=post2[i,"a"]+post2[i,"b_neo"]*dat_Multi$neocortex_c+post2[i,"b_mass"]*dat_Multi$logmass_c,sd=post2[i,"sigma"])
}
hpdi <- apply(post_pred,2,HPDI,0.89)
mn_ppd <- colMeans(post_pred)
plot(dat_Multi$kcal_per_g,mn_ppd,pch=21,bg="dodgerblue",ylim=range(hpdi))
segments(x0=dat_Multi$kcal_per_g,y0=hpdi[1,],y1=hpdi[2,])
abline(b=1,a=0)
post_pred2 <- matrix(NA, nrow=nrow(post2), ncol=length(neocortex_seq))
for(i in 1:nrow(post_pred)) {
post_pred2[i,] <- rnorm(length(neocortex_seq),
mean=post2$a[i] + post2$b_neo[i]*neocortex_seq,
sd=post2$sigma[i])
}
mn_ppd <- colMeans(post_pred2)
ci_ppd <- apply(post_pred2,2,HPDI,0.89)
plot(kcal_per_g~neocortex_c,data=dat_centered,pch=21,bg="dodgerblue", main="Posterior predictive distribution",ylim=c(0,1))
lines(neocortex_seq,mn_ppd,lwd=2)
rethinking::shade(ci_ppd,neocortex_seq,0.89)
# categorical variables
str(milk)
# kcal.per.g ~ cladeA + cladeB + cladeC + cladeD
X <- model.matrix(kcal.per.g~clade,milk)
stanCat <- "
data{
int N;
int K; // number of clades
vector[N] kcal_per_g;
matrix[N,K] clades; // matrix of clades
}
parameters{
vector[K] beta;
real sigma;
}
model{
kcal_per_g ~ normal(clades*beta,sigma);
beta[1] ~ normal(mean(kcal_per_g),10); // prior for the intercept
for(i in 2:K)
{
beta[i] ~ normal(0,1); // prior on intercepts
}
sigma ~ cauchy(0,1);
}
"
datCat <- list("N"=nrow(milk),
"K"=length(unique(milk$clade)),
"kcal_per_g"=milk$kcal.per.g,
"clades"=X)
fitCat <- stan(model_code=stanCat,data=datCat,iter=2000,chains=2,pars=c("beta","sigma"))
fitCat
aggregate(kcal.per.g~clade,data=milk,mean)
<file_sep>/Week 3/Week 3 code - Kyle.R
library(rethinking)
library(MASS)
options(mc.cores = 2)
rstan_options(auto_write = TRUE)
Sys.setenv(LOCAL_CPPFLAGS = '-march=native')
## load the dataset Howell1
data(Howell1)
d <- Howell1
# filter for adults: people > 18 years old
d2 <- d[ d$age >= 18 , ]
# look at the structure of the data
str( d2 )
layout(matrix(1:2,ncol=2))
dens(d2$height)
hist(d2$height)
layout(1)
## R code 4.25
flist <- alist(
height ~ dnorm( mu , sigma ) ,
mu ~ dnorm( 178 , 20 ) ,
sigma ~ dunif( 0 , 50 )
)
## fit the model via Gaussian approximation
m4.1 <- map( flist , data=d2 )
## R code 4.27
precis( m4.1 )
## R code 4.28
start <- list(
mu=mean(d2$height),
sigma=sd(d2$height)
)
# fit the model again with a strong prior on mu: let's say from a previous study
m4.2 <- map(
alist(
height ~ dnorm( mu , sigma ) ,
mu ~ dnorm( 178 , 0.1 ) ,
sigma ~ dunif( 0 , 50 )
) ,
data=d2,start=start)
precis( m4.2 )
# extract variance-covariance matrix
vcov( m4.1 )
## interact with variance-covariance matrix
diag( vcov( m4.1 ) )
# convert to correlation coefficients: bounded between -1 and 1
cov2cor( vcov( m4.1 ) )
## explore some priors of the data and how they influence the posterior
# compare vague prior to a strong prior
curve( dnorm( x , 178 , 20 ) , from=100 , to=250 ,lwd=2,col="orange")
curve( dnorm( x , 178 , 0.1 ) , from=100 , to=250 ,add=T,lwd=2,lty=2,col="dodgerblue")
# compare strong prior and posterior distribution - dominated by prior
curve( dnorm( x , 178 , 0.1 ) , from=100 , to=250 ,lwd=2,lty=2,col="dodgerblue")
curve( dnorm( x , coef(m4.2)["mu"] , sqrt(diag(vcov(m4.2))["mu"])),add=T,lwd=2,lty=1,col="purple")
# compare vague prior and posterior distribution - dominated by data
curve( dnorm( x , 178 , 20 ) , from=100 , to=250 ,lwd=2,lty=2,col="dodgerblue",ylim=c(0,0.3))
curve( dnorm( x , coef(m4.1)["mu"] , sqrt(diag(vcov(m4.1))["mu"])),add=T,lwd=2,lty=1,col="purple")
# let's code this model in Stan:
# start with the data section
# move to estimated parameters section
# then write the model section: likelihoods!
stanModel <- "
data {
int<lower=0> N;
vector[N] height;
}
parameters {
real mu;
real<lower=0,upper=50> sigma;
}
model {
// comment log-likelihood for normal is: normal_lpdf(data | mean, standard deviation);
target += normal_lpdf(height | mu, sigma);
target += normal_lpdf(mu | 178, 20);
}
"
# make a list for the data: "N" and "height"
dat <- list(N = nrow(d2),
height = d2$height)
fit <- stan(model_code=stanModel, data=dat,
chains = 2, iter = 2000,cores=2,
pars=c("mu","sigma"),
init=function(){return(list("mu"=mean(dat$height),"sigma"=sd(dat$height)))})
print(fit, probs = c(0.10, 0.5, 0.9))
fit
plot(fit)
# store posterior samples
post <- as.data.frame(fit)
mean(post$mu);sd(post$mu)
precis(m4.1)
# okay, this is dumb. We want regression!!
plot(height~weight,data=d2,xlab="Weight (kg)",ylab="Height (cm)",pch=21,bg=ifelse(male==1,"dodgerblue","orange"))
stanRegression <- "
data {
int<lower=0> N;
vector[N] height;
vector[N] weight;
}
parameters {
real b; // intercept
real m; // slope
real<lower=0,upper=50> sigma;
}
model {
// declare length of a numeric vector called mu
vector[N] mu = m * weight + b;
target += normal_lpdf(height | mu, sigma);
target += normal_lpdf(b | mean(height), 20);
target += normal_lpdf(m | 0, 10);
}
"
dat <- list(N = nrow(d2),
height = d2$height,
weight = d2$weight)
fit <- stan(model_code=stanRegression, data=dat,
chains = 2, iter = 2000,cores=2,
pars=c("b","m","sigma"),
init=function(){return(list("b"=mean(dat$height),"m"=0,"sigma"=sd(dat$height)))})
fit
plot(fit)
post <- as.data.frame(fit)
colMeans(post)
pairs(post,lower.panel=panel.smooth)
cor(post)
# that's weird! the slope and intercept are correlated!
# to reduce the correlation, let's center the data on the average weight:
stanCentered <- "
data {
int<lower=0> N;
vector[N] height;
vector[N] weight_c;
}
parameters {
real b; // intercept
real m; // slope
real<lower=0,upper=50> sigma;
}
model {
// declare length of a numeric vector called mu
vector[N] mu = m * weight_c + b;
target += normal_lpdf(height | mu, sigma);
target += normal_lpdf(b | mean(height), 20);
target += normal_lpdf(m | 0, 10);
}
"
datCentered <- list(N = nrow(d2),
height = d2$height,
weight_c = (d2$weight-mean(d2$weight)))
fitCentered <- stan(model_code=stanCentered, data=datCentered,
chains = 2, iter = 2000,cores=2,
pars=c("b","m","sigma"),
init=function(){return(list("b"=mean(datCentered$height),"m"=0,"sigma"=sd(datCentered$height)))})
fitCentered
plot(fitCentered)
postCentered <- as.data.frame(fitCentered)
colMeans(postCentered) # average height at the average weight
colMeans(post) # average height when weight is 0
pairs(postCentered,lower.panel=panel.smooth)
cor(postCentered)
# plot the average response: what are we missing?
plot(height~weight_c,data=datCentered,pch=21,bg="dodgerblue")
invisible(sapply(1:250,function(i){
curve(postCentered$b[i]+postCentered$m[i]*x,add=T,lwd=2,col=adjustcolor("grey",alpha=0.1))
}))
curve(mean(postCentered$b)+mean(postCentered$m)*x,add=T,lwd=2)
plot(height~weight,data=dat,pch=21,bg="dodgerblue")
invisible(sapply(1:250,function(i){
curve(post$b[i]+post$m[i]*x,add=T,lwd=2,col=adjustcolor("grey",alpha=0.1))
}))
NsubSamp <- 10
datv1 <- list(N = NsubSamp,
height = d2$height[1:NsubSamp],
weight_c = (d2$weight[1:NsubSamp]-mean(d2$weight[1:NsubSamp])))
fitv1 <- stan(model_code=stanCentered, data=datv1,
chains = 2, iter = 2000,cores=2,
pars=c("b","m","sigma"))
postv1 <- as.data.frame(fitv1)
layout(matrix(1:2,nrow=2))
plot(height~weight_c,data=datv1,pch=21,bg="dodgerblue")
invisible(sapply(1:250,function(i){
curve(postv1$b[i]+postv1$m[i]*x,add=T,lwd=2,col=adjustcolor("grey",alpha=0.1))
}))
NsubSamp <- 25
datv2 <- list(N = NsubSamp,
height = d2$height[1:NsubSamp],
weight_c = (d2$weight[1:NsubSamp]-mean(d2$weight[1:NsubSamp])))
fitv2 <- stan(model_code=stanCentered, data=datv2,
chains = 2, iter = 2000,cores=2,
pars=c("b","m","sigma"))
postv2 <- as.data.frame(fitv2)
plot(height~weight_c,data=datv2,pch=21,bg="dodgerblue")
invisible(sapply(1:250,function(i){
curve(postv2$b[i]+postv2$m[i]*x,add=T,lwd=2,col=adjustcolor("grey",alpha=0.1))
}))
# create a posterior predictive distribution and plot the uncertainty in the model
weight.seq <- seq(from=-20,to=30,by=1)
post_pred <- matrix(NA,nrow=nrow(postCentered),ncol=length(weight.seq))
for(i in 1:nrow(post_pred))
{
post_pred[i,] <- rnorm(length(weight.seq),
mean=postCentered$b[i]+postCentered$m[i]*weight.seq,
sd=postCentered$sigma[i])
}
mu.mean <- apply(post_pred,2,mean)
mu.hdi <- apply(post_pred,2,HPDI,prob=0.89)
layout(1)
plot(height~weight_c,data=datCentered,pch=21,bg="dodgerblue")
polygon(c(weight.seq,rev(weight.seq)),c(mu.hdi[1,],rev(mu.hdi[2,])),col=adjustcolor("dodgerblue",0.2),border=F)
lines(weight.seq,mu.mean,col=adjustcolor("black",0.8),lwd=3)
# we've been looking at just adults for a few reasons: young people put on height more quickly than weight!
# but what about the entire dataset?
plot(height~weight,data=d)
# what about a polynomial regression?
# can use polynomial regression to understand height ~ weight for ALL ages of people
# to reduce the correlation, let's center the data on the average weight:
stanPoly <- "
data {
int<lower=0> N;
vector[N] height;
vector[N] weight_c;
vector[N] weight_sq;
}
parameters {
real b; // intercept
real m; // slope
real poly; // polynomial inflection point
real<lower=0,upper=50> sigma;
}
model {
// declare length of a numeric vector called mu
vector[N] mu = m * weight_c + poly * weight_sq + b;
target += normal_lpdf(height | mu, sigma);
target += normal_lpdf(b | mean(height), 20); // prior on intercept
target += normal_lpdf(m | 0, 10); // prior on slope
target += normal_lpdf(poly | 0, 10); // prior on polynomial term
}
"
datPoly <- list(N = nrow(d),
height = d$height,
weight_c = (d$weight-mean(d$weight)),
weight_sq = (d$weight-mean(d$weight))^2)
fitPoly <- stan(model_code=stanPoly, data=datPoly,
chains = 2, iter = 2000,cores=2,
pars=c("b","m","poly","sigma"))
fitPoly
postPoly <- as.data.frame(fitPoly)
colMeans(postPoly) # average height at the average weight
pairs(postPoly,lower.panel=panel.smooth)
cor(postPoly)
# create a posterior predictive distribution and plot the uncertainty in the model
weight.seq <- seq(from=-40,to=40,by=1)
post_pred <- matrix(NA,nrow=nrow(postPoly),ncol=length(weight.seq))
for(i in 1:nrow(post_pred))
{
post_pred[i,] <- rnorm(length(weight.seq),
mean=postPoly$b[i]+postPoly$m[i]*weight.seq + postPoly$poly[i]*weight.seq^2,
sd=postPoly$sigma[i])
}
mu.mean <- apply(post_pred,2,mean)
mu.hdi <- apply(post_pred,2,HPDI,prob=0.89)
layout(1)
plot(height~weight_c,data=datPoly,pch=21,bg="dodgerblue")
polygon(c(weight.seq,rev(weight.seq)),c(mu.hdi[1,],rev(mu.hdi[2,])),col=adjustcolor("dodgerblue",0.2),border=F)
lines(weight.seq,mu.mean,col=adjustcolor("black",0.8),lwd=3)
<file_sep>/Week 5/Week 5 - in class.R
library(rethinking)
library(MASS)
library(loo)
options(mc.cores = 4)
rstan_options(auto_write = TRUE)
Sys.setenv(LOCAL_CPPFLAGS = '-march=native')
data("Howell1")
d <- Howell1
# check for NAs
sum(is.na(d))
# basic model
stan_linear <- "
data {
int<lower=0> N;
vector[N] height;
vector[N] weight_c;
}
parameters {
real b; // intercept
real m; // intercept
real sigma; // intercept
}
model {
// declare length of a numeric vector called mu
vector[N] mu = m*weight_c + b;
height ~ normal(mu, sigma);
b ~ normal(mean(height), 20);
m ~ normal(0, 10);
sigma ~ cauchy(5, 100);
}
generated quantities {
vector[N] log_lik; // need to code log-like into model
for(i in 1:N) {
log_lik[i] = normal_lpdf(height[i] | b + m*weight_c[i], sigma);
}
}
"
dat_linear <- list(N = nrow(d),
height=d$height,
weight_c= d$weight-mean(d$weight))
fit_linear <- stan(model_code=stan_linear,
data=dat_linear,
chains=2,
iter=2000,
cores=3,
pars=c("b","m","sigma","log_lik"))
beepr::beep(sound=8)
# the log_lik we generate is a matrix of N number of datapoints for M number of posterior samples
# we can extract them to calculate using wAIC package via the loo package
ll_linear <- extract_log_lik(fit_linear)
kyle_wAIC <- sum(-2*apply(ll_linear,2,mean)) + sum(apply(ll_linear,2,var))
kyle_DIC <- sum(-2*apply(ll_linear,1,mean)) + -2*apply(ll_linear,1,mean)
# calculate WAIC
loo::waic(ll_linear)
rethinking::WAIC(fit_linear)
stan_poly <- "
data {
int<lower=0> N;
vector[N] height;
vector[N] weight_c;
vector[N] weight_sq; //squared centered weight
}
parameters {
real b; // intercept
real m; // slope
real poly; // polynomial inflection point
real sigma; // variance
}
model {
// declare length of a numeric vector called mu
vector[N] mu = m*weight_c + poly*weight_sq + b;
height ~ normal(mu, sigma);
b ~ normal(mean(height), 20);
m ~ normal(0, 10);
poly ~ normal(0,10);
sigma ~ cauchy(5, 100);
}
generated quantities {
vector[N] log_lik; // need to code log-like into model
for(i in 1:N) {
log_lik[i] = normal_lpdf(height[i] | b + m*weight_c[i] + poly*weight_sq[i], sigma);
}
}
"
dat_poly <- list(N = nrow(d),
height=d$height,
weight_c = d$weight-mean(d$weight),
weight_sq = (d$weight-mean(d$weight))^2)
fit_poly <- stan(model_code=stan_poly,
data=dat_poly,
chains=2,
iter=2000,
cores=3,
pars=c("b","m","poly","sigma","log_lik"))
beepr::beep(sound=8)
summary(fit_poly)
log_lik_poly <- extract_log_lik(fit_poly)
waic(log_lik_poly)
waic(ll_linear)
plot(height~weight_c,data=dat_poly)
precis(fit_poly)
# even more complex!!
stan_poly_cat <- "
data {
int<lower=0> N;
vector[N] height;
vector[N] weight_c;
vector[N] weight_sq; //squared centered weight
int Nsex;
int sex[N]; // read in whether sample is male or female
}
parameters {
vector[Nsex] b; // intercept
real m; // slope
real poly; // polynomial inflection point
real sigma; // variance
}
transformed parameters {
vector[N] mu;
for(i in 1:N) {
mu[i] = m*weight_c[i] + poly*weight_sq[i] + b[sex[i]];
}
}
model {
// declare length of a numeric vector called mu
//vector[N] mu;
for(i in 1:N) {
//mu[i] = m*weight_c[i] + poly*weight_sq[i] + b[sex[i]];
height[i] ~ normal(mu[i], sigma);
}
b ~ normal(mean(height), 20);
m ~ normal(0, 10);
poly ~ normal(0,10);
sigma ~ cauchy(5, 100);
}
generated quantities {
vector[N] log_lik; // need to code log-like into model
//vector[N] new_mu;
for(i in 1:N) {
//mu[i] = b[sex[i]] + m*weight_c[i] + poly*weight_sq[i];
log_lik[i] = normal_lpdf(height[i] | mu[i], sigma);
}
}
"
dat_poly_sex <- list(N = nrow(d),
Nsex = length(unique(d$male)),
height=d$height,
weight_c = d$weight-mean(d$weight),
weight_sq = (d$weight-mean(d$weight))^2,
sex = as.integer(as.factor(d$male)))
fit_poly_sex <- stan(model_code=stan_poly_cat,
data=dat_poly_sex,
chains=2,
iter=2000,
cores=3,
pars=c("b","m","poly","sigma","log_lik"))
beepr::beep(sound=8)
summary(fit_poly_sex)
precis(fit_poly_sex,2)
log_lik_poly_sex <- extract_log_lik(fit_poly_sex)
rethinking::compare(fit_linear,fit_poly,fit_poly_sex)
# let's look at LOO
loo_linear <- loo(fit_linear)
loo_poly <- loo(fit_poly)
loo_poly_sex <- loo(fit_poly_sex)
loo_poly_sex
waic(log_lik_poly_sex)
coefs <- coeftab(fit_linear,fit_poly,fit_poly_sex)
params <- c("b","b[1]","b[2]","m","poly","sigma")
par(mfrow=c(1,3))
coeftab_plot(coefs,pars=c("b","b[1]","b[2]"))
coeftab_plot(coefs,pars="m")
coeftab_plot(coefs,pars="poly")
<file_sep>/Week 3/Week 3 code - in class.R
library(rethinking)
library(MASS)
options(mc.cores=2)
rstan_options(auto_write=TRUE)
Sys.setenv(LOCAL_CPPFLAGS = '-march=native')
data(Howell1)
d <- Howell1
head(Howell1)
plot(height~weight,data=d)
d2 <- d[d$age >= 18, ]
plot(height~weight,data=d2)
layout(matrix(1:2,ncol=2))
dens(d2$height)
hist(d2$height)
layout(1)
# MAP - the posterior distribution via Gaussian approximiation
flist <- alist(
height ~ dnorm(mu, sigma),
mu ~ dnorm(178, 20),
sigma ~ dunif(0, 50)
)
mFit <- map(flist, data=d2)
precis(mFit)
# change the starting values of MAP
# change the prior on mu & sigma
mFit2 <- map(
alist(
height ~ dnorm(mu, sigma),
mu ~ dnorm(178, 0.1),
sigma ~ dunif(0, 50)
),
data=d2, start = list("mu"=mean(d2$height),"sigma"=sd(d2$height))
)
precis(mFit2)
# extract the variance-covariance matrix
vcov(mFit2)
diag(vcov(mFit2))
mu_SD <- sqrt(diag(vcov(mFit2)))["mu"]
# convert covariance to CORRELATION: bounded between -1 and 1
cov2cor(vcov(mFit2))
# plot the effect of different priors
curve( dnorm(x, mean=178, sd=20), from= 100, to = 250, lwd=2,col="orange",ylim=c(0,4))
curve( dnorm(x, mean=178, sd=0.1), add=T, lwd=2, lty=2,col="dodgerblue")
# compare the strong prior to the posterior: dominated by the prior
curve( dnorm(x, mean=178, sd=0.1), from= 100, to = 250, lwd=2,col="orange",ylim=c(0,3))
curve( dnorm(x, mean=177.86, sd=0.1002), add=T, lwd=2, lty=2,col="dodgerblue")
# compare the vague prior to the posterior: dominated by the data
precis(mFit)
curve( dnorm(x, mean=178, sd=20), from= 100, to = 250, lwd=2,col="orange",ylim=c(0,1))
curve( dnorm(x, mean=154.61, sd=0.41), add=T, lwd=2, lty=2,col="dodgerblue")
hist(d2$height,freq=F,add=T)
# let's code this model in Stan!
# start with a data section
# move to an estimated parameters section
# then write the model section: likelihoods & priors
stanModel <- "
data {
int<lower=0> N; // this is a comment
vector[N] height;
}
parameters {
real mu;
real sigma;
}
model {
// log-likelihoods or log-priors
// the normal likelihood is: normal_lpdf(data/name | mean, standard deviation)
target += normal_lpdf(height | mu, sigma);
target += normal_lpdf(mu | 178, 20);
target += uniform_lpdf(sigma | 0, 50);
}
"
dat <- list("N"=nrow(d2),
"height"=d2$height)
fit <- stan(model_code=stanModel, data=dat,
chains=2, iter=2000, cores=2,
pars=c("mu","sigma"))
fit
plot(fit)
traceplot(fit)
# store posterior samples
post <- as.data.frame(fit)
str(post)
# compare model fits with the values from the gaussian approximation
mean(post$mu)
sd(post$mu)
precis(mFit)
# this is dumb. we want to do actual regression
head(d2)
plot(height~weight,data=d2,xlab="Weight (kg)",ylab="Height (cm)",
pch=21,bg=ifelse(male==1,"orange","dodgerblue"))
stanRegression <- "
data{
int<lower=0> N;
vector[N] height;
vector[N] weight;
}
parameters{
real b; // intercept
real m; // slope
real sigma; // standard deviation (variance = sigma^2)
}
model{
vector[N] mu = weight*m + b; // define mu as y=mx+b
target += normal_lpdf(height | mu, sigma); // likelihood based on data
target += normal_lpdf(b | mean(height), sd(height));
target += normal_lpdf(m | 0, 10); // set this prior on slope
target += uniform_lpdf(sigma | 0, 100);
}
"
dat <- list("N"=nrow(d2),
"height"=d2$height,
"weight"=d2$weight)
fitRegression <- stan(model_code=stanRegression,
data=dat, chains=2, iter = 2000, cores = 2,
pars = c("b","m","sigma"))
fitRegression
post2 <- as.data.frame(fitRegression)
head(post2)
fitRegression@sim$samples[[1]][["b"]][1001]
colMeans(post2)
pairs(post2, lower.panel=panel.smooth)
cor(post2)
#
stanCentered <- "
data{
int<lower=0> N;
vector[N] height;
vector[N] weight_c;
}
parameters{
real b; // intercept
real m; // slope
real sigma; // standard deviation (variance = sigma^2)
}
model{
vector[N] mu = weight_c*m + b; // define mu as y=mx+b
target += normal_lpdf(height | mu, sigma); // likelihood based on data
target += normal_lpdf(b | mean(height), sd(height));
target += normal_lpdf(m | 0, 10); // set this prior on slope
target += uniform_lpdf(sigma | 0, 100);
}
"
datCentered <- list("N"=nrow(d2),
"height"=d2$height,
"weight_c"=d2$weight-mean(d2$weight))
fitCentered <- stan(model_code=stanCentered,
data=datCentered,chains=2,iter=2000,cores=2,
pars=c("b","m","sigma"))
postCentered <- as.data.frame(fitCentered)
colMeans(postCentered)
colMeans(post2)
pairs(postCentered,lower.panel=panel.smooth)
plot(height~weight_c,data=datCentered,pch=21,bg="dodgerblue")
invisible(sapply(1:250,function(i){
curve(postCentered$b[i]+postCentered$m[i]*x,add=T,lwd=2,col=adjustcolor("grey",alpha=0.1))
}))
curve(mean(postCentered$b)+mean(postCentered$m)*x,add=T,lwd=5)
# create a posterior predictive distribution and plot the uncertainty in the model
weight.seq <- seq(-20,30,by=1)
post_pred <- matrix(NA,nrow=nrow(postCentered),ncol=length(weight.seq))
for(i in 1:nrow(post_pred))
{
post_pred[i,] <- rnorm(length(weight.seq),
mean=postCentered$b[i] + postCentered$m[i]*weight.seq,sd=postCentered$sigma[i])
}
mu.mean <- apply(post_pred,2,mean)
mu.hdi <- apply(post_pred,2,HPDI,prob=0.89)
plot(height~weight_c,data=datCentered,pch=21,bg="dodgerblue")
polygon(c(weight.seq,rev(weight.seq)),c(mu.hdi[1,],rev(mu.hdi[2,])),col=adjustcolor("dodgerblue",0.7),border=F)
lines(weight.seq,mu.mean,col=adjustcolor("black",0.8),lwd=3)
<file_sep>/Week 2/Week 2 code.R
## R code 2.3
water_globe <- c(1,0,1,1,1,0,1,0,1) # 1 means we have a water, 0 means land
# define the size and values of the grid
Ngrid <- 20
p_grid <- seq( from=0 , to=1 , length.out=Ngrid )
# define prior
prior1 <- rep( 1 , Ngrid )
## R code 2.5
prior2 <- ifelse( p_grid < 0.5 , 0 , 1 )
prior3 <- exp( -5*abs( p_grid - 0.5 ) )
plot(prior1,ylim=range(prior1,prior2,prior3),pch=21,bg=rgb(1,0,0,0.7))
points(prior2,pch=21,bg=rgb(0,1,1,0.7))
points(prior3,pch=21,bg=rgb(0,0,1,0.7))
# compute likelihood at each value in grid
# binomial distribution: flip 9 coins, you observe 6 heads. What is the probability the coin is weighted at any particular value?
prior <- prior3
likelihood <- dbinom( 6 , size=9 , prob=p_grid )
# compute product of likelihood and prior
unstd.posterior <- likelihood * prior
# standardize the posterior, so it sums to 1
posterior <- unstd.posterior / sum(unstd.posterior)
## R code 2.4
plot( p_grid , posterior , type="b" ,
xlab="probability of water" , ylab="posterior probability" )
mtext( "20 points" )
## R code 2.6
library(rethinking)
globe.qa <- map(
alist(
w ~ dbinom(9,p) , # binomial likelihood
p ~ dunif(0,1) # uniform prior
) ,
data=list(w=6) ) # pass 'map()' the number of successes
# display summary of quadratic approximation
precis( globe.qa )
## R code 2.7
# analytical calculation
w <- 6 # number of successes
n <- 9 # number of trials
curve( dbeta( x , w+1 , n-w+1 ) , from=0 , to=1 )
# quadratic approximation
curve( dnorm( x , 0.67 , 0.16 ) , lty=2 , add=TRUE )
# let's see where this breaks down:
# let's approximate the posterior of a sample of 9 'waters' in 10 trials via gaussian
globe.qa <- map(
alist(
w ~ dbinom(10,p) , # binomial likelihood
p ~ dunif(0,1) # uniform prior
) ,
data=list(w=9), start=list(p=0.99)) # pass 'map()' the number of successes
# display summary of quadratic approximation
precis( globe.qa )
w <- 9 # number of successes
n <- 10 # number of trials
curve( dbeta( x , w+1 , n-w+1 ) , from=0 , to=1 )
# quadratic approximation
curve( dnorm( x , precis( globe.qa )@output$Mean , precis( globe.qa )@output$StdDev ) , lty=2 , add=TRUE )
## R code 3.1
# PrPV = probability of positive of vampire when its a vampire vampires
# PrPM = probability of positive of vampire when its a mortal person
# PrV = probability of vampire in population
# 1-PrV = probability of mortal in population
# PrP = probability of a positive for anyone
PrPV <- 0.95
PrPM <- 0.01
PrV <- 0.001
PrP <- PrPV*PrV + PrPM*(1-PrV) # whats the probability of a positive
( PrVP <- PrPV*PrV / PrP ) # whats the probability of a vampire with a successful test
# instead say there are 100,000 people
# there are 100 vampires
# 95 vampires test positive
# 90,900 mortals, 999 will test positive for vampirism
# what's the probability a positive test is a vampire?
# Pr(vampire|positive)
95/(95+999)
## R code 3.2
Ngrid <- 1000
p_grid <- seq( from=0 , to=1 , length.out=Ngrid )
prior <- rep( 1 , Ngrid )
likelihood <- dbinom( 6 , size=9 , prob=p_grid )
posterior <- likelihood * prior
posterior <- posterior / sum(posterior)
## R code 3.3
NewSamp <- 1e5
samples <- sample( p_grid , prob=posterior , size=NewSamp , replace=TRUE )
## R code 3.4
plot( samples )
## R code 3.5
library(rethinking)
dens( samples )
hist(samples,freq=F,add=T,col=adjustcolor("dodgerblue", 0.4))
## R code 3.6
# add up posterior probability where p < 0.5
sum( posterior[ p_grid < 0.5 ] )
## R code 3.7
sum( samples < 0.5 ) / NewSamp
## R code 3.8
sum( samples > 0.5 & samples < 0.75 ) / NewSamp
# how would you calculate how much is greater than 0.75
dens(samples,lwd=2,xlab="proportion of water") # plot the density/probability of each value
shade(density(samples),lim=c(-Inf,0.5),col=adjustcolor("dodgerblue",0.5)) # ~ 17% probability here
shade(density(samples),lim=c(0.5,0.75),col=adjustcolor("orange",0.5)) # ~ 60% of the probability is here
shade(density(samples),lim=c(0.75,1),col=adjustcolor("grey50",0.5))
## R code 3.9
quantile( samples , 0.8 )
## R code 3.10
quantile( samples , c( 0.1 , 0.9 ) ) # called the 80% credible interval
## R code 3.11
# Now imagine we got 3 "waters" in a row - let's calculate the posterior
Ngrid <- 1000 # define how long our grid is
NewSamps <- 1e4
p_grid <- seq( from=0 , to=1 , length.out=Ngrid )
prior <- rep(1,Ngrid)
likelihood <- dbinom( 3 , size=3 , prob=p_grid )
posterior <- likelihood * prior
posterior <- posterior / sum(posterior)
samples <- sample( p_grid , size=NewSamps , replace=TRUE , prob=posterior )
dens(samples)
## R code 3.12
PI( samples , prob=0.5 )
## R code 3.13
HPDI( samples , prob=0.5 )
## R code 3.14
p_grid[ which.max(posterior) ]
## R code 3.15
chainmode( samples , adj=0.01 )
## R code 3.16
mean( samples )
median( samples )
## R code 3.17
sum( posterior*abs( 0.5 - p_grid ) )
## R code 3.18
loss <- sapply( p_grid , function(d) sum( posterior*abs( d - p_grid ) ) )
## R code 3.19
p_grid[ which.min(loss) ]
## R code 3.20
# simulate fake data which mirrors the "small world" assumptions
dbinom( 0:2 , size=2 , prob=0.7 )
## R code 3.21
rbinom( 1 , size=2 , prob=0.7 )
## R code 3.22
rbinom( 10 , size=2 , prob=0.7 )
## R code 3.23
Nsamps <- 1e5
dummy_w <- rbinom( Nsamps , size=2 , prob=0.7 )
table(dummy_w)/Nsamps
## R code 3.24
dummy_w <- rbinom( Nsamps , size=9 , prob=0.7 )
simplehist( dummy_w , xlab="dummy water count" ,xaxt="n")
axis(1,at=names(table(dummy_w)),labels=round(as.numeric(names(table(dummy_w)))/max(dummy_w),2))
## R code 3.25
# model checks and adequacy
Nsamps <- 1e4
w <- rbinom( Nsamps , size=9 , prob=0.6 )
## R code 3.26
w <- rbinom( Nsamps , size=9 , prob=samples )
hist(w[round(samples,1)==0.3],xlab="dummy water count",breaks=0:9,col=adjustcolor("orange",0.5),ylim=c(0,max(hist(w,plot=F)$count)),main="") # plot the density/probability of each value
hist(w[round(samples,1)==0.6],xlab="dummy water count",breaks=0:9,col=adjustcolor("dodgerblue",0.5),ylim=c(0,max(hist(w,plot=F)$count)),add=T) # plot the density/probability of each value
hist(w[round(samples,1)==0.9],xlab="dummy water count",breaks=0:9,col=adjustcolor("darkblue",0.5),ylim=c(0,max(hist(w,plot=F)$count)),add=T) # plot the density/probability of each value
hist(w,breaks=0:9,col="steelblue")
abline(v=6,lwd=3,col="brown")
# calculate number of switches and maximum run length
maxSwitch <- maxRun <- rep(NA,length(w))
for(i in 1:length(w))
{
fakeDat <- rbinom(9,size=1,prob=samples[i])
maxRun[i] <- max(rle(fakeDat)$lengths)
maxSwitch[i] <- length(rle(fakeDat)$lengths)-1
}
simplehist(maxRun)
abline(v=max(rle(c(1,0,1,1,1,0,1,0,1))$lengths),lwd=4,col="orange")
simplehist(maxSwitch)
abline(v=length(rle(c(1,0,1,1,1,0,1,0,1))$lengths)-1,lwd=4,col="orange")
<file_sep>/Week 7/chap7lecture.R
#Chapter 7
#Interactions
library(rethinking)
rstan_options(auto_write = TRUE)
options(mc.cores = 2)
data(rugged)
d <- rugged
#Eliminate NA values
dd <- d[complete.cases(d$rgdppc_2000),]
pairs(data = dd , ~ rgdppc_2000 + rugged + cont_africa + slave_exports + dist_coast,
lower.panel = panel.smooth)
pairs(data = dd, ~ log(rgdppc_2000) + rugged + cont_africa + log(slave_exports) + dist_coast,
lower.panel = panel.smooth)
aggregate(slave_exports ~ cont_africa, data = d, FUN = mean)
#Use log(gdp)
dd$log_gdp <- log(dd$rgdppc_2000)
#Example 1 - Dummy Variable
#log_gdp vs ruggedness with cont_africa as dummy variable
#Visualizing your prior
# dens(dd$log_gdp)
# curve(dnorm(x, mean = mean(dd$log_gdp), sd = 5), add = TRUE)
#Prior for beta[1] can just cover the first distribution
hist(dd$log_gdp, breaks = seq(0,30, by = 0.5), freq = FALSE, ylim = c(0, 1), xlim = c(-30,30))
curve(dnorm(x, mean = mean(dd$log_gdp), sd = 5), add = TRUE)
# #Plot hist for africa only
# #Prior needs to cover both/the difference the ditribution of africa only and overall dist.
# hist(dd$log_gdp[dd$cont_africa == 1], breaks = seq(-30,30, by = 0.5), freq = FALSE, add = TRUE, col = "light blue")
#Average difference between the two peaks
#Prior covers that value
curve(dnorm(x, mean = 0, sd = 2), col = "orange", from = -5, to = 5, xlim = c(-10,10))
abline(v = mean(dd$log_gdp)-mean(dd$log_gdp[dd$cont_africa==1]))
X <- model.matrix(log_gdp ~ cont_africa + rugged, data = dd)
stan_model <- "
data{
int N;
int K; //number of predictors
vector[N] log_gdp;
matrix[N,K] design_mat;
}
parameters{
vector[K] beta;
real sigma;
}
transformed parameters{
vector[N] mu;
mu = design_mat*beta;
}
model{
log_gdp ~ normal(mu, sigma);
beta[1] ~ normal(mean(log_gdp), 5);
for (i in 2:K){
beta[i] ~ normal(0, 2);
}
sigma ~ cauchy(0,10);
}
generated quantities{
vector[N] log_lik;
vector[N] log_gdp_new;
for (i in 1:N){
log_lik[i] = normal_lpdf(log_gdp[i] | mu[i], sigma);
log_gdp_new[i] = normal_rng(mu[i], sigma);
}
}
"
dat1 <- list(N = nrow(dd), K = ncol(X), log_gdp = dd$log_gdp,
design_mat = X)
?stan
fit_dummy <- stan(model_code = stan_model, data = dat1,
chains = 2, iter = 2000, cores = 1,
pars = c("beta", "sigma", "log_lik","log_gdp_new"))
# the better way to view our posterior samples
summary(fit_dummy,pars=c("beta","sigma"),probs=c(0.1,0.9))$summary
precis(fit_dummy, depth = 2)
#Beta 1 and 2 are the intercepts and beta 3 is the slope
#Only the intercepts are allowed to change in this model
#Plot to visualize this
post1 <- as.data.frame(fit_dummy)
plot(log_gdp ~ rugged, data = dd, main = "Log-GDP ~ Ruggedness, Africa dummy variable")
invisible(sapply(1:250, function(i){
curve(post1$`beta[1]`[i] + post1$`beta[3]`[i]*x, add = TRUE, lwd = 2, col = adjustcolor("grey", alpha = 0.1))
curve(post1$`beta[1]`[i] + post1$`beta[2]`[i] + post1$`beta[3]`[i]*x, add = TRUE, lwd = 2, col = adjustcolor("light blue", alpha = 0.1))
}))
curve(mean(post1$`beta[1]`) + mean(post1$`beta[3]`)*x, add = TRUE, lwd = 2)
curve(mean(post1$`beta[1]`) + mean(post1$`beta[2]`) + mean(post1$`beta[3]`)*x, add = TRUE, lwd = 2, col = "dodger blue")
#Example 2
#GDP vs. ruggedness, with an interaction effect of being within/outside of Africa
X2 <- model.matrix(log_gdp ~ cont_africa*rugged, data = dd)
dat2 <- list(N = nrow(dd), K = ncol(X2), log_gdp = dd$log_gdp,
design_mat = X2)
fit_int <- stan(model_code = stan_model, data = dat2,
chains = 2, iter = 2000, cores = 1,
pars = c("beta", "sigma", "log_lik","log_gdp_new"))
precis(fit_int, depth = 2)
post2 <- as.data.frame(fit_int)
#Plot to visualize the interactions
par(mfrow = c(1,2))
#Non-African nations - Base case
plot(log_gdp ~ rugged, data = dd[dd$cont_africa == 0,], main = "Non-African Nations")
invisible(sapply(1:250, function(i){
curve(post2$`beta[1]`[i] + post2$`beta[3]`[i]*x, add = TRUE, lwd = 2, col = adjustcolor("grey", alpha = 0.1))
}))
curve(mean(post2$`beta[1]`) + mean(post2$`beta[3]`)*x, add = TRUE, lwd = 2)
#African nations
plot(log_gdp ~ rugged, data = dd[dd$cont_africa == 1,], main = "African Nations", col = "light blue")
invisible(sapply(1:250, function(i){
curve(post2$`beta[1]`[i] + post2$`beta[2]`[i] + post2$`beta[4]`[i]*x + post2$`beta[3]`[i]*x, add = TRUE, lwd = 2, col = adjustcolor("light blue", alpha = 0.1))
}))
curve(mean(post2$`beta[1]`) + mean(post2$`beta[2]`) + mean(post2$`beta[3]`)*x + mean(post2$`beta[4]`)*x, add = TRUE, lwd = 2, col = "dodger blue")
#Another way of visualizing
#Generate distributions of expected value for our observed values
# delete below
log_gdp_hat2 <- matrix(NA, nrow = nrow(post2), ncol= nrow(X2))
for (i in 1:nrow(post2)){
estimates <- sapply(1:nrow(X2), FUN = function(x){as.numeric(post2[i, grep("beta", colnames(post2))]*X2[x,])})
value <- colSums(estimates)
log_gdp_hat2[i,] <- rnorm(length(value), mean = value, sd = post2[i, "sigma"])
}
mn_ppd <- apply(log_gdp_hat2,2,mean)
ci_ppd <- apply(log_gdp_hat2,2,HPDI,prob=0.89)
par(mfrow = c(1,1))
plot(dat2$log_gdp,mn_ppd,pch=21,bg="lightblue",ylim=range(ci_ppd),xlim=range(ci_ppd), main = "Africa*rugged")
segments(x0=dd$log_gdp,y0=ci_ppd[1,],y1=ci_ppd[2,],lwd=1)
abline(b=1,a=0,lwd=2,lty=2,col="orange")
# delete above
ppd <- post2[,grep("log_gdp_new",colnames(post2))]
mn_ppd <- apply(ppd,2,mean)
ci_ppd <- apply(ppd,2,HPDI,prob=0.89)
par(mfrow = c(1,1))
plot(dat2$log_gdp,mn_ppd,pch=21,bg=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),ylim=range(ci_ppd),xlim=range(ci_ppd), main = "Africa*rugged",xlab="Observed ln(GDP)",ylab="Posterior predictive ln(GDP)")
segments(x0=dd$log_gdp,y0=ci_ppd[1,],y1=ci_ppd[2,],lwd=1)
abline(b=1,a=0,lwd=2,lty=2,col="orange")
boxplot(ppd,col=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),outline=FALSE)
log_gdp_mn <- aggregate(log_gdp ~ cont_africa, data = dd, FUN = mean)
abline(h=log_gdp_mn$log_gdp,col=c("lightblue","orange"),lwd=3)
#Example 2
#GDP vs ruggedness and slave exports within Africa
#Need to log slave exports (+1) because range is so wide
dd$slave_logged <- log(dd$slave_exports + 1)
X3 <- model.matrix(log_gdp ~ slave_logged*dist_coast, data = dd)
dat3 <- list(N = nrow(dd), K = ncol(X3), log_gdp = dd$log_gdp,
design_mat = X3)
fit_cont <- stan(model_code = stan_model, data = dat3,
chains = 2, iter = 2000, cores = 1,
pars = c("beta", "sigma", "log_lik","log_gdp_new"))
summary(fit_cont,pars=c("beta","sigma"),probs=c(0.1,0.9))$summary
precis(fit_cont, depth = 2)
post3 <- as.data.frame(fit_cont)
#Make triptych plots like in the textbook?
#Plot predicted vs observed
#Make an empty matrix to populate our expected values with
log_gdp_hat3 <- matrix(NA, nrow = nrow(post3), ncol= nrow(X3))
for (i in 1:nrow(post3)){
estimates <- sapply(1:nrow(X3), FUN = function(x){as.numeric(post3[i, grep("beta", colnames(post3))]*X3[x,])})
value <- colSums(estimates)
log_gdp_hat3[i,] <- rnorm(length(value), mean = value, sd = post3[i, "sigma"])
}
mn_ppd <- apply(log_gdp_hat3,2,mean)
ci_ppd <- apply(log_gdp_hat3,2,HPDI,prob=0.89)
plot(dd$log_gdp,mn_ppd,pch=21,bg="lightblue",ylim=range(ci_ppd),xlim=range(ci_ppd), main = "Slave exports*Dist to coast")
segments(x0=dd$log_gdp,y0=ci_ppd[1,],y1=ci_ppd[2,],lwd=1)
abline(b=1,a=0,lwd=2,lty=2,col="orange")
ppd <- post3[,grep("log_gdp_new",colnames(post2))]
mn_ppd <- apply(ppd,2,mean)
ci_ppd <- apply(ppd,2,HPDI,prob=0.89)
par(mfrow = c(1,1))
plot(dat3$log_gdp,mn_ppd,pch=21,bg=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),ylim=range(ci_ppd),xlim=range(ci_ppd), main = "Africa*rugged",xlab="Observed ln(GDP)",ylab="Posterior predictive ln(GDP)")
segments(x0=dd$log_gdp,y0=ci_ppd[1,],y1=ci_ppd[2,],lwd=1)
abline(b=1,a=0,lwd=2,lty=2,col="orange")
#Compare our models using WAIC
rethinking::compare(fit_dummy, fit_int, fit_cont)
<file_sep>/Week 1/Running Stan - example 2.R
library("rstan") # observe startup messages
parallel::detectCores()
options(mc.cores = 4)
rstan_options(auto_write = TRUE)
Sys.setenv(LOCAL_CPPFLAGS = '-march=native')
y <- as.matrix(read.table('https://raw.github.com/wiki/stan-dev/rstan/rats.txt', header = TRUE))
x <- c(8, 15, 22, 29, 36)
xbar <- mean(x)
N <- nrow(y)
T <- ncol(y)
rats_fit <- stan(file="Week 1/rats.stan", data = list(N=N, T=T, y=y, x=x, xbar=xbar))
print(rats_fit)
plot(rats_fit)
pairs(rats_fit, pars = c("mu_alpha", "mu_beta", "sigma_y"))
la <- extract(rats_fit, permuted = TRUE) # return a list of arrays
mu <- la$alpha
### return an array of three dimensions: iterations, chains, parameters
a <- extract(rats_fit, permuted = FALSE)
### use S3 functions on stanfit objects
a2 <- as.array(rats_fit)
m <- as.matrix(rats_fit)
d <- as.data.frame(rats_fit)
<file_sep>/Week 10/week_10_code_PARTIAL.R
# Statistical Rethinking Directed Readings
# Chapter 12 - Multi-level Models
# 2019-03-28
rm(list=ls())
library(rethinking)
rstan_options(auto_write = TRUE)
options(mc.cores=2)
# Why multi-level? We want to model the average of a group
# Multi-level model does two things;
# 1. What is the average across groups?
# 2. What is the group-level effect?
data("chimpanzees")
d <- chimpanzees
head(d)
#### Start with one intercept model and intercept for each chimp
# 1. Fit model with just one intercept ------------
model1 <- "
data {
int N;
int<lower=0, upper=1> pulled_left[N]; // pulled left
int prosoc_left[N]; // prosocial / two plates of food option is on left side
int condition[N]; // 1 means partner is present, 0 for control
}
parameters{
real a; // intercept
real bp; // beta for pro social
real bpc; // beta for pro social left and condition interaction
}
transformed parameters{
vector[N] p;
for(i in 1:N){
p[i] = a + bp * prosoc_left[i] + bpc * prosoc_left[i] * condition[i];
}
}
model{
a ~ normal(0,10);
bp ~ normal(0,10);
bpc ~ normal(0, 10);
pulled_left ~ binomial_logit(1,p);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N) {
log_lik[i] = bernoulli_logit_lpmf(pulled_left[i] | p[i]);
}
}
"
dat1 <- list(N=nrow(d),
pulled_left = d$pulled_left,
prosoc_left = d$prosoc_left,
condition = d$condition)
fit1 <-stan(model_code = model1, data=dat1, iter=3000,chains=2,cores=2,
pars=c("a", "bp", "bpc", "log_lik"))
summary(fit1,pars=c("a","bp","bpc"), probs=c(0.1, 0.9))$summary
#traceplot(fit1, pars=c("a", "bp", "bpc"))
# 2. Binomial model: individuals have specific intercepts ------------
model2 <- "
data {
int N;
int<lower=0, upper=1> pulled_left[N]; // pulled left
int prosoc_left[N]; // prosocial / two plates of food option is on left side
int condition[N]; // 1 means partner is present, 0 for control
int<lower=1,upper=N> N_chimps;
int<lower=1, upper=N_chimps> chimp[N]; // id of chimp / actor
}
parameters{
real a[N_chimps];
real bp;
real bpc;
}
transformed parameters {
vector[N] p;
for(i in 1:N){
p[i] = a[chimp[i]] + bp * prosoc_left[i] + bpc * condition[i] * prosoc_left[i];
}
}
model{
for(i in 1:N_chimps) {
a[i] ~ normal(0, 10);
}
bp ~ normal(0,10);
bpc ~ normal(0,10);
pulled_left ~ binomial_logit(1,p);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N){
log_lik[i] = binomial_logit_lpmf(pulled_left[i] | 1, p[i]);
}
}
"
dat2 <- list(N=nrow(d),
pulled_left = d$pulled_left,
prosoc_left = d$prosoc_left,
condition = d$condition,
N_chimps = length(unique(d$actor)),
chimp = d$actor)
fit2 <- stan(model_code = model2, data=dat2, iter=3000,chains=2,cores=2,control=list("adapt_delta"=0.81),
pars=c("a", "bp", "bpc", "log_lik"))
summary(fit2, pars=c("a","bp","bpc"),probs=c(0.1, 0.9))$summary
#traceplot(fit2)
### START TYPING WORKSHOP HERE
# make a multi-level model here
model3 <- "
data{
int N;
int<lower=0,upper=1> pulled_left[N];
int prosoc_left[N];
int condition[N];
int N_chimps;
int<lower=1, upper=N_chimps> chimp[N];
}
parameters{
real a_chimp[N_chimps];
real bp; // effect of prosoc_left
real bpc; // interaction effect
real mu_chimp; // mean intercept across chimps
real sigma_chimp; // standard deviation across chimps
}
transformed parameters {
vector[N] p; // logit-scale
for(i in 1:N) {
p[i] = a_chimp[chimp[i]] + bp*prosoc_left[i] + bpc*condition[i]*prosoc_left[i];
}
}
model {
for(i in 1:N_chimps) {
a_chimp[i] ~ normal(mu_chimp, sigma_chimp);
}
mu_chimp ~ normal(0,10);
sigma_chimp ~ cauchy(0, 10);
bp ~ normal(0, 10);
bpc ~ normal(0, 10);
pulled_left ~ binomial_logit(1, p); // likelihood function for data given model
}
generated quantities{
vector[N] log_lik;
for(i in 1:N) {
log_lik[i] = binomial_logit_lpmf(pulled_left[i] | 1, p[i]);
}
}
"
dat3 <- list(N=nrow(d),
pulled_left = d$pulled_left,
prosoc_left = d$prosoc_left,
condition = d$condition,
N_chimps = length(unique(d$actor)),
chimp = d$actor)
fit3 <- stan(model_code = model3, data=dat3, iter=3000,chains=2,cores=2,control=list("adapt_delta"=0.81),pars=c("mu_chimp","sigma_chimp","a_chimp", "bp", "bpc", "log_lik"))
summary(fit3, pars=c("mu_chimp","a_chimp","bp","bpc"),probs=c(0.1,0.9))$summary
# compare alphas between the models
# make a list of the posterior samples
post_list <- list(post1 <- as.data.frame(fit1),
post2 <- as.data.frame(fit2),
post3 <- as.data.frame(fit3))
# Make a function that does mean and quantiles
multi.fun <- function(x) {
c(mean=mean(x), quantile= quantile(x, probs = c(0.1, 0.9)))
}
# Get mean and quantiles for each of the three models
ints <- as.list(rep(NA,3)) # make three object list, each object is blank
# fill the list with the mean and 80% intervals
for(i in 1:3) {
ints[[i]] <- apply(X = as.matrix(post_list[[i]][ , grep("^a", names(post_list[[i]]))]), 2, multi.fun)
}
# Plot intercept estimates for the three models
# start with points for model 2
plot(ints[[2]][1,], col="black", pch=16,ylab="Posterior estimates of intercept", xlab="Chimp")
segments(x0= 1:7, y0=ints[[2]][3,], y1=ints[[2]][2, ], col="black")
points(x=1:7+0.2, y=ints[[3]][1,], col="dodger blue", pch=16) # add points for model 3
segments(x0= 1:7+ 0.2, y0=ints[[3]][3,], y1=ints[[3]][2, ], col="dodger blue")
abline(h= ints[[1]][1,], col="orange") # add line for model 1
abline(h= ints[[1]][2:3,], col=adjustcolor("orange", alpha=0.5))
# now add a block effect
model4 <- "
data{
int N;
int<lower=0,upper=1> pulled_left[N];
int prosoc_left[N];
int condition[N];
int N_chimps;
int<lower=1, upper=N_chimps> chimp[N]; // id of chimp
int N_blocks;
int<lower=1, upper=N_blocks> block_id[N]; // id of block
}
parameters{
real a; // global intercept
real a_block[N_blocks]; // block effect on intercepts
real a_chimp[N_chimps]; // chimp effect on intercepts
real bp; // effect of prosoc_left
real bpc; // interaction effect
real sigma_chimp; // standard deviation across chimps
real sigma_block; // standard deviation for how mean varies across block
}
transformed parameters {
vector[N] p; // logit-scale
for(i in 1:N) {
p[i] = a + a_chimp[chimp[i]] + a_block[block_id[i]] + bp*prosoc_left[i] + bpc*condition[i]*prosoc_left[i];
}
}
model {
for(i in 1:N_chimps) {
a_chimp[i] ~ normal(0, sigma_chimp);
}
for(i in 1:N_blocks) {
a_block[i] ~ normal(0, sigma_block);
}
a ~ normal(0,10);
sigma_chimp ~ cauchy(0, 10);
sigma_block ~ cauchy(0, 10);
bp ~ normal(0, 10);
bpc ~ normal(0, 10);
pulled_left ~ binomial_logit(1, p); // likelihood function for data given model
}
generated quantities{
vector[N] log_lik;
vector[N] pulled_left_new; // generate new predictions
for(i in 1:N) {
log_lik[i] = binomial_logit_lpmf(pulled_left[i] | 1, p[i]);
pulled_left_new[i] = binomial_rng(1, inv_logit(p[i]));
}
}
"
dat4 <- list(N=nrow(d),
pulled_left = d$pulled_left,
prosoc_left = d$prosoc_left,
condition = d$condition,
N_chimps = length(unique(d$actor)),
chimp = d$actor,
N_blocks = length(unique(d$block)),
block_id = d$block)
fit4 <- stan(model_code = model4, data=dat4, iter=3000,chains=2,cores=2,control=list("adapt_delta"=0.81),pars=c("a","sigma_chimp","a_chimp", "a_block","sigma_block", "bp", "bpc", "log_lik","pulled_left_new"))
summary(fit4, pars=c("a","sigma_chimp","a_chimp", "a_block","sigma_block", "bp", "bpc"),probs=c(0.1,0.9))$summary
compare(fit1,fit2,fit3,fit4)
post4 <- as.data.frame(fit4)
# plot predicted v. observed
pred <- post4[, grep("pulled_left_new",colnames(post4))]
pred_ppd <- matrix(NA, nrow=nrow(pred), ncol=4)
colnames(pred_ppd) <- c("0/0", "0/1", "1/0", "1/1") # prosocial-left/condition
counter <- 0
for(i in 0:1) {
for(j in 0:1) {
counter = counter + 1
pred_ppd[ , counter] = rowSums(pred[ , d$prosoc_left==i & d$condition==j])
}
}
layout(1)
boxplot(pred_ppd)
d$pro_soc_cond <- paste(d$prosoc_left,d$condition,sep="/")
obs <- aggregate(pulled_left~pro_soc_cond, data=d, FUN=sum)
points(1:4, obs$pulled_left, pch=21, bg="dodgerblue", cex=2)
# plot predicted v. observed for individuals
pred_mean <- apply(pred, 2, mean)
pred_hpdi <- apply(pred, 2, HPDI, prob=0.89)
pulled_left_jitter <- d$pulled_left + rnorm(nrow(d), 0 , 0.05)
col_vec <- rep(c("red", "green", "orange", "blue","black","gray","purple"), each=nrow(d)/length(unique(d$actor)))
plot(y=pred_mean, x=pulled_left_jitter, ylim=c(0,1),pch=21, bg=col_vec)
<file_sep>/README.md
# StatisticalRethinking
SFU Biology and EarthToOcean workshop series for reading and applying the Statistical Rethinking book in Stan
<file_sep>/Week 8/Week 8 - In Class.R
library(rethinking)
rstan_options(auto_write = TRUE)
options(mc.cores=2)
data("chimpanzees")
d <- chimpanzees
# binomial model with just an intercept
model10_1 <- "
data{
int N;
int<lower=0,upper=1> L[N]; // did they pull the left lever
}
parameters{
real a;
}
transformed parameters{
vector[N] p;
for(i in 1:N){
p[i] = inv_logit(a);
}
}
model{
a ~ normal(0,10);
L ~ binomial(1,p);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N) {
log_lik[i] = bernoulli_lpmf(L[i] | p[i]);
}
}
"
dat <- list(N=nrow(d), L = d$pulled_left)
fit10_1 <- stan(model_code = model10_1, data=dat, iter=2000,chains=2,cores=2)
summary(fit10_1, pars=c("a"),probs=c(0.1,0.9))$summary
model10_2 <- "
data{
int N;
int L[N]; // pulled left
int P[N];
}
parameters{
real a; // intercept
real bp; // beta for pro social
}
transformed parameters{
vector[N] p;
for(i in 1:N){
p[i] = a + bp * P[i];
}
}
model{
a ~ normal(0,10);
bp ~ normal(0,10);
L ~ binomial_logit(1,p);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N) {
log_lik[i] = bernoulli_logit_lpmf(L[i] | p[i]);
}
}
"
dat2 <- list(N=nrow(d), L = d$pulled_left, P = d$prosoc_left)
fit10_2 <- stan(model_code = model10_2, data=dat2, iter=3000,chains=2,cores=2)
summary(fit10_2, pars=c("a","bp"),probs=c(0.1,0.9))$summary
# binomial model: individuals have specific intercepts
model10_4 <- "
data {
int N;
int<lower=0, upper=1> L[N]; // pulled left
vector[N] P; // prosocial left
vector[N] C; // condition
int<lower=1,upper=N> MaxA;
int<lower=1, upper=MaxA> A[N]; // unique actors
}
parameters{
real a[MaxA];
real bp;
real bpc;
}
transformed parameters {
vector[N] p;
for(i in 1:N){
p[i] = a[A[i]] + bp * P[i] + bpc * C[i] * P[i];
}
}
model{
for(i in 1:MaxA) {
a[i] ~ normal(0, 10);
}
bp ~ normal(0,10);
bpc ~ normal(0,10);
L ~ binomial_logit(1,p);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N){
log_lik[i] = binomial_logit_lpmf(L[i] | 1, p[i]);
}
}
"
dat3 <- list(N=nrow(d), L = d$pulled_left, P = d$prosoc_left, C = d$condition, MaxA = length(unique(d$actor)), A = d$actor)
fit10_4 <- stan(model_code = model10_4, data=dat3, iter=3000,chains=2,cores=2,control=list("adapt_delta"=0.81))
summary(fit10_4, pars=c("a","bp","bpc"),probs=c(0.1,0.9))$summary
#pairs(fit10_4,pars=c("a","bp","bpc"))
compare(fit10_1,fit10_2,fit10_4)
# aggregated binomial
dA <- aggregate(d$pulled_left,list(prosoc_left=d$prosoc_left,
condition=d$condition,
actor=d$actor),
sum)
model10_5 <- "
data{
int N;
int<lower=0> x[N];
int<lower=1> MaxX;
vector[N] P;
vector[N] C;
}
parameters{
real a;
real bp;
real bpc;
}
transformed parameters{
vector[N] p;
for(i in 1:N){
p[i] = a+bp*P[i] + bpc*C[i]*P[i];
}
}
model {
a ~ normal(0,10);
bp ~ normal(0,10);
bpc ~ normal(0,10);
x ~ binomial_logit(MaxX,p);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N){
log_lik[i] = binomial_logit_lpmf(x[i] | MaxX, p[i]);
}
}
"
dat4 <- list(N=nrow(dA), x = dA$x, P = dA$prosoc_left, C = dA$condition, MaxX = max(dA$x), A = dA$actor)
fit10_5 <- stan(model_code = model10_5, data=dat4, iter=3000,chains=2,cores=2,control=list("adapt_delta"=0.81))
summary(fit10_5, pars=c("a","bp","bpc"),probs=c(0.1,0.9))$summary
data(Kline)
d <- Kline
d$contact_high <- ifelse(d$contact=="high",1,0)
model10_6 <- "
data{
int N;
int<lower=0> P[N]; // population
int<lower=0> T[N]; // total tools in population
int<lower=0> C[N]; // contact
}
parameters{
real a;
real bp;
real bc;
real bpc;
}
transformed parameters{
vector[N] lambda;
for(i in 1:N){
lambda[i] = a+bp*log(P[i]) + bpc*C[i]*log(P[i]) + bc*C[i];
}
}
model {
a ~ normal(0,100);
bp ~ normal(0,1);
bpc ~ normal(0,1);
bc ~ normal(0,1);
T ~ poisson_log(lambda);
}
generated quantities{
vector[N] log_lik;
for(i in 1:N){
log_lik[i] = poisson_log_lpmf(T[i] | lambda[i]);
}
}
"
dat5 <- list(N=nrow(d),P=d$population,C=d$contact_high,T=d$total_tools)
fit10_6 <- stan(model_code = model10_6, data=dat5, iter=3000,chains=2,cores=2,control=list("adapt_delta"=0.81))
summary(fit10_6, pars=c("a","bp","bpc","bc"),probs=c(0.1,0.9))$summary
<file_sep>/Week 7/Week 7 - in class.R
# Chapter 7
# Interactions
library(rethinking)
rstan_options(auto_write=TRUE)
options(mc.cores=2)
data(rugged)
d <- rugged
dd <- d[complete.cases(d$rgdppc_2000),]
dd$log_gdp <- log(dd$rgdppc_2000)
pairs(data = dd, ~ log_gdp + rugged + cont_africa + log(slave_exports) + dist_coast, lower.panel=panel.smooth)
X <- model.matrix(log_gdp ~ cont_africa + rugged, data=dd)
hist(dd$log_gdp,breaks=seq(-30,30,by=0.5),freq=FALSE,ylim=c(0,1),xlim=c(-20,20))
hist(dd$log_gdp[dd$cont_africa==1],breaks=seq(-30,30,by=0.5),freq=FALSE,add=TRUE,col="lightblue")
curve(dnorm(x,mean=mean(dd$log_gdp),sd=5),add=TRUE)
# cool code:
lookup(length,ReturnType = character())
stan_model <- "
data{
int N;
int K; // number of predictors in design matrix
vector[N] log_gdp;
matrix[N,K] design_mat;
}
parameters{
vector[K] beta;
real sigma;
}
transformed parameters{
vector[N] mu;
mu = design_mat*beta;
}
model{
log_gdp ~ normal(mu, sigma);
beta[1] ~ normal(mean(log_gdp),5);
for(i in 2:K) {
beta[i] ~ normal(0, 5);
}
sigma ~ cauchy(0, 10);
}
generated quantities{
vector[N] log_lik;
vector[N] log_gdp_new; // posterior predictive distributions
for(i in 1:N){
log_lik[i] = normal_lpdf(log_gdp[i] | mu[i], sigma);
log_gdp_new[i] = normal_rng(mu[i],sigma);
}
}
"
dat1 <- list(N = nrow(dd), K=ncol(X),log_gdp=dd$log_gdp,design_mat=X)
fit_dummy <- stan(model_code=stan_model,data=dat1,chains=2,iter=2000,cores=2,pars=c("beta","sigma","log_lik","log_gdp_new"))
summary(fit_dummy,pars=c("beta","sigma"),probs=c(0.1,0.9))$summary
# plots
post1 <- as.data.frame(fit_dummy)
plot(log_gdp~rugged, data=dd, main="Ln(GDP)~ Ruggedness, Africa dummy variable",pch=21,bg=ifelse(dd$cont_africa==1,"orange","grey"))
invisible(sapply(1:250,function(i){
curve(post1$`beta[1]`[i] + post1$`beta[3]`[i]*x,add=TRUE,lwd=2,col=adjustcolor("grey",alpha=0.5))
}))
invisible(sapply(1:250,function(i){
curve(post1$`beta[1]`[i] + post1$`beta[2]`[i]*1 + post1$`beta[3]`[i]*x,add=TRUE,lwd=2,col=adjustcolor("lightblue",alpha=0.5))
}))
curve(mean(post1$`beta[1]`) + mean(post1$`beta[2]`)*0 + mean(post1$`beta[3]`)*x,add=TRUE,lwd=2,col=adjustcolor("black",alpha=0.5))
curve(mean(post1$`beta[1]`) + mean(post1$`beta[2]`)*1 + mean(post1$`beta[3]`)*x,add=TRUE,lwd=2,col=adjustcolor("black",alpha=0.5))
# Example 2
# GDP v. ruggedness with an interaction effect of continent
X2 <- model.matrix(log_gdp ~ cont_africa*rugged,data=dd)
dat2 <- list(N=nrow(dd), K = ncol(X2), log_gdp=dd$log_gdp,design_mat=X2)
fit_int <- stan(model_code=stan_model,data=dat2,chains=2,iter=2000,cores=2,pars=c("beta","sigma","log_lik","log_gdp_new"))
summary(fit_int,pars=c("beta","sigma"),probs=c(0.1,0.9))$summary
rethinking::compare(fit_dummy,fit_int)
# plots
post2 <- as.data.frame(fit_int)
par(mfrow=c(1,2))
plot(log_gdp~rugged, data=dd[dd$cont_africa==0,], main="Non-Africa",pch=21)
invisible(sapply(1:250,function(i){
curve(post2$`beta[1]`[i] + post2$`beta[2]`[i]*0 + post2$`beta[3]`[i]*x + post2$`beta[4]`[i]*x*0,add=TRUE,lwd=2,col=adjustcolor("grey",alpha=0.5))
}))
curve(mean(post2$`beta[1]`) + mean(post2$`beta[2]`)*0 + mean(post2$`beta[3]`)*x + mean(post2$`beta[4]`)*x*0,add=TRUE,lwd=2,col=adjustcolor("black",alpha=1))
plot(log_gdp~rugged, data=dd[dd$cont_africa==1,], main="Africa",pch=21)
invisible(sapply(1:250,function(i){
curve(post2$`beta[1]`[i] + post2$`beta[2]`[i]*1 + post2$`beta[3]`[i]*x + post2$`beta[4]`[i]*x*1,add=TRUE,lwd=2,col=adjustcolor("lightblue",alpha=0.5))
}))
curve(mean(post2$`beta[1]`) + mean(post2$`beta[2]`)*1 + mean(post2$`beta[3]`)*x + mean(post2$`beta[4]`)*x*1,add=TRUE,lwd=2,col=adjustcolor("black",alpha=1))
# Visualize predicted distributions
ppd <- post2[ , grep("log_gdp_new",colnames(post2))]
mn_ppd <- apply(ppd, 2 ,mean)
ci_ppd <- apply(ppd, 2, HPDI, prob=0.89)
par(mfrow=c(1,1))
plot(dd$log_gdp, mn_ppd, pch=21, bg=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),ylim=range(ci_ppd),xlab="Observed ln(GDP)",ylab="Posterior predictive ln(GDP)")
segments(x0=dd$log_gdp, y0=ci_ppd[1,], y1=ci_ppd[2,],lwd=2)
abline(b=1,a=0,lwd=2,col="red")
boxplot(ppd, col=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),outline=FALSE)
log_gdp_mn <- aggregate(log_gdp~cont_africa,data=dd,FUN=mean)
abline(h=log_gdp_mn$log_gdp,col=c("lightblue","orange"),lwd=3)
# Example 3
# GDP ~ dist_coast + slave exports
dd$log_slave <- log(1+dd$slave_exports)
X3 <- model.matrix(log_gdp ~ log_slave*dist_coast,data=dd)
dat3 <- list(N=nrow(X3),K=ncol(X3),log_gdp=dd$log_gdp,design_mat=X3)
fit_cont <- stan(model_code = stan_model, data=dat3, chains=2, iter=2000,cores=2,pars=c("beta","sigma","log_lik","log_gdp_new"))
summary(fit_cont,pars=c("beta","sigma"),probs=c(0.1,0.9))$summary
rethinking::compare(fit_dummy,fit_int,fit_cont)
post3 <- as.data.frame(fit_cont)
# Visualize predicted distributions
ppd <- post3[ , grep("log_gdp_new",colnames(post3))]
mn_ppd <- apply(ppd, 2 ,mean)
ci_ppd <- apply(ppd, 2, HPDI, prob=0.89)
par(mfrow=c(1,1))
plot(dd$log_gdp, mn_ppd, pch=21, bg=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),ylim=range(ci_ppd),xlab="Observed ln(GDP)",ylab="Posterior predictive ln(GDP)")
segments(x0=dd$log_gdp, y0=ci_ppd[1,], y1=ci_ppd[2,],lwd=2)
abline(b=1,a=0,lwd=2,col="red")
boxplot(ppd, col=ifelse(dat2$design_mat[,2]==1,"orange","lightblue"),outline=FALSE)
log_gdp_mn <- aggregate(log_gdp~cont_africa,data=dd,FUN=mean)
abline(h=log_gdp_mn$log_gdp,col=c("lightblue","orange"),lwd=3)
<file_sep>/power analysis.R
library(lme4)
library(lmerTest)
library(plot3D)
# broom the model outputs & summary
# nSamps: number of samples per site
# nSites: number of sites (or groups)
# sd.obs: standard deviation in ecological metric (e.g., size)
# sd.group: standard deviation in how the mean of the metric varies among groups
sd.obs <- 4
sd.group <- 1
costSite <- 4 # hours of work/driving to add extra site
costSamp <- 0.5 # hours of work to add extra sample
statsig <- function(nSamps,nSites,effect,sd.obs,sd.group){
# imagine you have only 1 measurement of x per stream/site
x <- rnorm(nSites,mean=0,sd=1) # generate the predictor variable at the site
x1 <- rep(x,each=nSamps) # repeat the x variable for each sample at the site
group <- as.factor(rep(1:nSites,each=nSamps)) # track the site ID for each samples
y <- .2 + effect*x + rnorm(length(x),mean=0,sd=sd.group) # create random ecological metric
y1 <- rnorm(length(x1),mean=rep(y,each=nSamps),sd=sd.obs) # create random data for each group
fit1 <- lm(y1~x1)
fit2 <- suppressMessages(lmer(y1~x1+(1|group),REML=F))
s1 <- summary(fit1)
s2 <- summary(fit2)
pw1 <- effect <= (s1[[4]][2,1] + 1.96*s1[[4]][2,2]) & effect >= (s1[[4]][2,1]-1.96*s1[[4]][2,2]) & 0 <= (s1[[4]][2,1]+1.96*s1[[4]][2,2])*(s1[[4]][2,1]-1.96*s1[[4]][2,2])
pw2 <- effect<=(s2$coefficients[2,1]+1.96*s2$coefficients[2,2])&
effect>=(s2$coefficients[2,1]-1.96*s2$coefficients[2,2])&
0<=(s2$coefficients[2,1]+1.96*s2$coefficients[2,2])*
(s2$coefficients[2,1]-1.96*s2$coefficients[2,2])
round(c(slope1=s1$coefficients[2,1],R1=s1$adj.r.squared,
Type_I_error_1=s1[[4]][2,4]<=0.05,pw1=pw1,slope2=s2$coefficients[2,1],
Type_I_error_2=s2$coefficients[2,5]<=0.05,pw2=pw2),3)
}
effect_vec <- c(0,1)
nSites <- seq(from=5,to=50,by=5)
nSamps <- c(3,5,10,15,20,25,30,35,50,100)
results <- array(NA,dim=c(length(effect_vec),length(nSites),length(nSamps),7),dimnames=list("Effect size"=effect_vec,"N Sites"=nSites,"N Samps per Site"=nSamps,"Metric"=c("slope (lm)","R2 (lm)","Type I error (lm)","Power (lm)","Slope (lme4)","Type I error (lme4)","Power (lme4)")))
counter <- 1
progBar <- txtProgressBar(min = 0, max = length(effect_vec)*length(nSites)*length(nSamps),title="More power",style=3,initial=0)
ptm = Sys.time()
for(i in 1:length(effect_vec)){
for(j in 1:length(nSites)){
for(k in 1:length(nSamps)){
out <- replicate(1000,statsig(nSamps=nSamps[k],nSites=nSites[j],effect=effect_vec[i],sd.obs=sd.obs,sd.group=sd.group),simplify=T)
results[i,j,k,] <- rowMeans(out)
setTxtProgressBar(progBar,counter)
counter <- counter + 1
}
}
}
endtime <- Sys.time()-ptm
endtime
# analyze your cost-benefit ratios
power <- results[2,,,"Power (lme4)"]
power[power<0.8] <- NA
noType1 <- 1-results[1,,,"Type I error (lme4)"]
noType1[noType1<0.95] <- NA
cost <- sapply(costSamp*nSamps,function(x){x+costSite*nSites})
dimnames(cost) <- dimnames(power)
# find where you have minimal costs that maximizes your power and chance to avoid type 1 error
costBenefit <- which(abs(cost/power-min(cost/power,na.rm=T)+(cost/type1-min(cost/type1,na.rm=T)))==min(abs(cost/power-min(cost/power,na.rm=T)+(cost/type1-min(cost/type1,na.rm=T)))),arr.ind=T)
paste("Sites = ",nSites[costBenefit[1]]," & ",
"Samples = ",nSamps[costBenefit[2]],sep="")
# what if there was no cost to more sites or more samples per site
noCost <- which(abs(power-max(power)+(type1-max(type1)))==min(abs(power-max(power)+(type1-max(type1)))),arr.ind=T)
paste("Sites = ",nSites[noCost[1]]," & ",
"Samples = ",nSamps[noCost[2]],sep="")
# what if we didn't account for pseudoreplication?
# analyze your cost-benefit ratios
power <- results[2,,,"Power (lm)"]
noType1 <- 1-results[1,,,"Type I error (lm)"]
cost <- sapply(costSamp*nSamps,function(x){x+costSite*nSites})
dimnames(cost) <- dimnames(power)
# find where you have minimal costs that maximizes your power and chance to avoid type 1 error
costBenefit <- which(abs(cost/power-min(cost/power)+(cost/type1-min(cost/type1)))==min(abs(cost/power-min(cost/power)+(cost/type1-min(cost/type1)))),arr.ind=T)
paste("Sites = ",nSites[costBenefit[1]]," & ",
"Samples = ",nSamps[costBenefit[2]],sep="")
# what if there was no cost to more sites or more samples per site
noCost <- which(abs(power-max(power)+(type1-max(type1)))==min(abs(power-max(power)+(type1-max(type1)))),arr.ind=T)
paste("Sites = ",nSites[noCost[1]]," & ",
"Samples = ",nSamps[noCost[2]],sep="")
# make contour plot to highlight tradeoff
jpeg("cost-benefit.jpeg",units="in",res=800,height=7,width=7)
layout(1)
par(mar=c(5,4,1,1))
filled.contour(x=costSamp*nSamps, y=costSite*nSites, z=results[2,,,"Power (lme4)"],xlab='Time spent sampling each site',ylab='Time spent getting to sites',color.palette = colorRampPalette(c("red",'orange','dodgerblue',"yellow")))
dev.off()
jpeg("sample size tradeoff.jpeg",units="in",res=800,height=7,width=7)
layout(1)
par(mar=c(5,4,1,1))
filled.contour(x=nSamps, y=nSites, z=results[2,,,"Power (lme4)"],xlab='Number of samples',ylab='Number of sites',color.palette = colorRampPalette(c("red",'orange','dodgerblue',"yellow")))
dev.off()
jpeg("sample size cost-benefit.jpeg",units="in",res=800,height=7,width=7)
layout(1)
par(mar=c(5,4,1,1))
filled.contour(x=nSamps, y=nSites, z=cost/results[2,,,"Power (lme4)"],xlab='Number of samples',ylab='Number of sites',color.palette = colorRampPalette(c("red",'orange','dodgerblue',"yellow")))
dev.off()
jpeg("type 1 error.jpeg",units="in",res=800,height=7,width=7)
layout(1)
par(mar=c(5,4,1,1))
filled.contour(x=nSamps, y=nSites, z=noType1,xlab='Number of samples',ylab='Number of sites',color.palette = colorRampPalette(c("red",'orange','dodgerblue',"yellow")))
dev.off()
|
e99a7e8a46bc304f7c09de1a3ae77322efbeafae
|
[
"Markdown",
"R"
] | 12 |
R
|
klwilson23/StatisticalRethinking
|
bd3cfdc5e5f45452e7ec57c990a77dfe7b8bf45a
|
41e7a96d2dfcccd7a651218840f9fa04af619f20
|
refs/heads/master
|
<file_sep># Runs on Python 3.7
# Packages and programs needed
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
from nltk import word_tokenize, bigrams, trigrams
from nltk.stem import PorterStemmer
from collections import Counter
import re, os, itertools, csv
# Getting stop words from MIT's site
stop_words = urlopen('http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/a11-smart-stop-list/english.stop').read().decode().split('\n')
# Making my own list of stopwords if I want to add names of candidates or other words
original_stopwords =('')
# Getting the porter stemmer ready to use
pt = PorterStemmer()
# It should not be necessary to set it up like this, but it kept glitching when I tried to add this to the for loop later
# creating lists of the stemmed stop words so they can easily be removed from the stemmed corpuses later
stop_words_stemmed = []
original_stopwords_stemmed = []
for w in stop_words:
stop_words_stemmed.append(pt.stem(w))
for w in original_stopwords:
original_stopwords_stemmed.append(pt.stem(w))
# Using so states all appear as "my_state". Trying to break this into multiple lines throws too many errors.
states_regex = re.compile(r'alabama|alaska|arizona|arkansas|california|colorado|connecticut|delaware|florida|georgia|hawaii|idaho|illinois|indiana|iowa|kansas|kentucky|louisiana|maine|maryland|massachusetts|michigan|minnesota|mississippi|missouri|montana|nebraska|nevada|ohio|oklahoma|oregon|pennsylvania|tennessee|texas|utah|vermont|wisconsin|wyoming|virginia')
# Candidate names (need to catch any words belonging to the candidates name (first, middle, maiden, last))
# I want to later be able to catch all names as belonging to family members
def replace_candidate_name(split_name, text):
# Find all permutations of the words in a candidates' name
_gen = (itertools.permutations(split_name, i + 1) for i in range(len(split_name)))
all_permutations_gen = itertools.chain(*_gen)
# Create a regex from them
name_phrases = [' '. join(w) for w in all_permutations_gen]
name_phrases_no_single_initials = []
# Drop initials (they would match too many things)
for name_phrase in name_phrases:
if len(name_phrase) > 1:
name_phrases_no_single_initials.append(name_phrase)
# Have it do matches in decreasing order of complexity so full names get matched first
name_phrases_no_single_initials.reverse()
# Create regex.
candidate_regex ='|'.join(name_phrases_no_single_initials)
# Making sure the expression isn't catching when names are part of words
compiled_candidate_regex = re.compile('((^|\s)('+ candidate_regex + ')($|\s))')
return compiled_candidate_regex.sub(' candidate.name ', text)
# Reading in a list of common first names
myfile = open("firstnames.csv", "r") # "r" to only read the file
firstnames = csv.reader(myfile) # Get rows in the file
firstnameslist = []
for row in firstnames:
firstnameslist.append(row)
# Concatenating all first names into a single string separated by |
firstnames_data = ''
for item in firstnameslist:
firstnames_data += str(item[0]) +'|'
# Remove the final pipe so ever word used doesn't get added
firstnames_data
firstnames_data = firstnames_data[:-1]
# Making sure only exact matches happen
compiled_firstnames_regex = re.compile('((\s)('+ firstnames_data + ')($|\s))')
# Formatting how bigrams and trigrams will be reported
def cleaner(tuple):
out = tuple[0] + '_' + tuple[1]
return(out)
def cleaner_tri(tuple):
out = tuple[0] + '_' + tuple[1] + '_' + tuple[2]
return(out)
# Where to look for the files
os.chdir('./House Bios/')
stuff = ['Cleaned House Bios']
# Making dictionaries to store each file as a statement and store counts of words and phrases
# Making lists to fill with all unigrams, bigrams, and trigrams
statements = {}
word_store = {}
all_unigrams = []
all_bigrams = []
all_trigrams = []
# Storing the identifying information of each file along with all the text in each file
for z in stuff:
os.chdir('[redacted]House Bios/' + z)
files = os.listdir(os.getcwd())
for y in files:
splits = re.split("_", y)
state = splits[0]
party = splits[1]
name = splits[-1].split('.txt')[0]
split_name = re.split("-", name.lower())
filename = y
# Reading in text from each file, making lowercase, removing numbers, removing whitespace
text = open(y, 'r').readlines()
text = ' '.join(text)
text = text.lower()
text = re.sub('[0-9]+', '', text)
text = re.sub('\W', ' ', text)
#Making all states show up as "my.state", two state names are more complicated
text = re.sub(r'new hampshire', 'my.state', text)
text = re.sub(r'new jersey','my.state', text)
text = re.sub(r'new mexico', 'my.state',text)
text = re.sub(r'new york', 'my.state', text)
text = re.sub(r'north arolina', 'my.state', text)
text = re.sub(r'north dakota', 'my.state', text)
text = re.sub(r'rhode island', 'my.state', text)
text = re.sub(r'south carolina', 'my.state', text)
text = re.sub(r'south dakota', 'my.state', text)
text = re.sub(r'west virgina', 'my.state', text)
text = re.sub(states_regex, 'my.state', text)
#This is necessary to be able to find family names later
text = re.sub(r'<NAME>|pelosi', 'nancy_pelosi', text)
text = re.sub(r'<NAME>|schumer', 'chuck_schumer', text)
text = re.sub(r'<NAME>|clinton', 'hillary_clinton', text)
text = re.sub(r'<NAME>|trump', 'donald_trump', text)
text = re.sub(r'<NAME>|mcconnell', 'mitch_mcconnell', text)
text = re.sub(r'<NAME>', 'paul_ryan', text)
text = re.sub(r'<NAME>|biden', 'joe_biden', text)
text = re.sub(r'<NAME>', 'barack_obama', text)
text = re.sub(r'<NAME>', 'hugo_chavez', text)
text = re.sub(r'<NAME>', 'fidel_castro', text)
text = re.sub(r'<NAME>', 'kim_jong_un', text)
text = re.sub(r'<NAME>', 'benjamin_netanyahu', text)
text = re.sub(r'mao_zedong', 'mao_zedong', text)
text = re.sub(r'<NAME>', 'hurricane_katrina', text)
text = re.sub(r'<NAME>|<NAME>', 'hurricane_hermine', text)
# All mentions of the candidate will now appear as candidate.name
text = replace_candidate_name(split_name,text)
# All other first names will appear as family.name
text = re.sub(compiled_firstnames_regex, ' family.name ', text)
# Storing all of the identifying information of a file with the text
statements[y] = {"State": state, "Party": party,
"Name": name, "Text": text}
# Dictionaries for counts per statement for unigrams, bigrams, trigrams for words/phrases that aren't stop words
nestedDict = statements
for entry in nestedDict.values():
unigrams_statements = {}
bigrams_statements = {}
trigrams_statements = {}
tokes = word_tokenize(entry["Text"])
tokes_stemmed = map(pt.stem, tokes)
tokes_cleaned = [w for w in tokes_stemmed if w not in stop_words_stemmed and w not in original_stopwords_stemmed]
# Finding and formatting bigrams and trigrams
tokes_bi = bigrams(tokes_cleaned)
clean_bis = map(cleaner, list(tokes_bi))
tokes_tri = trigrams(tokes_cleaned)
clean_tris = map(cleaner_tri, list(tokes_tri))
# Counting unigrams, bigrams and trigrams per statement
for word in tokes_cleaned:
if word in unigrams_statements:
unigrams_statements[
word] += 1
elif word not in unigrams_statements:
unigrams_statements[word] = 1
all_unigrams.append(word)
for word in clean_bis:
if word in bigrams_statements:
bigrams_statements[
word] += 1
elif word not in bigrams_statements:
bigrams_statements[word] = 1
all_bigrams.append(word)
for word in clean_tris:
if word in trigrams_statements:
trigrams_statements[
word] += 1
elif word not in trigrams_statements:
trigrams_statements[word] = 1
all_trigrams.append(word)
entry['unigrams_statements'] = unigrams_statements
entry['bigrams_statements'] = bigrams_statements
entry['trigrams_statements'] = trigrams_statements
# Storing all unigrams and the most common bigrams and trigrams
most_used_unigrams = Counter(all_unigrams).most_common(20098)
most_used_bigrams = Counter(all_bigrams).most_common(100)
most_used_trigrams = Counter(all_trigrams).most_common(50)
# Writing the DTM
out = open('[Redacted]SenateDTM.csv', 'w')
out.write('State,Party,Name')
for word in most_used_unigrams:
out.write("," + word[0])
for word in most_used_bigrams:
out.write("," + word[0])
for word in most_used_trigrams:
out.write("," + word[0])
out.write('\n')
# Iterates through each statement of each senator
nestedDict = statements
for key in nestedDict:
out.write(nestedDict[key]["State"] + "," + nestedDict[key]["Party"] + "," + nestedDict[key]["Name"])
for word in most_used_unigrams:
if word[0] in nestedDict[key]["unigrams_statements"]:
count = nestedDict[key]["unigrams_statements"][
word[0]] # word is a tuple, so need to make sure it's only using the first element
else:
count = 0
out.write("," + str(count))
for word in most_used_bigrams:
if word[0] in nestedDict[key]["bigrams_statements"]:
count = nestedDict[key]["bigrams_statements"][
word[0]] # word is a tuple, so need to make sure it's only using the first element
else:
count = 0
out.write("," + str(count))
for word in most_used_trigrams:
if word[0] in nestedDict[key]["trigrams_statements"]:
count = nestedDict[key]["trigrams_statements"][
word[0]] # word is a tuple, so need to make sure it's only using the first element
else:
count = 0
out.write("," + str(count))
out.write('\n')
out.write("\n")
out.close()
<file_sep># Candidate Self Presentation Project
This project uses web scraping and machine learning to analyze how candidates presented themselves and their issue stances to voters in the 2018 election. This is an ongoing project, and as such, data files are not provided.
## Web Scraping
- Using csv files created from public candidate filing records for candidates, this project scrapes every available campaign website produced for U.S. Congressional Elections in 2018.
- Those csv files are not provided, but are used by house_bios.py, house_issues.py, senate_bios.py, and senate_issues.py to scrape every campaign website.
## Keeping biographies separate from issue pages
- As "About Me" pages and "Issue" pages are quite different, their information is kept separate for this project.
- Files are named logically to reflect this separation.
## Creating DTMs from the "About Me" pages
- In order to use the scraped information in ongoing machine learning projects, Document Term Matrices (DTMs) were created to easily store the data collected.
- These DTMs are created by HouseDTM.py and SenateDTM.py.
- These DTMs are used to create structural topic models, but are not provided here due to the ongoing nature of this work.
Questions or requests for data can be made to <EMAIL>.
<file_sep># Runs on Python 3.7. Packages that you need to have downloaded to run the code: beautiful soup, urlib.request
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
import re, os, csv
myfile = open("senate_websites.csv", "r") # "r" to only read the file
senatefile = csv.reader(myfile) # Get rows in the file
senatefilelist = []
for row in senatefile:
senatefilelist.append(row) # Storing all the info from the csv
def print_rows():
for row in senatefilelist:
print (row) # Print all rows in the file, doing this to double-check info was read in correctly
# Creating empty lists to be filled in and used for naming files later
state = []
partyid = []
name = []
sourceAddress = []
issueAddress = []
def get_csv_fields():
# Filling in those lists with info from csv
for row in senatefilelist:
state.append(row[0])
partyid.append(row[1])
name.append(row[2])
sourceAddress.append(row[3])
issueAddress.append(row[4])
def parse_data():
# Beginning the scraping
hdr = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'} # Some of the websites have security, this pretends I'm manually going to each site
for z in range(0, len(issueAddress)):
url = ''
try:
r = Request(issueAddress[z], headers=hdr)
url = urlopen(r).read()
except Exception as e: # Checking for errors, keeps looping even if errors
print(e) # Prints error associated with not being able to access the website
print(issueAddress[z]) # Print website if not being accessed
if url:
soup = BeautifulSoup(url)
# Get the text
paragraphs = soup.findAll('p') # Catches all html tags <p>, this gets most of the text for us. To learn more inspect individual webpages and notice what tags they use.
text = ''
for paragraph in paragraphs:
text += paragraph.text # For each webpage, everytime python finds a <p> tag it adds the text for that tag to "text" for each page.
if text:
# Writing filenames
filename = state[z] + "_" + partyid[z] + "_" + name[z] + '.txt'
# Writing the files
source = 'Senate Issues/%s' % (filename)
output = open(source, 'w')
output.write(text)
output.close()
else:
print(sourceAddress[z]) # Which websites don't use <p> in their formatting
# These can be uncommented when I want to re-create the files
if __name__ == '__main__':
print_rows() # Uncomment only to check the data was read in correctly
# get_csv_fields() # Uncomment to get the data
# parse_data() # Uncomment to write the files
<file_sep># Runs on Python 3.7. Packages that you need to have downloaded to run the code: beautiful soup, urlib.request
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
import re, os, csv
myfile = open("house_issues.csv", "r") # "r" to only read the file
housefile = csv.reader(myfile) # Get rows in the file
housefilelist = []
for row in housefile:
housefilelist.append(row) # Storing all the info from the csv
def print_rows():
for row in housefilelist:
print(row) # Print all rows in the file, doing this to double-check info was read in correctly
# Creating empty lists to be filled in and used for naming files later
state = []
district = []
partyid = []
name = []
sourceAddress = []
def get_csv_fields():
# Filling in those lists with info from csv
for row in housefilelist:
state.append(row[0])
district.append(row[1])
partyid.append(row[2])
name.append(row[3])
sourceAddress.append(row[4:])
def parse_data():
# Beginning the scraping
for z in range(0, len(sourceAddress)):
for address in sourceAddress[z]:
if address is not None and address != '':
process_site(address, z)
# Try to open the url. If it works, write the contents to a file.
def process_site(address, z):
hdr = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'} # Some of the websites have security, this pretends I'm manually going to each site
url = ''
try:
r = Request(address, headers=hdr)
url = urlopen(r).read()
except Exception as e: # Checking for errors, keeps looping even if errors
print(e) # Prints error associated with not being able to access the website
print(address) # Print website if not being accessed
if url:
write_site_to_file(address, url, z)
# Parses a url and writes the content of a site toa text file.
def write_site_to_file(address, url, z):
soup = BeautifulSoup(url)
# Get the text
paragraphs = soup.findAll(
'p') # Catches all html tags <p>, this gets most of the text for us. To learn more inspect individual webpages and notice what tags they use.
text = ''
for paragraph in paragraphs:
text += paragraph.text # For each webpage, everytime python finds a <p> tag it adds the text for that tag to "text" for each page.
if text:
# Writing filenames
filename = state[z] + "_" + district[z] + "_" + partyid[z] + "_" + name[z] + '.txt'
# Writing the files
source = 'House Issues/%s' % (filename)
output = open(source, 'a')
output.write(text)
output.close()
else:
print(address) # Which websites don't use <p> in their formatting
# These can be uncommented when I want to re-create the files
if __name__ == '__main__':
print_rows() # Uncomment only to check the data was read in correctly
get_csv_fields() # Uncomment to get the data
parse_data() # Uncomment to write the files
|
966337a0693867fb945244044fce883727b323f0
|
[
"Markdown",
"Python"
] | 4 |
Python
|
megsavel/US-2018-Congressional-Elections
|
2fa42ea45f1dd9e5a5e9634a4db5b4a6e615a328
|
1e4cae57874650da048f00d20d1657fb7554e14a
|
refs/heads/master
|
<repo_name>x15413812/SafetyMap<file_sep>/app/src/main/java/com/safetymap/safetymap/LocActivity.java
package com.safetymap.safetymap;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class LocActivity extends AppCompatActivity {
private Button view_map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc);
view_map = (Button) findViewById(R.id.View_Map);
view_map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(LocActivity.this, R.string.view_map_clicked, Toast.LENGTH_SHORT).show();
Intent i = new Intent(LocActivity.this, MapsActivity.class);
startActivity(i);
}
});
}
}<file_sep>/app/src/main/java/com/safetymap/safetymap/NumberActivity.java
package com.safetymap.safetymap;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NumberActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.number_layout);
final Button numberBtn = (Button) findViewById(R.id.numberBtn);
final EditText edNumber=(EditText) findViewById(R.id.edNumber);
numberBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Database database = new Database(getFilesDir().getPath());
database.saveUsername(edNumber.getText().toString());
Intent nextIntent = new Intent(NumberActivity.this,HomeActivity.class);
NumberActivity.this.startActivity(nextIntent);
}
});
}
}
<file_sep>/app/src/main/java/com/safetymap/safetymap/database.java
package com.safetymap.safetymap;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
class Database {
// Variables that will never change
public static final String FILE_NAME = "/name.txt";
public static final String ENCODING = "UTF-8";
private String directory;
public Database(String directory) {
this.directory = directory;
}
public void saveUsername(String name) {
try {
PrintWriter writer = new PrintWriter(directory + FILE_NAME, ENCODING);
writer.println(name);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//public String getUsername() {
//TODO read file with path directory + FILE_NAME
//}
}
<file_sep>/app/src/main/java/com/safetymap/safetymap/RegisterActivity.java
package com.safetymap.safetymap;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
final EditText nameTf = (EditText) findViewById(R.id.nameTf);
final Button nextBtn = (Button) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Database database = new Database(getFilesDir().getPath());
database.saveUsername(nameTf.getText().toString());
Intent nextIntent = new Intent(RegisterActivity.this,NumberActivity.class);
RegisterActivity.this.startActivity(nextIntent);
}
});
}
}
|
1d3448a9a514760913f8c07cfc733878ef977daf
|
[
"Java"
] | 4 |
Java
|
x15413812/SafetyMap
|
2e2ff635aea5cbded5d0207636fe8a9c0ead8812
|
b25b9bdec8e1e6d012695a3fb0b524de76da2c63
|
refs/heads/master
|
<file_sep>(function (root, factory) {
var nsParts = 'DecorativeLines'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('./lagrange/drawing/Alphabet'));
} else {
ns[name] = factory(lagrange.drawing.Alphabet);
}
}(this, function (Alphabet) {
"use strict";
//original scale factor
var Lines = {
scale : 0.1,
svgFile : 'assets/lignes.svg',
easepoints : {"folie":[[0.2643860025806711]],"wordDecorationEnd":[[0.6140462357835195]],"decembre":[[0.5796293820295325]],"nouvelles":[[0.2520739271467172,0.6689654220432111]]}
};
return Alphabet.factory(Lines);
}));<file_sep>/*!
* More info at http://lab.la-grange.ca
* @author <NAME> <<EMAIL>>
* @copyright 2014 <NAME> <<EMAIL>>
*
*/
(function (root, factory) {
var nsParts = 'lagrange/drawing/DrawPath'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
ns[name] = module.exports = factory(require('lodash'), require('raphael'), require('gsap'));
} else {
ns[name] = factory(root._, root.Raphael, (root.GreenSockGlobals || root));
}
}(this, function (_, Raphael, TweenMax) {
"use strict";
//gsap exports TweenMax
var gsap = window.GreenSockGlobals || window;
var defaults = {
color: '#000000',
strokeWidth : 0.6,
pxPerSecond : 100, //speed of drawing
easing : gsap.Quad.easeIn
};
//helper
var DrawPath = {
single : function(path, layer, params){
var settings = _.extend({}, defaults, params);
var pathStr = path.getSVGString();
var length = path.getLength();
var pxPerSecond;
var time;
//we can have either a time for the animation, or a number of pixels per second
if(settings.time){
time = settings.time;
pxPerSecond = length / time;
} else {
pxPerSecond = settings.pxPerSecond;
time = length / pxPerSecond;
}
//console.log(length, pxPerSecond, time);
var anim = {start: 0, end: 0};
var update = (function(){
//console.log('update');
var el;
return function(){
layer.remove(el);
if(anim.start === anim.end) return;
var pathPart = path.getSvgSub(anim.start, anim.end, true);
el = layer.add('path', pathPart);
el.attr({"stroke-width": settings.strokeWidth, stroke: settings.color});
};
})();
var easePoints = path.getEasepoints();
/*console.log(easePoints.length);
easePoints.forEach(function(pos){
var p = Raphael.getPointAtLength(pathStr, pos);
layer.showPoint(p, '#ff0000', 2);
});/**/
var animate = ['end'];
//do we need to "undraw" the path after it is drawn?
if(params.undraw) {
animate.push('start');
}
var getAnimate = function(prop, val){
var props = {ease : settings.easing};
props[prop] = val;
return props;
};
return animate.reduce(
function(tl, prop){
var last = 0;
return easePoints.reduce(function(tl, dist) {
var time = (dist-last) / pxPerSecond;
last = dist;
return tl.to(anim, time, getAnimate(prop, dist));
}, tl).to(anim, ((length - (easePoints.length && easePoints[easePoints.length-1])) / pxPerSecond), getAnimate(prop, length));
},
new gsap.TimelineMax({
onUpdate : update
})
);
var last = 0;
var tl = easePoints.reduce(function(tl, dist) {
var time = (dist-last) / pxPerSecond;
last = dist;
return tl.to(anim, time, {end: dist, ease : settings.easing});
}, new gsap.TimelineMax({
onUpdate : update
})).to(anim, ((length - (easePoints.length && easePoints[easePoints.length-1])) / pxPerSecond), {end: length, ease : settings.easing});
return tl;
},
group : function(paths, layer, settings, tl) {
return paths.reduce(function(tl, path){
return tl.append(DrawPath.single(path, layer, settings));
}, tl || new gsap.TimelineMax({paused:true}));
}
}
return DrawPath;
}));
<file_sep>'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;'+
'*/\n\n',
watch : {
js : {
files: 'app/**/*.js',
tasks: ['browserify:dev']
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
build: {
src: 'js/main.js',
dest: 'js/main.min.js'
},
common: {
src: 'js/common.js',
dest: 'js/common.js'
}
},
browserify : {
options : {
external: ['es5-shim', 'gsap', 'jquery', 'raphael', 'lodash'],
browserifyOptions : {
debug: false
}
},
dev : {
files: {
'js/main.js': ['app/Example.js'],
},
options : {
browserifyOptions : {
debug: true
},
}
},
prod : {
files: {
'js/main.js': ['app/Example.js'],
},
},
common: {
src: ['.'],
dest: 'js/common.js',
options: {
debug: false,
alias: [
'es5-shim:',
'jquery:',
'raphael:',
'gsap:',
'lodash:',
],
external : null,
},
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task.
grunt.registerTask('default', ['browserify:dev']);
grunt.registerTask('jslibs', ['browserify:common', 'uglify:common']);
grunt.registerTask('build', ['browserify:prod', 'uglify:prod']);
};
<file_sep>
var $ = require('jquery');
var PathEasepoints = require('./lagrange/drawing/PathEasepoints');/**/
var WriteNames = require('./WriteNames');
var Stage = require('./lagrange/drawing/Stage');
var docReady = (function(){
var d = $.Deferred();
$(document).ready(function(){
d.resolve()
});
return d.promise();
})();
var ready = $.when(docReady, WriteNames.load());
var doDraw = function(){
var container = $('#svg');
var words = [
{
text : 'Hello',
size : 1
},
{
text : 'Montréal',
size : 1.2,
append : function(DecorativeLines){
return {
symbol: DecorativeLines.getSymbol('wordDecorationEnd').getPaths()[0],
size: 1 //height in em
};
}
}
];
var stage = Stage.getStage('svg');
var tl = WriteNames.getTimeline(words, stage);
tl.play();
};
var btn = $('#ctrl');
btn.on('click.alphabet', function(){
ready.then(doDraw);
});
//parse les easepoints de chaque lettre, output en JSON (à saver)
var printEasepoints = function(){
//EmilieFont
//DecorativeLines
var EmilieFont = require('./lagrange/drawing/EmilieFont.js');
var DecorativeLines = require('./DecorativeLines');
PathEasepoints(Stage.getStage('svg'), DecorativeLines.getAll(), $('#brp'));
};
var getBpr = $('#getbrp');
getBpr.on('click.alphabet', function(){
ready.then(printEasepoints);
});
<file_sep><?php
$lst = file_get_contents('http://www.whoismorefamous.com/?fulllist=1');
$names = array(
'first'=>array(),
'last'=>array(),
);
preg_match_all('/<li>.*/i', $lst, $matchesLi);
foreach($matchesLi[0] as $name){
preg_match_all('/[a-z]{3,}/i', $name, $matches);
if($matches[0][0]) $names['first'][] = $matches[0][0];
if($matches[0][1]) $names['last'][] = $matches[0][1];
}
//Utils::debug($names);
$parsed = array();
for($i=0; $i<50; $i++){
$name = $names['first'][rand(0, count($names['first'])-1)] . ' ' . $names['last'][rand(0, count($names['last'])-1)];
$parsed[] = "$name";
}
echo json_encode($parsed);<file_sep>/*!
* More info at http://lab.la-grange.ca
* @author <NAME> <<EMAIL>>
* @copyright 2014 <NAME> <<EMAIL>>
*
* module pattern : https://github.com/umdjs/umd/blob/master/amdWebGlobal.js
*/
(function (root, factory) {
var nsParts = 'lagrange/drawing/VectorWord'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('./PathGroup'));
} else {
ns[name] = factory(lagrange.drawing.PathGroup);
}
}(this, function (PathGroup) {
"use strict";
var VectorWord = {
getPaths : function(alphabet, text) {
var right = 0;
var lines = new PathGroup(text);
var continuous = false;
//loop for every character in name (string)
for(var i=0; i<text.length; i++) {
var letter = text[i];
if(letter === ' ') {
right += alphabet.getNSpace();
continuous = false;
continue;
}
var letterDef = alphabet.getSymbol(letter) || alphabet.getSymbol('-');
//console.log(letter, letterDef);
var letterJoinedEnd = false;
letterDef.paths.forEach(function(path) {
var def = path.translate(right, 0);
var joinedStart = def.name && def.name.indexOf('joina') > -1;
var joinedEnd = /join(a?)b/.test(def.name);
//console.log(letter, joinedStart, joinedEnd);
letterJoinedEnd = letterJoinedEnd || joinedEnd;
if(joinedStart && continuous) {
//append au continuous
continuous.append(def, letter);
//ajoute les easepoints de ce path
var totalLength = continuous.getLength();
var pathStartPos = totalLength - def.getLength();
def.getEasepoints().forEach(function(pos){
continuous.addEasepoint((pathStartPos + pos) / totalLength);
});
} else if(joinedEnd && !continuous) {
//start un nouveau line (clone en scalant de 1)
continuous = def.clone();
continuous.name = letter;
lines.addPath(continuous);
} else {
lines.addPath(def);
}
if(!letterJoinedEnd) {
continuous = false;
}
});
right += letterDef.getWidth();
//console.table([{letter:name[i], letterWidth: letter.getWidth(), total:right}]);
}
//console.log(lines.getBounding());
var b = lines.getBounding();
lines.setOffset(-b.x, -b.y);
return lines;
}
};
return VectorWord;
}));
<file_sep>(function (root, factory) {
var nsParts = 'lagrange/drawing/Drawing'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'), require('lodash'), require('raphael'));
} else {
ns[name] = factory(root.jQuery, root._, root.Raphael);
}
}(this, function ($, _, Raphael) {
//helper
var showPoint = function(stage, point, color, size){
var el = stage.circle(point.x, point.y, size || 2);
el.attr({fill: color || '#ff0000', "stroke-width":0});
return el;
};
//layer is an extension of Raphael's set that is linked to a stage, so that you can add directly to it instead of havong to have acces to both the stage and the set.
var Layer = function(paper) {
this.add = function() {
var args = arguments;
var fcn = Array.prototype.shift.call(args);
if(!paper[fcn]) throw new Error(fcn + ' does not exist on Raphael');
var el = paper[fcn].apply(paper, args);
this.push(el);
return el;
};
this.remove = function(el) {
if(!el) return;
el.remove();
this.exclude(el);
};
this.showPoint = function(point, color, size){
var el = showPoint(paper, point, color, size);
this.push(el);
};
this.clearAndRemoveAll = function(){
var e;
while(e = this.pop()){
e.remove();
}
};
};
var Stage = function(name){
//le stage est un element contenu dans le container, pour pouvoir le resizer responsive
var container = $('#'+name);
var paperName = name+'Paper';
container.append('<div id="'+paperName+'"></div>');
var width = container.width();
var height = container.height();
var paper = Raphael(paperName, width, height);
var resizeNotifier = $.Deferred();
this.onResize = resizeNotifier.promise();
var onResize = function(){
width = container.width();
height = container.height();
paper.setSize(width, height);
resizeNotifier.notify({w:width, h:height});
};
$(window).on('resize.stage'+name, onResize);
this.width = function(){
return width;
};
this.height = function(){
return height;
};
this.clear = function(){
return paper.clear();
};
this.showPoint = function(point, color, size){
return showPoint(paper, point, color, size);
};
this.getNewLayer = function() {
var layer = paper.set();
layer = _.extend(layer, new Layer(paper));
return layer;
};
};
var getStage = (function(){
var stages = {};
var init = function(name){
return new Stage(name);
};
return function(name){
return stages[name] = stages[name] || init(name);
}
})();
return {
getStage : getStage,
showPoint : showPoint
};
}));<file_sep>(function (root, factory) {
var nsParts = 'rose/animations/WriteNames'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
module.exports = factory(
require('jquery'),
require('lodash'),
require('./lagrange/drawing/EmilieFont.js'),
require('./DecorativeLines'),
require('./lagrange/drawing/DrawPath'),
require('./lagrange/drawing/VectorWord'),
require('./lagrange/drawing/PathGroup'),
require('raphael'),
require('gsap'));
} else {
ns[name] = factory(root.jQuery, root._);
}
}(this, function ($, _, EmilieFont, DecorativeLines, DrawPath, VectorWord, PathGroup, Raphael, TweenMax) {
var gsap = window.GreenSockGlobals || window;
var defaultSettings = {
color: '#444444',
stroke: 2,
lineHeight: 1.2,
speed: 250 //px per second
};
var getAppend = function(paths, append){
var curve = append.symbol;
//trouve les points de départ et d'arrivée de la curve
var curveStr = curve.getSVGString();
var startPos = Raphael.getPointAtLength(curveStr, 0);
var endPos = Raphael.getPointAtLength(curveStr, curve.getLength());
var wordPaths = paths.getPaths();
//trouve le path qui finit le plus à droite dans les lettres
var lastPath = wordPaths.reduce(function(last, cur){
if(!last) return cur;
//si le path se finit plus à droite ET qu'il a un nom (les détails genre barre du t et point de i n'ont pas de nom)
if(cur.name && last.getBounding().x2 < cur.getBounding().x2){
last = cur;
}
return last;
}, null);
var wordEndPos = Raphael.getPointAtLength(lastPath.getSVGString(), lastPath.getLength());
//position absolue du point de départ du path
var absStartPos = {
x: wordEndPos.x - startPos.x,
y: wordEndPos.y - startPos.y
};
/*showPoint({x:wordEndPos.xx, y:wordEndPos.y}, '#22ff00');
showPoint(absStartPos, '#ff0000');/**/
//à combien de distance le boute est du début
var relEndPos = {
x: endPos.x - startPos.x,
y: endPos.y - startPos.y
};
//à quel endroit on doit faire arriver le endpos, relatif au début du path
var targetRelEndPos = {
x: - wordEndPos.x,
y: append.size * EmilieFont.getUpperLineHeight()
};
var ratio = {
x : targetRelEndPos.x / relEndPos.x,
y : targetRelEndPos.y / relEndPos.y,
};
/*console.log('start at',absStartPos);
console.log(targetRelEndPos);
console.log(ratio, currentEndPos);**/
var m = Raphael.matrix();
m.scale(ratio.x, ratio.y, absStartPos.x+startPos.x, absStartPos.y);
m.translate(absStartPos.x, absStartPos.y);
curve = curve.applyMatrix(m);
lastPath.append(curve);
return paths;
};
var getWords = function(words, lineHeight) {
var top = 0;
return words.map(function(word, lineNum){
var paths = VectorWord.getPaths(EmilieFont, word.text);
paths = paths.scale(word.size);
//center text
var width = paths.getWidth();
var left = - width / 2;
paths.setOffset(left, top);
top += EmilieFont.getUpperLineHeight() * lineHeight;
//ajoute le guidi sur le dernier mot
if(word.append) {
paths = getAppend(paths, word.append(DecorativeLines));
}
word.paths = paths;
return word;
});
};
//trouve le bounding box de l'ensemble des paths, s'en servira pour s'assurer que ça entre toujours dans le stage
var getBounding = function(words){
return words.reduce(function(g, w){
w.paths.getPaths().forEach(function(p){
g.addPath(p);
});
return g;
}, PathGroup.factory()).getBounding();
};
return {
getTimeline : function(words, stage, settings) {
settings = _.extend({}, defaultSettings, settings);
words = getWords(words, settings.lineHeight);
var bounding = getBounding(words);
var layer = stage.getNewLayer();
/*layer.showPoint({x:bounding.x, y:bounding.y});
layer.showPoint({x:bounding.x2, y:bounding.y2});/**/
//console.log(bounding);
var resizeSet = (function(){
var padding = 0.1;//%
var W = 0, H = 0;
return function(){
//if(stage.width === W && stage.height === H) return;
W = stage.width() * (1-padding);
H = stage.height() * (1-padding);
var scale = W / bounding.width;
var targetH = bounding.height * scale;
if(targetH > H){
scale = H / bounding.height;
}
var targetLeft = (stage.width() * padding * 0.5) + ((W - bounding.width) / 2) - bounding.x;
var targetTop = -(stage.height() * padding * 0.5) + (stage.height() - ( bounding.y + (bounding.height*scale)));
layer.transform('t'+targetLeft+','+targetTop+'s'+scale+','+scale+',0,0');
}
})();
stage.onResize.progress(resizeSet);
var tl = words.reduce(function(tl, word, lineNum){
return DrawPath.group(word.paths.getPaths(), layer, {
pxPerSecond : settings.speed * word.size,
color : settings.color,
strokeWidth : settings.stroke,
easing : gsap.Sine.easeInOut
}, tl);
}, new gsap.TimelineMax({paused:true, onUpdate: resizeSet}));
//tl.timeScale(0.2);
return tl;
},
load : function(){
return $.when(EmilieFont.load(), DecorativeLines.load());
}
};
}));<file_sep>/*!
* More info at http://lab.la-grange.ca
* @author <NAME> <<EMAIL>>
* @copyright 2014 <NAME> <<EMAIL>>
*
*/
(function (root, factory) {
var nsParts = 'lagrange/drawing/Alphabet'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'), require('./Path'), require('./PathGroup'));
} else {
ns[name] = factory(root.jQuery, root.lagrange.drawing.Path, root.lagrange.drawing.PathGroup);
}
}(this, function ($, Path, PathGroup) {
"use strict";
var specialChars = {
'_x2D_' : '-',
'_x2E_' : '.'
};
var Alphabet = function(){
var settings;
var symbols = {};
var parseSVG = function(data){
//console.log(data);
var doc = $(data);
var layers = doc.find('g');
layers.each(function(i, el){
var layer = $(el);
var id = layer.attr('id');
id = specialChars[id] || id;
//console.log(id);
//if(id.length > 1) return;
var paths = layer.find('path');
if(paths.length===0) return;
var symbol = symbols[id] = new PathGroup(id);
paths.each(function(i, el){
var pathEl = $(el);
var p = Path.factory( pathEl.attr('d'), pathEl.attr('id'), null, settings.easepoints[id] && settings.easepoints[id][i]).scale(settings.scale || 1);
symbol.addPath( p );
});
});
//trouve le top absolu (top de la lettre la plus haute)
var top = Object.keys(symbols).reduce(function(min, symbolName){
var t = symbols[symbolName].getTop();
if(min === undefined || min > t) {
min = t;
}
return min;
}, undefined);
//console.log(symbols);
//ajuste le baseline de chaque lettre
Object.keys(symbols).forEach(function(key) {
symbols[key].setOffset(-1 * symbols[key].getLeft(), -1 * top);
});
};
var doLoad = function(basePath){
var loading = $.ajax({
url : ((basePath && basePath+'/') || '') + settings.svgFile,
dataType : 'text'
});
loading.then(parseSVG, function(a, b, c){
console.log('error load');
console.log(b);
//console.log(c);
//console.log(a.responseText);
});
return loading.promise();
};
this.init = function(s) {
settings = s;
return this;
};
this.load = function(basePath) {
return doLoad(basePath);
};
this.getSymbol = function(l){
return symbols[l];
};
this.getNSpace = function(){
return symbols['n'] && symbols['n'].getWidth();
};
this.getLowerLineHeight = function(){
return symbols['n'] && symbols['n'].getHeight();
};
this.getUpperLineHeight = function(){
return symbols['N'] && symbols['N'].getHeight();
};
this.getAll = function(){
return symbols;
};
return this;
};
var instances = {};
Alphabet.factory = function(settings){
var svg = settings.svgFile;
instances[svg] = instances[svg] || (new Alphabet()).init(settings);
return instances[svg];
};
return Alphabet;
}));
<file_sep>/*!
* More info at http://lab.la-grange.ca
* @author <NAME> <<EMAIL>>
* @copyright 2014 <NAME> <<EMAIL>>
*
* module pattern : https://github.com/umdjs/umd/blob/master/amdWebGlobal.js
*/
(function (root, factory) {
var nsParts = 'lagrange/drawing/Path'.split('/');
var name = nsParts.pop();
var ns = nsParts.reduce(function(prev, part){
return prev[part] = (prev[part] || {});
}, root);
if (typeof exports === 'object') {
// CommonJS
ns[name] = module.exports = factory(require('raphael'));
} else {
ns[name] = factory(root.Raphael);
}
}(this, function (Raphael) {
"use strict";
var reg = /([a-z])([0-9\s\,\.\-]+)/gi;
//expected length of each type
var expectedLengths = {
m : 2,
l : 2,
v : 1,
h : 1,
c : 6,
s : 4
};
var Path = function(svg, name, parsed, easePoints) {
this.name = name;
//if(svg) console.log(svg, parsed);
this.easePoints = easePoints || [];
//console.log(name, easePoints);
this._setParsed(parsed || this._parse(svg));
};
Path.prototype._setParsed = function(parsed) {
//console.log(parsed);
this.svg = null;
this.parsed = parsed;
};
Path.prototype.getCubic = function() {
return this.cubic || this._parseCubic();
};
Path.prototype.getLength = function() {
return Raphael.getTotalLength(this.getSVGString());
};
/**
Gets an SVG string of the path segemnts. It is not the svg property of the path, as it is potentially transformed
*/
Path.prototype.getSVGString = function() {
return this.svg = this.svg || this.parsed.reduce(function(svg, segment){
return svg + segment.type + segment.anchors.join(',');
}, '');
};
/**
Gets the absolute positions at which we have ease points (which are preparsed and considered part of the path's definitions)
*/
Path.prototype.getEasepoints = function() {
var l = this.getLength();
return this.easePoints.map(function(e){
return e * l;
});
};
Path.prototype.getPoint = function(idx) {
//console.log(this.parsed);
return this.parsed[idx] && this.parsed[idx].anchors;
};
Path.prototype.getSvgSub = function(start, end, absolute) {
start = start || 0;
end = end || 1;
var subL = end - start;
var l = this.getLength();
if(!absolute) {
start *=l;
end *= l;
}
return Raphael.getSubpath(this.getSVGString(), start, end);
};
Path.prototype.getSub = function(start, end, absolute) {
var prcStart = absolute ? start / this.getLength() : start;
var subL = end - start;
var ease = this.easePoints.map(function(e){
return (e - prcStart) / subL;
}).filter(function(e){
return e > 0 && e < 1;
});/**/
return Path.factory(this.getSvgSub(start, end, absolute), this.name, null, ease);
};
/**
Parses an SVG path string to a list of segment definitions with ABSOLUTE positions using Raphael.path2curve
*/
Path.prototype._parse = function(svg) {
var curve = Raphael.path2curve(svg);
var path = curve.map(function(point){
return {
type : point.shift(),
anchors : point
};
});
return path;
};
/**
Parses a path defined by parsePath to a list of bezier points to be used by Greensock Bezier plugin, for example
TweenMax.to(sprite, 500, {
bezier:{type:"cubic", values:cubic},
ease:Quad.easeInOut,
useFrames : true
});
*/
Path.prototype._parseCubic = function() {
//console.log(path);
//assumed first element is a moveto
var anchors = this.cubic = this.parsed.reduce(function(anchors, segment){
var a = segment.anchors;
if(segment.type==='M'){
anchors.push({x: a[0], y:a[1]});
} else if(segment.type==='L'){
anchors.push({x: anchors[anchors.length-1].x, y: anchors[anchors.length-1].y})
anchors.push({x: a[0], y: a[1]});
anchors.push({x: anchors[anchors.length-1].x, y: anchors[anchors.length-1].y})
} else {
anchors.push({x: a[0], y: a[1]});
anchors.push({x: a[2], y: a[3]});
anchors.push({x: a[4], y: a[5]});
}
return anchors;
}, []);
return anchors;
};
//trouve le bounding box d'une lettre (en se fiant juste sur les points... on ne calcule pas ou passe le path)
Path.prototype.getBounding = function() {
return Raphael.pathBBox(this.getSVGString());
};
Path.prototype.translate = function(x, y) {
var m = Raphael.matrix();
m.translate(x, y);
return this.applyMatrix(m);
};
Path.prototype.rotate = function(deg) {
var m = Raphael.matrix();
m.rotate(deg);
return this.applyMatrix(m);
};
//returns a new path, scaled
Path.prototype.scale = Path.prototype.clone = function(ratiox, ratioy) {
ratiox = ratiox || 1;
var m = Raphael.matrix();
m.scale(ratiox, ratioy || ratiox);
return this.applyMatrix(m);
};
Path.prototype.applyMatrix = function(m){
var svg = Raphael.mapPath(this.getSVGString(), m);
return Path.factory(svg, this.name, null, this.easePoints.slice(0));
};
Path.prototype.append = function(part, name) {
//console.log(part);
if(name) this.name += name;
var origLength = this.getLength();
this._setParsed(this.parsed.concat(part.parsed.slice(1)));
var finalLength = this.getLength();
//remap easepoints, as length of path has changed
var lengthRatio = finalLength / origLength;
this.easePoints = this.easePoints.map(function(e){
return e / lengthRatio;
});
};
Path.prototype.addEasepoint = function(pos){
//console.log(this.easePoints, pos);
this.easePoints.push(pos);
};
Path.prototype.reverse = function(){
var svg = this.getSVGString();
var pathPieces = svg.match(/[MLHVCSQTA][-0-9.,]*/gi);
var reversed = '';
var skip = true;
var previousPathType;
for (var i = pathPieces.length - 1; i >= 0; i--) {
var pathType = pathPieces[i].substr(0, 1);
var pathValues = pathPieces[i].substr(1);
switch (pathType) {
case 'M':
case 'L':
reversed += (skip ? '' : pathType) + pathValues;
skip = false;
break;
case 'C':
var curvePieces = pathValues.match(/^([-0-9.]*,[-0-9.]*),([-0-9.]*,[-0-9.]*),([-0-9.]*,[-0-9.]*)$/);
reversed += curvePieces[3] + pathType + curvePieces[2] + ',' + curvePieces[1] + ',';
skip = true;
break;
default:
alert('Not implemented: ' + pathType);
break;
}
}
var ease = this.easePoints.map(function(e){
return 1 - e;
});
//console.log(reversed);
return Path.factory('M'+reversed, this.name, null, ease);
};
Path.factory = function(svg, name, parsed, easePoints) {
return new Path(svg, name, parsed, easePoints);
};
return Path;
}));
|
00e00bee2ee6c3f0899b2909a3026e0824578243
|
[
"JavaScript",
"PHP"
] | 10 |
JavaScript
|
LaGrangeMtl/grange-drawing
|
4adc0270f81c6b7317f1b3c1b32566273aaa0956
|
a417dc2a3f1f70818592efdea515e5d16b8f247c
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <vector>
//#include <ctime>
//#include <cstdlib>
#include <algorithm>
using namespace std;
int how_much_time(int position_of_leaves[], int width);
int main()
{
//srand( time( 0 ) );
int width_of_a_river = 5;
const int size = 8;
int A[size];
A[0] = 1;
A[1] = 3;
A[2] = 1;
A[3] = 4;
A[4] = 2;
A[5] = 3;
A[6] = 5;
A[7] = 4;
// for (int i = 0; i < size; i++)
// {
// A[i] = ((rand()%5)+ 1);
// cout << A[i] << endl;
// }
int time = how_much_time(A, width_of_a_river);
if (time > 0)
cout << "Frog needs to wait for " << time << " seconds until there are enough leaves to jump across the river. " << endl;
else
cout << "The are not enough leaves for the frog to jump across the river. " << endl;
return 0;
}
int how_much_time(int position_of_leaves[], int width)
{
vector <int> gaps;
for (int i = 0 ; i < width; i++)
{
gaps.push_back(i + 1);
}
int time = 0;
for (time = 0; time < 8; time++)
{
gaps.erase(remove(gaps.begin(), gaps.end(), position_of_leaves[time]), gaps.end());
if (gaps.empty())
{
return time;
}
}
return -1;
}
|
039295e9f06cf3c9b9692801bedb897824659741
|
[
"C++"
] | 1 |
C++
|
AnnaGawrysiak/Frog_and_autumn_river
|
f7188c8296b0160b85b005d2ef106dd6fcb71013
|
f109d8b74cdca1e6504920957ea691ebb95f7208
|
refs/heads/master
|
<file_sep>var express = require('express')
var serveIndex = require('serve-index')
var app = express()
// Serve URLs like /ftp/thing as public/ftp/thing
app.use('/', express.static('/home'), serveIndex('/home', {'icons': true}));
app.listen(80)
<file_sep>FROM ubuntu:14.04
MAINTAINER <NAME>
RUN export DEBIAN_FRONTEND=noninteractive && \
apt-get update && \
apt-get install curl -y && \
curl -sL https://deb.nodesource.com/setup_5.x | bash - && \
apt-get install -y openssh-server supervisor vsftpd nodejs build-essential -y
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
ADD vsftpd.conf /etc/
RUN mkdir -p /var/run/sshd /var/log/supervisor && \
mkdir -p /var/run/vsftpd/empty && \
chown root:root /etc/vsftpd.conf
RUN adduser --disabled-password --gecos '' user
RUN echo 'user:password' | chpasswd
ADD app /app
RUN cd /app && npm install
VOLUME /home
EXPOSE 21/tcp 80
CMD ["/usr/bin/supervisord"]
|
fb20ba44a3d6d29a8a721c50f9e1af0934b43343
|
[
"JavaScript",
"Dockerfile"
] | 2 |
JavaScript
|
okvic77/docker-webftp
|
804e898d02a238e18d1fc7d6bf9c5468a38252a3
|
282f6a2a7071b49f794d18d68439307d94e4b48a
|
refs/heads/master
|
<file_sep># Ejercicios 1 y 2
En este proyecto va incluído el ejercicio 1 y ejercicio 2, donde es Dockerizado "NodeJS" y la base de datos MongoDB, la generación de la API es con "Json" utilizando "Postman"
para que funcione completamente el proyecto se deben instalar algunos módulos necesarios.
### Pre-requisitos 📋
*npm i express
*npm i mongoose
*npm i faker
*npm nodemon -D
*npm i json-server
*npm i underscore
*npm i fs
Para entrar al CRUD de API en "Postman" el link es http://localhost:4000/api/empresas para GET y POST, para DELETE y PUT es http://localhost:4000/api/empresas/(id del elemento)
<file_sep>a, b = 1,1
contador = 0
while(a > 0):
print(a, end=' ')
a, b = b, a + b
for i in range(a, a+1):
if a % i == 0:
contador += 1
if contador > 1000:
print("El número",a ,"tiene 1000 divisores")
a = 0
<file_sep>const faker = require('faker/locale/es');
const fs = require('fs');
var cant = 2 //cantidad de empresas que desea generar
const {Schema, model} = require('mongoose');
const empresaSchema = new Schema({
nombre_empresa: String,
sufijo_empresa: String,
descrip_empresa: String,
},{
timestamp: true
});
/*function generateCompany() {
let empresas = [];
for (let id = 1; id <= cant; id++){
const nombre_empresa = faker.company.companyName();
const sufijo_empresa = faker.company.companySuffix();
const descrip_empresa = faker.company.catchPhraseDescriptor();
empresas.push({
id:id,
nombre_empresa: nombre_empresa,
sufijo_empresa: sufijo_empresa,
descrip_empresa: descrip_empresa,
})
}
return { data: empresas }
}*/
//const generatedCompany = generateCompany();
//fs.writeFileSync('src/data.json', JSON.stringify(generatedCompany, null, "\t"))
//module.exports = model("empresa", empresas);
<file_sep>import random
def dias(kms: int):
if kms < 100:
return 0
if kms < 200:
return dias(kms=(kms-100)) + 1
return dias(kms=(kms-100)) + dias(kms=(kms-200))
kms = random.randint(0, 2000)
days = dias(kms=kms)
print(f'Será entregado en: {days} días. Distancia: {kms}')
<file_sep>CREATE DATABASE IF NOT EXISTS `ejercicio7` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `ejercicio7`;
-- MySQL dump 10.13 Distrib 8.0.25, for Win64 (x86_64)
--
-- Host: localhost Database: ejercicio7
-- ------------------------------------------------------
-- Server version 8.0.25
/*!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 */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `continents`
--
DROP TABLE IF EXISTS `continents`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `continents` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`anual_adjustment` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `continents`
--
LOCK TABLES `continents` WRITE;
/*!40000 ALTER TABLE `continents` DISABLE KEYS */;
INSERT INTO `continents` VALUES (1,'América',4),(2,'Europa',5),(3,'Asia',6),(4,'Oceanía',6),(5,'Africa',5);
/*!40000 ALTER TABLE `continents` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `countries`
--
DROP TABLE IF EXISTS `countries`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `countries` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`continent_id` int NOT NULL,
`name` varchar(25) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `countries`
--
LOCK TABLES `countries` WRITE;
/*!40000 ALTER TABLE `countries` DISABLE KEYS */;
INSERT INTO `countries` VALUES (1,1,'Chile'),(2,1,'Argentina'),(3,1,'Canadá'),(4,1,'Colombia'),(5,2,'Alemania'),(6,2,'Francia'),(7,2,'España'),(8,2,'Grecia'),(9,3,'India'),(10,3,'Japón'),(11,3,'Corea del Sur'),(12,4,'Australia');
/*!40000 ALTER TABLE `countries` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `employees`
--
DROP TABLE IF EXISTS `employees`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `employees` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`country_id` int NOT NULL,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`salary` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `employees`
--
LOCK TABLES `employees` WRITE;
/*!40000 ALTER TABLE `employees` DISABLE KEYS */;
INSERT INTO `employees` VALUES (1,1,'Pedro','Rojas',2080),(2,2,'Luciano','Alessandri',2184),(3,3,'John','Carter',3172),(4,4,'Alejandra','Benavides',2236),(5,5,'Moritz','Baring',6000),(6,6,'Thierry','Henry',5900),(7,7,'Sergio','Ramos',6200),(8,8,'Nikoleta','Kyriakopulu',7000),(9,9,'Aamir','Khan',2120),(10,10,'Takumi','Fujiwara',5300),(11,11,'Heung-min','Son',5100),(12,12,'Peter','Johnson',6100);
/*!40000 ALTER TABLE `employees` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!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 */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2021-05-13 22:55:24
|
6544a214e37f5a83ff650e2ded73bc97c6da7443
|
[
"Markdown",
"SQL",
"Python",
"JavaScript"
] | 5 |
Markdown
|
Lack01/Challenge_Enviame
|
ea57d4d118e73f82aaf6a19619537f019b5f0af3
|
cec58a6f86625f79478a1ecd0da983967b3f154d
|
refs/heads/master
|
<file_sep>'use strict';
module.exports = function(Subjects) {
};
|
5e6ee9642df560424a7ee99749a06fc65c212e8c
|
[
"JavaScript"
] | 1 |
JavaScript
|
KalanaDananjaya/quizeez
|
5a3abfb668df67be7489dbd6ee56e9649d3438a2
|
8cfe8816e7487d7884efca9a89a9ee4a3ebad47d
|
refs/heads/master
|
<repo_name>rafaelgckto/Senai-Dev<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/ClasseRepository.cs
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class ClasseRepository : IClasseRepository {
HroadsContext ctx = new HroadsContext();
public void Delete(int id) {
ctx.Classes.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Classe> ListAll() {
return ctx.Classes.ToList();
}
public List<Classe> ListNames() {
throw new System.NotImplementedException();
}
public void Register(Classe newEntity) {
ctx.Classes.Add(newEntity);
ctx.SaveChanges();
}
public Classe SearchById(int id) {
return ctx.Classes.FirstOrDefault(c => c.IdClasse == id);
}
public void Update(int id, Classe newEntity) {
Classe classSought = SearchById(id);
if(classSought != null) {
classSought.Nome = newEntity.Nome;
}
ctx.Classes.Update(classSought);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Controller/Base/IStandardController.cs
using Microsoft.AspNetCore.Mvc;
namespace Senai.Hroads.WebApi.Interfaces.Controller.Base {
interface IStandardController<TEntity> {
IActionResult Get();
IActionResult Get(int id);
IActionResult Post(TEntity newEntity);
IActionResult Put(int id, TEntity newEntity);
IActionResult Delete(int id);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Interfaces/Controller/IJogosController.cs
using Microsoft.AspNetCore.Mvc;
using Senai.InLock.WebApi.Domains;
namespace Senai.InLock.WebApi.Interfaces.Controller {
interface IJogosController : IStandardController<JogosDomain> {
IActionResult GetGamesStudios();
}
}
<file_sep>/5º Sprint-Mobile/mobile/src/screens/login.js
import React, { Component } from "react";
import {
Image,
ImageBackground,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import api from "../services/api";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
senha: "",
};
}
realizarLogin = async () => {
console.warn(this.state.email + " " + this.state.senha);
const resposta = await api.post("/login", {
email: this.state.email,
senha: this.state.senha,
});
const token = resposta.data.token;
console.warn(token);
await AsyncStorage.setItem("userToken", token);
this.props.navigation.navigate("Consulta");
};
render() {
const styles = StyleSheet.create({
overlay: {
...StyleSheet.absoluteFillObject,
backgroundColor: "white",
},
main: {
width: "100%",
height: "100%",
justifyContent: "center",
alignItems: "center",
},
mainImgLogin: {
tintColor: "#FFF",
height: 100,
width: 90,
margin: 60,
marginTop: 0,
},
inputLogin: {
width: 220,
marginBottom: 30,
fontSize: 18,
color: "#000",
borderColor: "#000",
borderWidth: 1,
borderRadius: 10,
},
btnLogin: {
alignItems: "center",
justifyContent: "center",
height: 38,
width: 165,
color: "#000",
borderRadius: 10,
shadowOffset: { height: 1, width: 1 },
},
btnLoginText: {
fontSize: 12,
fontFamily: "Poppins",
color: "#000",
letterSpacing: 5,
textTransform: "uppercase",
},
});
return (
<ImageBackground source="" style={StyleSheet.absoluteFillObject}>
<View style={styles.overlay} />
<View style={styles.main}>
<Image source="" style={styles.mainImgLogin} />
<TextInput
style={styles.inputLogin}
placeholder="username"
placeholderTextColor="#FFF"
keyboardType="email-address"
onChangeText={(email) => this.setState({ email })}
/>
<TextInput
style={styles.inputLogin}
placeholder="<PASSWORD>"
placeholderTextColor="#FFF"
secureTextEntry={true}
onChangeText={(senha) => this.setState({ senha })}
/>
<TouchableOpacity
style={styles.btnLogin}
onPress={this.realizarLogin}
>
<Text style={styles.btnLoginText}>login</Text>
</TouchableOpacity>
</View>
</ImageBackground>
);
}
}
export default Login;
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/UsuarioController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Controllers.Base;
using MedicalGroup.WebApi.Interfaces.Repositories;
using MedicalGroup.WebApi.Repositories;
using System;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class UsuarioController : ControllerBase, IStandardController<Usuario> {
IUsuarioRepository _userRepository { get; set; }
public UsuarioController() {
_userRepository = new UsuarioRepository();
}
/// <summary>
/// Deleta um usuário.
/// </summary>
/// <param name="id">O id do usuário que será deletado.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
try {
_userRepository.Delete(id);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Lista todos os usuários.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de usuários.</returns>
[HttpGet]
public IActionResult Get() {
try {
return Ok(_userRepository.ListAll());
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Busca apenas um usuário.
/// </summary>
/// <param name="id">O id do usuário que será buscado.</param>
/// <returns>Retorna um objeto JSON, do usuário buscado.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
try {
return Ok(_userRepository.SearchById(id));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Cadastra um novo usuário.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles ="1")]
[HttpPost]
public IActionResult Post(Usuario newEntity) {
try {
_userRepository.Register(newEntity);
return StatusCode(201);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Atualiza um usuário.
/// </summary>
/// <param name="id">O id do usuário escolhido a ser atualizado.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Usuario newEntity) {
try {
_userRepository.Update(id, newEntity);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/Peoples/Senai.Peoples/Senai.Peoples.WebApi/Interfaces/IFuncionarioRepository.cs
using Senai.Peoples.WebApi.Domains;
using System.Collections.Generic;
namespace Senai.Peoples.WebApi.Interfaces {
/// <summary>
/// Interface responsável pelo repositório 'FuncionarioRepository'.
/// </summary>
interface IFuncionarioRepository {
List<Funcionario> Get();
Funcionario GetById(int id);
Funcionario GetByName(string nameEmployee);
List<Funcionario> GetFullName();
List<Funcionario> GetOrdination(string order);
void Insert(Funcionario newEmployee);
void Update(Funcionario employee);
void UpdateIdUrl(int id, Funcionario employee);
void Delete(int id);
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Repositories/EnderecoRepository.cs
using MedicalGroup.WebApi.Contexts;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
using System.Linq;
namespace MedicalGroup.WebApi.Repositories {
public class EnderecoRepository : IStantardRepository<Endereco> {
MedicalGroupContext ctx = new MedicalGroupContext();
public void Delete(int id) {
ctx.Enderecos.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Endereco> ListAll() {
return ctx.Enderecos.ToList();
}
public void Register(Endereco newEntity) {
ctx.Enderecos.Add(newEntity);
ctx.SaveChanges();
}
public Endereco SearchById(int id) {
return ctx.Enderecos.FirstOrDefault(end => end.IdEndereco == id);
}
public void Update(int id, Endereco newEntity) {
Endereco searchedAddress = ctx.Enderecos.Find(id);
if(searchedAddress != null) {
// UNDONE: searchedAddress != null
}
ctx.Enderecos.Update(searchedAddress);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Interfaces/Repository/Base/IStandardRepository.cs
using System.Collections.Generic;
namespace Senai.InLock.WebApi.Interfaces {
interface IStandardRepository<TEntity> {
List<TEntity> ListAll();
TEntity SearchById(int id);
void Register(TEntity newTEntity);
void Update(TEntity newTEntity);
void Delete(int id);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Repositories/IClasseRepository.cs
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
namespace Senai.Hroads.WebApi.Interfaces.Repositories {
interface IClasseRepository : IStandardRepository<Classe> {
List<Classe> ListNames();
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Contexts/HroadsContext.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Domains;
#nullable disable
namespace Senai.Hroads.WebApi.Contexts {
public partial class HroadsContext : DbContext {
public HroadsContext() {
}
public HroadsContext(DbContextOptions<HroadsContext> options)
: base(options) {
}
public virtual DbSet<Classe> Classes { get; set; }
public virtual DbSet<ClasseHabilidade> ClasseHabilidades { get; set; }
public virtual DbSet<Habilidade> Habilidades { get; set; }
public virtual DbSet<Personagem> Personagems { get; set; }
public virtual DbSet<TipoHabilidade> TipoHabilidades { get; set; }
public virtual DbSet<TipoUsuario> TipoUsuarios { get; set; }
public virtual DbSet<Usuario> Usuarios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
if(!optionsBuilder.IsConfigured) {
//#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Data Source=CELSO-PC; initial catalog=Senai_Hroads_Manha; user Id=sa; pwd=<PASSWORD>;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasAnnotation("Relational:Collation", "Latin1_General_CI_AS");
modelBuilder.Entity<Classe>(entity => {
entity.HasKey(e => e.IdClasse);
entity.ToTable("Classe");
entity.Property(e => e.IdClasse).HasColumnName("idClasse");
entity.Property(e => e.Nome)
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("nome");
});
modelBuilder.Entity<ClasseHabilidade>(entity => {
entity.HasKey(e => e.IdClasseHabilidade)
.HasName("PK_ClasseHabilidade");
entity.ToTable("Classe_Habilidade");
entity.Property(e => e.IdClasseHabilidade).HasColumnName("idClasseHabilidade");
entity.Property(e => e.IdClasse).HasColumnName("idClasse");
entity.Property(e => e.IdHabilidade).HasColumnName("idHabilidade");
entity.HasOne(d => d.IdClasseNavigation)
.WithMany(p => p.ClasseHabilidades)
.HasForeignKey(d => d.IdClasse)
.HasConstraintName("FK_Classe");
entity.HasOne(d => d.IdHabilidadeNavigation)
.WithMany(p => p.ClasseHabilidades)
.HasForeignKey(d => d.IdHabilidade)
.HasConstraintName("FK_Habilidade");
});
modelBuilder.Entity<Habilidade>(entity => {
entity.HasKey(e => e.IdHabilidade);
entity.ToTable("Habilidade");
entity.Property(e => e.IdHabilidade).HasColumnName("idHabilidade");
entity.Property(e => e.IdTipoHabilidade).HasColumnName("idTipoHabilidade");
entity.Property(e => e.Nome)
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("nome");
entity.HasOne(d => d.IdTipoHabilidadeNavigation)
.WithMany(p => p.Habilidades)
.HasForeignKey(d => d.IdTipoHabilidade)
.HasConstraintName("FK_TipoHabilidade_Habilidade");
});
modelBuilder.Entity<Personagem>(entity => {
entity.HasKey(e => e.IdPersonagem);
entity.ToTable("Personagem");
entity.Property(e => e.IdPersonagem).HasColumnName("idPersonagem");
entity.Property(e => e.DtAtualizacao)
.HasColumnType("date")
.HasColumnName("dtAtualizacao");
entity.Property(e => e.DtCricao)
.HasColumnType("date")
.HasColumnName("dtCricao");
entity.Property(e => e.IdClasse).HasColumnName("idClasse");
entity.Property(e => e.Mana)
.HasColumnType("decimal(5, 2)")
.HasColumnName("mana");
entity.Property(e => e.Nome)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("nome");
entity.Property(e => e.Vida)
.HasColumnType("decimal(5, 2)")
.HasColumnName("vida");
entity.HasOne(d => d.IdClasseNavigation)
.WithMany(p => p.Personagems)
.HasForeignKey(d => d.IdClasse)
.HasConstraintName("FK_Classe_Personagem");
});
modelBuilder.Entity<TipoHabilidade>(entity => {
entity.HasKey(e => e.IdTipoHabilidade);
entity.ToTable("TipoHabilidade");
entity.Property(e => e.IdTipoHabilidade).HasColumnName("idTipoHabilidade");
entity.Property(e => e.Tipo)
.HasMaxLength(25)
.IsUnicode(false)
.HasColumnName("tipo");
});
modelBuilder.Entity<TipoUsuario>(entity => {
entity.HasKey(e => e.IdTipoUsuario);
entity.ToTable("TipoUsuario");
entity.Property(e => e.IdTipoUsuario).HasColumnName("idTipoUsuario");
entity.Property(e => e.Tipo)
.HasMaxLength(25)
.IsUnicode(false)
.HasColumnName("tipo");
});
modelBuilder.Entity<Usuario>(entity => {
entity.HasKey(e => e.IdUsuario);
entity.ToTable("Usuario");
entity.Property(e => e.IdUsuario).HasColumnName("idUsuario");
entity.Property(e => e.Email)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("email");
entity.Property(e => e.IdTipoUsuario).HasColumnName("idTipoUsuario");
entity.Property(e => e.Senha)
.HasMaxLength(255)
.IsUnicode(false)
.HasColumnName("senha");
entity.HasOne(d => d.IdTipoUsuarioNavigation)
.WithMany(p => p.Usuarios)
.HasForeignKey(d => d.IdTipoUsuario)
.HasConstraintName("FK_TipoUsuario_PK_Usuario");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Repositories/JogosRepository.cs
using Senai.InLock.WebApi.Domains;
using Senai.InLock.WebApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace Senai.InLock.WebApi.Repositories {
public class JogosRepository : IJogosRepository {
const string connectionString = "Server=CELSO-PC;Database=InLock_Games;User Id=sa;Password=<PASSWORD>;";
public void Delete(int id) {
throw new System.NotImplementedException();
}
public List<JogosDomain> ListAll() {
throw new System.NotImplementedException();
}
public List<JogosDomain> ListGamesStudios() {
// MVP
List<JogosDomain> listUsers = new List<JogosDomain>();
using(SqlConnection con = new SqlConnection(connectionString)) {
string querySelectAll = "SELECT * FROM Jogos AS J INNER JOIN Estudios AS E ON J.idEstudio = E.idEstudio;";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(querySelectAll, con)) {
sdr = cmd.ExecuteReader();
while(sdr.Read()) {
JogosDomain game = new JogosDomain() {
idJogo = Convert.ToInt32(sdr[0]),
nome = sdr[1].ToString(),
descricao = sdr[2].ToString(),
dtLancamento = Convert.ToDateTime(sdr[3]),
valor = decimal.Parse(sdr[4].ToString()),
idEstudio = Convert.ToInt32(sdr[5]),
estudio = new EstudiosDomain() {
idEstudio = Convert.ToInt32(sdr[6]),
nome = sdr[7].ToString()
}
};
listUsers.Add(game);
}
return listUsers;
}
}
}
public List<JogosDomain> ListStudiosGames() {
throw new System.NotImplementedException();
}
public void Register(JogosDomain newTEntity) {
// MVP
using(SqlConnection con = new SqlConnection(connectionString)) {
string queryInsert = "INSERT INTO Jogos(nome, descricao, dtLancamento, valor, idEstudio) VALUES(@nome, @descricao, @dtLancamento, @valor, @idEstudio)";
using(SqlCommand cmd = new SqlCommand(queryInsert, con)) {
cmd.Parameters.AddWithValue("@nome", newTEntity.nome);
cmd.Parameters.AddWithValue("@descricao", newTEntity.descricao);
cmd.Parameters.AddWithValue("@dtLancamento", newTEntity.dtLancamento);
cmd.Parameters.AddWithValue("@valor", newTEntity.valor);
cmd.Parameters.AddWithValue("@idEstudio", newTEntity.idEstudio);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
public JogosDomain SearchById(int id) {
throw new System.NotImplementedException();
}
public void Update(JogosDomain newTEntity) {
throw new System.NotImplementedException();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/Peoples/Modeling Scripts/people_DQL.sql
USE Peoples;
SELECT *
FROM Funcionario;
SELECT nome, sobrenome
FROM Funcionario
WHERE nome = 'Catarina';
SELECT CONCAT(nome, ' ', sobrenome) AS [Nome Completo]
FROM Funcionario;
SELECT nome, sobrenome
FROM Funcionario
ORDER BY nome ASC;--ASC OU DESC<file_sep>/4º Sprint-Front_End/SP Medical Group/frontend/src/components/Aside.jsx
import React from "react";
import { parseJwt, usuarioAutenticado } from "../services/auth";
import "../assets/css/aside.css";
import logo from "../assets/img/png/logo_spmedgroup_v2.png";
import profileADM from "../assets/img/svg/management3.svg";
import profileDoctor from "../assets/img/png/doctor1.png";
import profilePatient from "../assets/img/svg/patient3.svg";
function Aside() {
const user = usuarioAutenticado() && parseJwt().role;
return (
<aside className="aside-body">
<img className="aside-img-logo" src={logo} alt="Logo Medical Group" />
{user === "1" && (
<img
className="aside-img-profile"
src={profileADM}
alt="Imagem de Perfil"
/>
)}
{user === "2" && (
<img
className="aside-img-profile"
src={profileDoctor}
alt="Imagem de Perfil"
/>
)}
{user === "3" && (
<img
className="aside-img-profile"
src={profilePatient}
alt="Imagem de Perfil"
/>
)}
</aside>
);
}
export default Aside;
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Repositories/ConsultaRepository.cs
using Microsoft.EntityFrameworkCore;
using MedicalGroup.WebApi.Contexts;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace MedicalGroup.WebApi.Repositories {
public class ConsultaRepository : IConsultaRepository {
MedicalGroupContext ctx = new MedicalGroupContext();
public void Delete(int id) {
ctx.Consulta.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Consulta> ListAll() {
return ctx.Consulta
.Include(m => m.IdMedicoNavigation)
.Include(m => m.IdMedicoNavigation.IdEspecialidadeNavigation)
.Include(p => p.IdPacienteNavigation)
.Include(s => s.IdSituacaoNavigation)
.ToList();
}
public List<Consulta> ListMedico(string name) {
return ctx.Consulta
.Include(m => m.IdMedicoNavigation)
.Include(m => m.IdMedicoNavigation.IdEspecialidadeNavigation)
.Include(m => m.IdMedicoNavigation.IdUsuarioNavigation)
.Include(p => p.IdPacienteNavigation)
.Include(p => p.IdPacienteNavigation.IdUsuarioNavigation)
.Include(s => s.IdSituacaoNavigation)
.Where(m => m.IdMedicoNavigation.Nome == name)
.ToList();
}
public List<Consulta> ListPaciente(string name) {
return ctx.Consulta
.Include(m => m.IdMedicoNavigation)
.Include(m => m.IdMedicoNavigation.IdEspecialidadeNavigation)
.Include(m => m.IdMedicoNavigation.IdUsuarioNavigation)
.Include(p => p.IdPacienteNavigation)
.Include(p => p.IdPacienteNavigation.IdUsuarioNavigation)
.Include(s => s.IdSituacaoNavigation)
.Where(p => p.IdPacienteNavigation.Nome == name)
.ToList();
}
public void Register(Consulta newEntity) {
ctx.Consulta.Add(newEntity);
ctx.SaveChanges();
}
public Consulta SearchById(int id) {
return ctx.Consulta.FirstOrDefault(con => con.IdConsulta == id);
}
public void Update(int id, Consulta newEntity) {
Consulta fetchedQuery = ctx.Consulta.Find(id);
if(newEntity != null) {
// UNDONE: newEntity.<atributo> != null
fetchedQuery = newEntity;
}
ctx.Consulta.Update(fetchedQuery);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Repositories/IUsuarioRepository.cs
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
namespace Senai.Hroads.WebApi.Interfaces.Repositories {
interface IUsuarioRepository : IStandardRepository<Usuario> {
Usuario Login(string email, string password);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Controllers/LoginController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using Senai.Hroads.WebApi.Repositories;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace Senai.Hroads.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase {
IUsuarioRepository _userRepository { get; set; }
public LoginController() {
_userRepository = new UsuarioRepository();
}
/// <summary>
/// Valida o usuário.
/// </summary>
/// <param name="login">Objeto login que contém o e-mail e a senha do usuário.</param>
/// <returns>Retorna um token com as informações do usuário.</returns>
[HttpPost]
public IActionResult PostLogin(Usuario login) {
Usuario searchedUser = _userRepository.Login(login.Email, login.Senha); // Busca o usuário pelo e-mail e senha.
// Caso não encontre nenhum usuário com o e-mail e senha informados.
if(searchedUser == null)
return NotFound("E-mail ou senha inválidos."); // Retorna 'NotFound' com uma mensagem personalizada.
// Define os dados que serão fornecidos no token - Payload.
var claims = new[] {
// Formato da Claim = TipoDaClaim, ValorDaClaim.
new Claim(JwtRegisteredClaimNames.Email, searchedUser.Email),
new Claim(JwtRegisteredClaimNames.Jti, searchedUser.IdUsuario.ToString()),
new Claim(ClaimTypes.Role, searchedUser.IdTipoUsuario.ToString()),
new Claim("Claim personalizada", "Valor teste")
};
// Define a chave de acesso ao token.
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("hroads-chave-autenticacao"));
// Define as credenciais do token - Header.
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// Gerar o token.
var token = new JwtSecurityToken(
issuer: "Hroads.webApi", // Emissor do token.
audience: "Hroads.webApi", // Destinatário do token.
claims: claims, // Dados definidos acima.
expires: DateTime.Now.AddMinutes(30), // Tempo de expiração.
signingCredentials: creds // Credenciais do token.
);
return Ok(new {
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Domains/Paciente.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace MedicalGroup.WebApi.Domains
{
public partial class Paciente
{
public Paciente()
{
Consulta = new HashSet<Consulta>();
}
public int IdPaciente { get; set; }
public string Nome { get; set; }
public string Telefone { get; set; }
public DateTime DtNasc { get; set; }
public string Rg { get; set; }
public string Cpf { get; set; }
public int IdUsuario { get; set; }
public int IdEndereco { get; set; }
public virtual Endereco IdEnderecoNavigation { get; set; }
public virtual Usuario IdUsuarioNavigation { get; set; }
public virtual ICollection<Consulta> Consulta { get; set; }
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Controllers/JogosController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senai.InLock.WebApi.Domains;
using Senai.InLock.WebApi.Interfaces;
using Senai.InLock.WebApi.Interfaces.Controller;
using Senai.InLock.WebApi.Repositories;
using System.Collections.Generic;
namespace Senai.InLock.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class JogosController : ControllerBase, IJogosController {
IJogosRepository _gameRepository { get; set; }
public JogosController() {
_gameRepository = new JogosRepository();
}
// http://localhost:5000/api/jogos
// http://localhost:5000/swagger/
/// <summary>
/// Lista todos jogos com seus respectivos estúdios.
/// </summary>
/// <returns>Retorna todos os jogos com seus estúdios.</returns>
[Authorize]
[HttpGet("gameStudio")]
public IActionResult GetGamesStudios() {
List<JogosDomain> listGames = _gameRepository.ListGamesStudios();
return Ok(listGames);
}
[HttpGet]
public IActionResult Get() {
throw new System.NotImplementedException();
}
[HttpGet("{id}")]
public IActionResult Get(int id) {
throw new System.NotImplementedException();
}
/// <summary>
/// Cadastra um novo jogo.
/// </summary>
/// <param name="newTEntity">Novo objeto.</param>
/// <returns>Retorna um novo jogo cadastrado e um status code 201.</returns>
[Authorize(Roles ="1")]
[HttpPost]
public IActionResult Post(JogosDomain newTEntity) {
_gameRepository.Register(newTEntity);
return StatusCode(201);
}
[HttpPut]
public IActionResult Put(JogosDomain newTEntity) {
throw new System.NotImplementedException();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
throw new System.NotImplementedException();
}
}
}
<file_sep>/1º Sprint-BD/exercicios/1.3 - pclinics/PcLinics_DQL.sql
USE PcLinics;
SELECT * FROM TipoPets;
SELECT * FROM Raca;
SELECT * FROM Dono;
SELECT * FROM Pets;
SELECT * FROM Clinica;
SELECT * FROM Veterinarios;
SELECT * FROM Atendimento;
SELECT C.razaoSocial AS [RAZÃO SOCIAL], V.nome AS [VETERINÁRIO], V.crmv AS [CRMV]
FROM Veterinarios AS V
INNER JOIN Clinica AS C
ON V.idClinica = C.idClinica;
SELECT nome AS [RAÇAS]
FROM Raca
WHERE nome LIKE 'S%';
SELECT nome AS [TIPOS DE PET]
FROM TipoPets
WHERE nome LIKE '%O';
SELECT R.nome AS [RAÇA], D.nome AS [DONO], P.nome AS [NOME DO PET]
FROM Pets AS P
LEFT JOIN Dono AS D
ON P.idDono = D.idDono
LEFT JOIN Raca AS R
ON P.idRaca = R.idRaca;
SELECT V.nome AS [VETERINÁRIO], P.nome AS [NOME DO PET], R.nome AS [RAÇA], TP.nome AS [TIPO DE RAÇA], D.nome AS [DONO], C.razaoSocial AS [Clinica]
FROM Atendimento AS A
INNER JOIN Veterinarios AS V ON A.idVeterinarios = V.idVeterinarios
INNER JOIN Clinica AS C ON V.idClinica = C.idClinica
INNER JOIN Pets AS P ON A.idPets = P.idPets
INNER JOIN Raca AS R ON P.idRaca = R.idRaca
INNER JOIN TipoPets AS TP ON R.idTipoPets = TP.idTipoPets
INNER JOIN Dono AS D ON P.idDono = D.idDono;<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/ClasseHabilidadeRepository.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class ClasseHabilidadeRepository : IClasseHabilidadeRepository {
HroadsContext ctx = new HroadsContext();
public void Delete(int id) {
ctx.ClasseHabilidades.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<ClasseHabilidade> ListAll() {
return ctx.ClasseHabilidades.Include(ch => ch.IdClasseNavigation).Include(ch => ch.IdHabilidadeNavigation).ToList();
}
public List<ClasseHabilidade> ListCorresponding() {
throw new System.NotImplementedException();
}
public List<ClasseHabilidade> ListNotCorresponding() {
throw new System.NotImplementedException();
}
public void Register(ClasseHabilidade newEntity) {
ctx.ClasseHabilidades.Add(newEntity);
ctx.SaveChanges();
}
public ClasseHabilidade SearchById(int id) {
return ctx.ClasseHabilidades.FirstOrDefault(ch => ch.IdClasseHabilidade == id);
}
public void Update(int id, ClasseHabilidade newEntity) {
ClasseHabilidade classSkillSought = SearchById(id);
if(classSkillSought != null) {
classSkillSought.IdClasse = newEntity.IdClasse;
classSkillSought.IdHabilidade = newEntity.IdHabilidade;
}
ctx.ClasseHabilidades.Update(classSkillSought);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Domains/UsuarioDomain.cs
namespace Senai.InLock.WebApi.Domains {
public class UsuarioDomain {
public int idUsuario { get; set; }
public string email { get; set; }
public string senha { get; set; }
public int idTipoUsuario { get; set; }
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Interfaces/Controller/Base/IStandardController.cs
using Microsoft.AspNetCore.Mvc;
namespace Senai.InLock.WebApi.Interfaces {
interface IStandardController<TEntity> {
IActionResult Get();
IActionResult Get(int id);
IActionResult Post(TEntity newTEntity);
IActionResult Put(TEntity newTEntity);
IActionResult Delete(int id);
}
}
<file_sep>/4º Sprint-Front_End/SP Medical Group/frontend/src/index.js
import React from "react";
import ReactDOM from "react-dom";
import {
Route,
BrowserRouter as Router,
Switch,
Redirect,
} from "react-router-dom";
import { parseJwt, usuarioAutenticado } from "./services/auth";
import "./index.css";
import App from "./App";
import NotFound from "./pages/notfound/NotFound";
import Login from "./pages/login/Login";
import Consulta from "./pages/consulta/Consulta";
import reportWebVitals from "./reportWebVitals";
const PermissaoAdm = ({ component: Component }) => (
<Route
render={(props) =>
usuarioAutenticado() && parseJwt().role === "1" ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
const PermissaoDoctor = ({ component: Component }) => (
<Route
render={(props) =>
usuarioAutenticado() && parseJwt().role === "2" ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
const PermissaoPatient = ({ component: Component }) => (
<Route
render={(props) =>
usuarioAutenticado() && parseJwt().role === "3" ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
const routing = (
<Router>
<div>
<Switch>
<Route exact path="/" component={App} />
<Route path="/login" component={Login} />
<Route path="/consulta" component={Consulta} />
<PermissaoAdm path="/consulta" component={Consulta} />
<PermissaoDoctor path="/consulta" component={Consulta} />
<PermissaoPatient path="/consulta" component={Consulta} />
<Route exact path="/notfound" component={NotFound} />
<Redirect to="/notfound" />
</Switch>
</div>
</Router>
);
ReactDOM.render(routing, document.getElementById("root"));
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Modeling/InLock_DML.sql
USE InLock_Games;
INSERT INTO Estudios(nome)
VALUES( 'Blizzard' ), ( 'Rockstar Studios' ), ( 'Square Enix' );
INSERT INTO Jogos(nome, descricao, dtLancamento, valor, idEstudio)
VALUES(
'<NAME>', 'É um jogo que contém bastante ação e é viciante, seja você um novato ou fã.', '15/05/2012', 99.00, 1
), (
'Red Dead Redemption II', 'Jogo eletrônico de ação-aventura western', '26/10/2018', 120.00, 2
);
INSERT INTO TipoUsuario(titulo)
VALUES( 'Administrador' ), ( 'Cliente' );
INSERT INTO Usuario(email, senha, idTipoUsuario)
VALUES(
'<EMAIL>', 'admin', 1
), (
'<EMAIL>', 'cliente', 2
);<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Repositories/UsuarioRepository.cs
using Senai.InLock.WebApi.Domains;
using Senai.InLock.WebApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace Senai.InLock.WebApi.Repositories {
public class UsuarioRepository : IUsuarioRepository {
const string connectionString = "Server=CELSO-PC;Database=InLock_Games;User Id=sa;Password=<PASSWORD>;";
public void Delete(int id) {
using(SqlConnection con = new SqlConnection(connectionString)) {
string queryDelete = "DELETE FROM Usuario WHERE idUsuario = @id";
using(SqlCommand cmd = new SqlCommand(queryDelete, con)) {
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
public List<UsuarioDomain> ListAll() {
List<UsuarioDomain> listUsers = new List<UsuarioDomain>();
using(SqlConnection con = new SqlConnection(connectionString)) {
string querySelectAll = "SELECT * FROM Usuario";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(querySelectAll, con)) {
sdr = cmd.ExecuteReader();
while(sdr.Read()) {
UsuarioDomain user = new UsuarioDomain() {
idUsuario = Convert.ToInt32(sdr[0]),
email = sdr[1].ToString(),
senha = sdr[2].ToString(),
idTipoUsuario = Convert.ToInt32(sdr[3])
};
listUsers.Add(user);
}
return listUsers;
}
}
}
public UsuarioDomain Login(string email, string password) {
// MVP
using(SqlConnection con = new SqlConnection(connectionString)) {
string queryLogin = "SELECT idUsuario, email, senha, idTipoUsuario FROM Usuario WHERE email = @email AND senha = @senha;";
using(SqlCommand cmd = new SqlCommand(queryLogin, con)) {
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@senha", password);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if(sdr.Read()) {
UsuarioDomain searchedUser = new UsuarioDomain() {
idUsuario = Convert.ToInt32(sdr["idUsuario"]),
email = sdr["email"].ToString(),
senha = sdr["senha"].ToString(),
idTipoUsuario = Convert.ToInt32(sdr["idTipoUsuario"])
};
return searchedUser;
}
return null;
}
}
}
public void Register(UsuarioDomain newTEntity) {
using(SqlConnection con = new SqlConnection(connectionString)) {
string queryInsert = "INSERT INTO Usuario(email, senha, idTipoUsuario) VALUES(@email, @senha, @idTipoUsuario)";
using(SqlCommand cmd = new SqlCommand(queryInsert, con)) {
cmd.Parameters.AddWithValue("@email", newTEntity.email);
cmd.Parameters.AddWithValue("@senha", newTEntity.senha);
cmd.Parameters.AddWithValue("@idTipoUsuario", newTEntity.idTipoUsuario);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
public UsuarioDomain SearchById(int id) {
using(SqlConnection con = new SqlConnection(connectionString)) {
string querySelectById = "SELECT * FROM Usuario WHERE idUsuario = @id";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(querySelectById, con)) {
cmd.Parameters.AddWithValue("@id", id);
sdr = cmd.ExecuteReader();
if(sdr.Read()) {
UsuarioDomain soughtUser = new UsuarioDomain() {
idUsuario = Convert.ToInt32(sdr["idUsuario"]),
email = sdr["email"].ToString(),
senha = sdr["senha"].ToString(),
idTipoUsuario = Convert.ToInt32(sdr["idTipoUsuario"])
};
return soughtUser;
}
return null;
}
}
}
public void Update(UsuarioDomain newTEntity) {
using(SqlConnection con = new SqlConnection(connectionString)) {
string queryUpdateBody = "UPDATE Usuario SET email = @email, senha = @senha, idTipoUsuario = @idTipoUsuario WHERE idUsuario = @id";
using(SqlCommand cmd = new SqlCommand(queryUpdateBody, con)) {
cmd.Parameters.AddWithValue("@id", newTEntity.idUsuario);
cmd.Parameters.AddWithValue("@email", newTEntity.email);
cmd.Parameters.AddWithValue("@senha", newTEntity.senha);
cmd.Parameters.AddWithValue("@idTipoUsuario", newTEntity.idTipoUsuario);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/LoginController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories;
using MedicalGroup.WebApi.Repositories;
using MedicalGroup.WebApi.ViewModel;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase {
IUsuarioRepository _userRepository { get; set; }
public LoginController() {
_userRepository = new UsuarioRepository();
}
/// <summary>
/// Valida o usuário
/// </summary>
/// <param name="login">Objeto login que contém o e-mail e a senha do usuário</param>
/// <returns>Retorna um token com as informações do usuário</returns>
[HttpPost]
public IActionResult PostLogin(LoginViewModel login) {
try {
Usuario soughtUser = _userRepository.Login(login.Email, login.Senha);
if(soughtUser == null)
return NotFound("E-mail ou senha inválidos.");
var claims = new[] {
// Armazena na Claim o e-mail do usuário autenticado
new Claim(JwtRegisteredClaimNames.Email, soughtUser.Email),
// Armazena na Claim o ID do usuário autenticado
new Claim(JwtRegisteredClaimNames.Jti, soughtUser.IdUsuario.ToString()),
// Armazena na Claim o tipo de usuário que foi autenticado (Administrador ou Comum)
new Claim(ClaimTypes.Role, soughtUser.IdTipoUsuario.ToString()),
// Armazena na Claim o tipo de usuário que foi autenticado (Administrador ou Comum) de forma personalizada
new Claim("role", soughtUser.IdTipoUsuario.ToString()),
};
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("sp_mg-chave-autenticacao"));
// Define as credenciais do token - Header
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// Gera o token
var token = new JwtSecurityToken(
issuer: "MedicalGroup.WebApi", // emissor do token
audience: "MedicalGroup.WebApi", // destinatário do token
claims: claims, // dados definidos acima
expires: DateTime.Now.AddMinutes(30), // tempo de expiração
signingCredentials: creds // credenciais do token
);
// Retorna Ok com o token
return Ok(new {
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/Peoples/Senai.Peoples/Senai.Peoples.WebApi/Controllers/FuncionarioController.cs
using Microsoft.AspNetCore.Mvc;
using Senai.Peoples.WebApi.Domains;
using Senai.Peoples.WebApi.Interfaces;
using Senai.Peoples.WebApi.Repositories;
using System;
using System.Collections.Generic;
namespace Senai.Peoples.WebApi.Controllers {
/// <summary>
/// Controller responsável pelos endpoints (URLs) referentes aos funcionários.
/// </summary>
[Produces("application/json")] // Define que o tipo de resposta da API será no formato JSON
[Route("api/[controller]")] // Define que a rota de uma requisição será no formato 'dominio/api/nomeController' Ex.: http://localhost:5000/api/funcionario
[ApiController] // Define que é um controlador de API
public class FuncionarioController : ControllerBase {
/// <summary>
/// Objeto '_employeeRepository' que irá receber todos os métodos definidos na interface IFuncionarioRepository
/// </summary>
IFuncionarioRepository _employeeRepository { get; set; }
/// <summary>
/// Instancia o objeto '_employeeRepository' para que haja a referência aos métodos no repositório
/// </summary>
public FuncionarioController() {
_employeeRepository = new FuncionarioRepository();
}
/// <summary>
/// Lista todos os funcionários.
/// </summary>
/// <returns>Uma lista de funcionários e um status code.</returns>
[HttpGet]
public ActionResult Get() {
List<Funcionario> listEmployee = _employeeRepository.Get();
return Ok(listEmployee);
}
/// <summary>
/// Busca um funcionário através do seu 'id'.
/// </summary>
/// <param name="id">O 'id' do funcionário que será buscado.</param>
/// <returns>Um funcionário buscado ou 'NotFound', caso nenhum funcionário seja encontrado.</returns>
[HttpGet("{id}")]
public ActionResult GetById(int id) {
Funcionario soughtEmployee = _employeeRepository.GetById(id);
if(soughtEmployee == null)
return NotFound("Nenhum funcionário foi encontrado.");
return Ok(soughtEmployee);
}
/// <summary>
/// Busca um funcionário através do seu 'nome'.
/// </summary>
/// <param name="nameEmployee">O 'nameEmployee' do funcionário que será buscado.</param>
/// <returns>Um funcionário buscado ou 'NotFound', caso nenhum funcionário seja encontrado.</returns>
[HttpGet("search/{nameEmployee}")]
public ActionResult GetByName(string nameEmployee) {
Funcionario soughtEmployee = _employeeRepository.GetByName(nameEmployee);
if(soughtEmployee == null)
return NotFound("Nenhum funcionário foi encontrado.");
return Ok(soughtEmployee);
}
/// <summary>
/// Lista todos os funcionários, exibindo o nome completo.
/// </summary>
/// <returns>A lista de funcionários com nome completo.</returns>
[HttpGet("fullName")]
public ActionResult FullName() {
List<Funcionario> listEmployee = _employeeRepository.GetFullName();
return Ok(listEmployee);
}
/// <summary>
/// Lista todos os funcionários em ordem crescente ou decrescente(ASC - ascending ou DESC - descending).
/// </summary>
/// <param name="order">O tipo de ordem que será buscado.</param>
/// <returns>A lista de funcionários na ordem escolhida.</returns>
[HttpGet("ordination/{order}")]
public ActionResult GetOrder(string order) {
List<Funcionario> listEmployee = _employeeRepository.GetOrdination(order);
if(order != "ASC" && order != "DESC") {
return BadRequest("Não é possível ordenar da maneira solicitada. Por favor, ordene por 'ASC' ou 'DESC'");
}
return Ok(listEmployee);
}
/// <summary>
/// Cadastra um novo funcionário.
/// </summary>
/// <param name="employee">Objeto 'employee' recebido na aquisição.</param>
/// <returns>Um status code 201 Created.E um novo funcionário cadastrado.</returns>
[HttpPost]
public ActionResult Post(Funcionario employee) {
_employeeRepository.Insert(employee);
return StatusCode(201);
}
/// <summary>
///
/// </summary>
/// <param name="employee"></param>
/// <returns></returns>
[HttpPut]
public ActionResult Put(Funcionario employee) {
Funcionario soughtEmployee = _employeeRepository.GetById(employee.idFuncionario);
if(soughtEmployee != null) {
try {
_employeeRepository.Update(employee);
return NoContent();
}
catch(Exception error) {
return BadRequest(error);
}
}
return NotFound(new {
message = "Funcionário não encontrado."
});
}
/// <summary>
/// Atualiza um funcionário existente passando o seu 'id' pelo corpo da requisição.
/// </summary>
/// <param name="id">O 'id' do funcionário que será atualizado.</param>
/// <param name="employee">Objeto 'employee' com as novas informações.</param>
/// <returns>O funcionário escolhido atualizado.</returns>
[HttpPut("{id}")]
public ActionResult PutId(int id, Funcionario employee) {
Funcionario soughtEmployee = _employeeRepository.GetById(id);
if(soughtEmployee == null) {
return NotFound(new {
message = "Funcionário não encontrado.",
error = true
});
}
try {
_employeeRepository.UpdateIdUrl(id, employee);
return NoContent();
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Deleta um funcionário existente.
/// </summary>
/// <param name="id">O 'id' do funcionário que será deletado.</param>
/// <returns>Um status code 204 - NoContent</returns>
[HttpDelete("{id}")]
public ActionResult Delete(int id) {
_employeeRepository.Delete(id);
return StatusCode(204);
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/Peoples/Senai.Peoples/Senai.Peoples.WebApi/Repositories/FuncionarioRepository.cs
using Senai.Peoples.WebApi.Domains;
using Senai.Peoples.WebApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace Senai.Peoples.WebApi.Repositories {
/// <summary>
/// Classe responsável pelo repositório dos funcionários.
/// </summary>
public class FuncionarioRepository : IFuncionarioRepository {
//MSSQLSERVER é a instância padrão, portanto, apenas forneça o nome do servidor sozinho na string de conexão.
const string stringConexao = "Server=CELSO-PC;Database=Peoples;User Id=sa;Password=<PASSWORD>;";
/// <summary>
/// Lista todos os funcionários.
/// </summary>
/// <returns>Uma lista de funcionários.</returns>
public List<Funcionario> Get() {
List<Funcionario> listEmployees = new List<Funcionario>();
using(SqlConnection con = new SqlConnection(stringConexao)) {
string querySelectAll = "SELECT * FROM Funcionario";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(querySelectAll, con)) {
sdr = cmd.ExecuteReader();
while(sdr.Read()) {
Funcionario employee = new Funcionario() {
idFuncionario = Convert.ToInt32(sdr[0]),
nome = sdr[1].ToString(),
sobrenome = sdr[2].ToString(),
dtNasc = Convert.ToDateTime(sdr[3])
};
listEmployees.Add(employee);
}
return listEmployees;
}
}
}
/// <summary>
/// Busca um funcionário através do seu id.
/// </summary>
/// <param name="id">O 'id' do funcionário que será buscado.</param>
/// <returns>O funcionário buscado ou null caso não seja encontrado.</returns>
public Funcionario GetById(int id) {
using(SqlConnection con = new SqlConnection(stringConexao)) {
string querySelectById = "SELECT idFuncionario, nome, sobrenome, dtNasc FROM Funcionario WHERE idFuncionario = @Id";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(querySelectById, con)) {
cmd.Parameters.AddWithValue("@Id", id);
sdr = cmd.ExecuteReader();
if(sdr.Read()) {
Funcionario soughtEmployee = new Funcionario() {
idFuncionario = Convert.ToInt32(sdr["idFuncionario"]),
nome = sdr["nome"].ToString(),
sobrenome = sdr["sobrenome"].ToString(),
dtNasc = Convert.ToDateTime(sdr["dtNasc"])
};
return soughtEmployee;
}
return null;
}
}
}
/// <summary>
/// Busca um funcionário através do seu nome.
/// </summary>
/// <param name="newEmployee">O 'nameEployee' do funcionário que será buscado.</param>
/// <returns>O funcionário buscado ou null caso não seja encontrado.</returns>
public Funcionario GetByName(string nameEmployee) {
using(SqlConnection con = new SqlConnection(stringConexao)) {
string querySelectById = "SELECT idFuncionario, nome, sobrenome, dtNasc FROM Funcionario WHERE nome = @NOME";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(querySelectById, con)) {
cmd.Parameters.AddWithValue("@NOME", nameEmployee);
sdr = cmd.ExecuteReader();
/*DateTime dt = DateTime.ParseExact(sdr["dtNasc"].ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);*/
if(sdr.Read()) {
Funcionario soughtEmployee = new Funcionario() {
idFuncionario = Convert.ToInt32(sdr["idFuncionario"]),
nome = sdr["nome"].ToString(),
sobrenome = sdr["sobrenome"].ToString(),
dtNasc = Convert.ToDateTime(sdr["dtNasc"])
};
return soughtEmployee;
}
return null;
}
}
}
/// <summary>
/// Lista todos os funcionários, exibindo o nome completo.
/// </summary>
/// <returns>A lista de funcionários com nome completo.</returns>
public List<Funcionario> GetFullName() {
List<Funcionario> listEmployees = new List<Funcionario>();
using(SqlConnection con = new SqlConnection(stringConexao)) {
string queryFullName = "SELECT CONCAT(nome, ' ', sobrenome) AS [Nome Completo] FROM Funcionario";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(queryFullName, con)) {
sdr = cmd.ExecuteReader();
while(sdr.Read()) {
Funcionario soughtEmployee = new Funcionario() {
//idFuncionario = Convert.ToInt32(sdr["idFuncionario"]),
nome = sdr[0].ToString(),
//nome = sdr["nome"].ToString() + ' ' + sdr["sobrenome"].ToString()
//dtNasc = Convert.ToDateTime(sdr["dtNasc"])
};
listEmployees.Add(soughtEmployee);
}
return listEmployees;
}
}
}
/// <summary>
/// Lista todos os funcionários em ordem crescente ou decrescente(ASC - ascending ou DESC - descending).
/// </summary>
/// <param name="order">O tipo de ordem que será buscado.</param>
/// <returns>A lista de funcionários na ordem escolhida.</returns>
public List<Funcionario> GetOrdination(string order) {
List<Funcionario> listEmployees = new List<Funcionario>();
using(SqlConnection con = new SqlConnection(stringConexao)) {
string queryOrder = $"SELECT nome, sobrenome FROM Funcionario ORDER BY nome {order}";
con.Open();
SqlDataReader sdr;
using(SqlCommand cmd = new SqlCommand(queryOrder, con)) {
sdr = cmd.ExecuteReader();
while(sdr.Read()) {
Funcionario soughtEmployee = new Funcionario() {
nome = sdr["nome"].ToString(),
sobrenome = sdr["sobrenome"].ToString()
};
listEmployees.Add(soughtEmployee);
}
return listEmployees;
}
}
}
/// <summary>
/// Efetua um cadastro de um funcionário.
/// </summary>
/// <param name="newEmployee">Objeto 'newEmployee' com as informações que serão cadastradas.</param>
public void Insert(Funcionario newEmployee) {
using(SqlConnection con = new SqlConnection(stringConexao)) {
string queryInsert = "INSERT INTO Funcionario(nome, sobrenome, dtNasc) VALUES(@Nome, @Sobrenome, @DtNasc)";
using(SqlCommand cmd = new SqlCommand(queryInsert, con)) {
cmd.Parameters.AddWithValue("@Nome", newEmployee.nome);
cmd.Parameters.AddWithValue("@Sobrenome", newEmployee.sobrenome);
cmd.Parameters.AddWithValue("@DtNasc", newEmployee.dtNasc);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// Atualiza um funcionário passando as dados pelo corpo.
/// </summary>
/// <param name="employee">Objeto 'employee' com as novas informações.</param>
public void Update(Funcionario employee) {
using(SqlConnection con = new SqlConnection(stringConexao)) {
string queryUpdateBody = "UPDATE Funcionario SET nome = @Nome, sobrenome = @Sobrenome, dtNasc = @DtNasc WHERE idFuncionario = @Id";
using(SqlCommand cmd = new SqlCommand(queryUpdateBody, con)) {
cmd.Parameters.AddWithValue("@Id", employee.idFuncionario);
cmd.Parameters.AddWithValue("@Nome", employee.nome);
cmd.Parameters.AddWithValue("@Sobrenome", employee.sobrenome);
cmd.Parameters.AddWithValue("@DtNasc", employee.dtNasc);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// Atualiza um funcionário passando o 'id' pelo recurso (URL)
/// </summary>
/// <param name="id">Objeto 'id' do funcionário que será atualizado.</param>
/// <param name="employee">Objeto 'employee' com as novas informações.</param>
public void UpdateIdUrl(int id, Funcionario employee) {
using(SqlConnection con = new SqlConnection(stringConexao)) {
string queryUpdateIdUrl = "UPDATE Funcionario SET nome = @Nome, sobrenome = @Sobrenome, dtNasc = @DtNasc WHERE idFuncionario = @Id";
using(SqlCommand cmd = new SqlCommand(queryUpdateIdUrl, con)) {
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@Nome", employee.nome);
cmd.Parameters.AddWithValue("@Sobrenome", employee.sobrenome);
cmd.Parameters.AddWithValue("@DtNasc", employee.dtNasc);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// Deleta um funcionário atráves do seu 'id'.
/// </summary>
/// <param name="id">Objeto 'id' do funcionário que será excluído.</param>
public void Delete(int id) {
using(SqlConnection con = new SqlConnection(stringConexao)) {
string queryDelete = "DELETE FROM Funcionario WHERE idFuncionario = @Id";
using(SqlCommand cmd = new SqlCommand(queryDelete, con)) {
cmd.Parameters.AddWithValue("@Id", id);
con.Open();
cmd.ExecuteNonQuery();
}
}
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/Modeling/Scripts/SP_MedGroup_DQL.sql
USE SP_MedicalGroup;
SELECT *
FROM dbo.Endereco;
SELECT *
FROM dbo.Paciente;
SELECT *
FROM dbo.Clinica;
SELECT *
FROM dbo.Especialidade;
SELECT *
FROM dbo.Medico;
SELECT *
FROM dbo.Situacao;
SELECT *
FROM dbo.Consulta;
SELECT *
FROM dbo.TipoUsuario;
SELECT *
FROM dbo.Usuario;
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Controllers/UsuarioController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Senai.InLock.WebApi.Domains;
using Senai.InLock.WebApi.Interfaces;
using Senai.InLock.WebApi.Interfaces.Controller;
using Senai.InLock.WebApi.Repositories;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace Senai.InLock.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")] // http://localhost:5000/api/usuario
[ApiController]
public class UsuarioController : ControllerBase, IUsuarioController {
IUsuarioRepository _userRepository { get; set; }
public UsuarioController() {
_userRepository = new UsuarioRepository();
}
[HttpPost("login")]
public IActionResult Login(UsuarioDomain login) {
UsuarioDomain searchedUser = _userRepository.Login(login.email, login.senha); // Busca o usuário pelo e-mail e senha.
// Caso não encontre nenhum usuário com o e-mail e senha informados.
if(searchedUser == null)
return NotFound("E-mail ou senha inválidos."); // Retorna 'NotFound' com uma mensagem personalizada.
// Define os dados que serão fornecidos no token - Payload.
var claims = new[] {
// Formato da Claim = TipoDaClaim, ValorDaClaim.
new Claim(JwtRegisteredClaimNames.Email, searchedUser.email),
new Claim(JwtRegisteredClaimNames.Jti, searchedUser.idUsuario.ToString()),
new Claim(ClaimTypes.Role, searchedUser.idTipoUsuario.ToString()),
new Claim("Claim personalizada", "Valor teste")
};
// Define a chave de acesso ao token.
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("inlock-chave-autenticacao"));
// Define as credenciais do token - Header.
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// Gerar o token.
var token = new JwtSecurityToken(
issuer: "InLock.webApi", // Emissor do token.
audience: "InLock.webApi", // Destinatário do token.
claims: claims, // Dados definidos acima.
expires: DateTime.Now.AddMinutes(30), // Tempo de expiração.
signingCredentials: creds // Credenciais do token.
);
return Ok(new {
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
[HttpGet]
public IActionResult Get() {
throw new System.NotImplementedException();
}
[HttpGet("{id}")]
public IActionResult Get(int id) {
throw new System.NotImplementedException();
}
[HttpPost]
public IActionResult Post(UsuarioDomain newTEntity) {
throw new System.NotImplementedException();
}
[HttpPut]
public IActionResult Put(UsuarioDomain newTEntity) {
throw new System.NotImplementedException();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
throw new System.NotImplementedException();
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Contexts/MedicalGroupContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using MedicalGroup.WebApi.Domains;
#nullable disable
namespace MedicalGroup.WebApi.Contexts {
public partial class MedicalGroupContext : DbContext {
public MedicalGroupContext() {
}
public MedicalGroupContext(DbContextOptions<MedicalGroupContext> options)
: base(options) {
}
public virtual DbSet<Clinica> Clinicas { get; set; }
public virtual DbSet<Consulta> Consulta { get; set; }
public virtual DbSet<Endereco> Enderecos { get; set; }
public virtual DbSet<Especialidade> Especialidades { get; set; }
public virtual DbSet<Medico> Medicos { get; set; }
public virtual DbSet<Paciente> Pacientes { get; set; }
public virtual DbSet<Situacao> Situacaos { get; set; }
public virtual DbSet<TipoUsuario> TipoUsuarios { get; set; }
public virtual DbSet<Usuario> Usuarios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
if(!optionsBuilder.IsConfigured) {
optionsBuilder.UseSqlServer("Data Source=USER; initial catalog=SP_MedicalGroup; user Id=sa; pwd=<PASSWORD>;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasAnnotation("Relational:Collation", "Latin1_General_CI_AS");
modelBuilder.Entity<Clinica>(entity => {
entity.HasKey(e => e.IdClinica);
entity.ToTable("Clinica");
entity.HasIndex(e => e.Cnpj, "UQ_Clinica")
.IsUnique();
entity.Property(e => e.IdClinica).HasColumnName("idClinica");
entity.Property(e => e.Cnpj)
.IsRequired()
.HasMaxLength(14)
.IsUnicode(false)
.HasColumnName("cnpj")
.IsFixedLength(true);
entity.Property(e => e.HoraFuncionamento)
.IsRequired()
.HasMaxLength(11)
.IsUnicode(false)
.HasColumnName("horaFuncionamento");
entity.Property(e => e.IdEndereco).HasColumnName("idEndereco");
entity.Property(e => e.NomeFantasia)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("nomeFantasia");
entity.Property(e => e.RazaoSocial)
.IsRequired()
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("razaoSocial");
entity.HasOne(d => d.IdEnderecoNavigation)
.WithMany(p => p.Clinicas)
.HasForeignKey(d => d.IdEndereco)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Endereco_Clinica");
});
modelBuilder.Entity<Consulta>(entity => {
entity.HasKey(e => e.IdConsulta);
entity.Property(e => e.IdConsulta).HasColumnName("idConsulta");
entity.Property(e => e.Descricao)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnName("descricao");
entity.Property(e => e.DtAgendamento)
.HasColumnType("datetime")
.HasColumnName("dtAgendamento");
entity.Property(e => e.IdMedico).HasColumnName("idMedico");
entity.Property(e => e.IdPaciente).HasColumnName("idPaciente");
entity.Property(e => e.IdSituacao).HasColumnName("idSituacao");
entity.HasOne(d => d.IdMedicoNavigation)
.WithMany(p => p.Consulta)
.HasForeignKey(d => d.IdMedico)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Medico_Consulta");
entity.HasOne(d => d.IdPacienteNavigation)
.WithMany(p => p.Consulta)
.HasForeignKey(d => d.IdPaciente)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Paciente_Consulta");
entity.HasOne(d => d.IdSituacaoNavigation)
.WithMany(p => p.Consulta)
.HasForeignKey(d => d.IdSituacao)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Situacao_Consulta");
});
modelBuilder.Entity<Endereco>(entity => {
entity.HasKey(e => e.IdEndereco);
entity.ToTable("Endereco");
entity.Property(e => e.IdEndereco).HasColumnName("idEndereco");
entity.Property(e => e.Bairro)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("bairro");
entity.Property(e => e.Cep)
.IsRequired()
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("cep")
.IsFixedLength(true);
entity.Property(e => e.Cidade)
.IsRequired()
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("cidade");
entity.Property(e => e.Estado)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("estado");
entity.Property(e => e.Logradouro)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("logradouro");
entity.Property(e => e.Numero)
.IsRequired()
.HasMaxLength(4)
.IsUnicode(false)
.HasColumnName("numero");
});
modelBuilder.Entity<Especialidade>(entity => {
entity.HasKey(e => e.IdEspecialidade);
entity.ToTable("Especialidade");
entity.HasIndex(e => e.Nome, "UQ_Especialidade")
.IsUnique();
entity.Property(e => e.IdEspecialidade).HasColumnName("idEspecialidade");
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("nome");
});
modelBuilder.Entity<Medico>(entity => {
entity.HasKey(e => e.IdMedico);
entity.ToTable("Medico");
entity.HasIndex(e => e.Crm, "UQ_Medico")
.IsUnique();
entity.Property(e => e.IdMedico).HasColumnName("idMedico");
entity.Property(e => e.Crm)
.IsRequired()
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnName("crm")
.IsFixedLength(true);
entity.Property(e => e.IdClinica).HasColumnName("idClinica");
entity.Property(e => e.IdEspecialidade).HasColumnName("idEspecialidade");
entity.Property(e => e.IdUsuario).HasColumnName("idUsuario");
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("nome");
entity.HasOne(d => d.IdClinicaNavigation)
.WithMany(p => p.Medicos)
.HasForeignKey(d => d.IdClinica)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Clinica_Medico");
entity.HasOne(d => d.IdEspecialidadeNavigation)
.WithMany(p => p.Medicos)
.HasForeignKey(d => d.IdEspecialidade)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Especialidade_Medico");
entity.HasOne(d => d.IdUsuarioNavigation)
.WithMany(p => p.Medicos)
.HasForeignKey(d => d.IdUsuario)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Usuario_Medico");
});
modelBuilder.Entity<Paciente>(entity => {
entity.HasKey(e => e.IdPaciente);
entity.ToTable("Paciente");
entity.HasIndex(e => new { e.Telefone, e.Rg, e.Cpf }, "UQ_Paciente")
.IsUnique();
entity.Property(e => e.IdPaciente).HasColumnName("idPaciente");
entity.Property(e => e.Cpf)
.IsRequired()
.HasMaxLength(11)
.IsUnicode(false)
.HasColumnName("cpf");
entity.Property(e => e.DtNasc)
.HasColumnType("date")
.HasColumnName("dtNasc");
entity.Property(e => e.IdEndereco).HasColumnName("idEndereco");
entity.Property(e => e.IdUsuario).HasColumnName("idUsuario");
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(35)
.IsUnicode(false)
.HasColumnName("nome");
entity.Property(e => e.Rg)
.IsRequired()
.HasMaxLength(9)
.IsUnicode(false)
.HasColumnName("rg");
entity.Property(e => e.Telefone)
.IsRequired()
.HasMaxLength(11)
.IsUnicode(false)
.HasColumnName("telefone");
entity.HasOne(d => d.IdEnderecoNavigation)
.WithMany(p => p.Pacientes)
.HasForeignKey(d => d.IdEndereco)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Endereco_Paciente");
entity.HasOne(d => d.IdUsuarioNavigation)
.WithMany(p => p.Pacientes)
.HasForeignKey(d => d.IdUsuario)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Usuario_Paciente");
});
modelBuilder.Entity<Situacao>(entity => {
entity.HasKey(e => e.IdSituacao);
entity.ToTable("Situacao");
entity.HasIndex(e => e.Tipo, "UQ_Situacao")
.IsUnique();
entity.Property(e => e.IdSituacao).HasColumnName("idSituacao");
entity.Property(e => e.Tipo)
.IsRequired()
.HasMaxLength(30)
.IsUnicode(false)
.HasColumnName("tipo");
});
modelBuilder.Entity<TipoUsuario>(entity => {
entity.HasKey(e => e.IdTipoUsuario);
entity.ToTable("TipoUsuario");
entity.HasIndex(e => e.Perfil, "UQ_TipoUsuario")
.IsUnique();
entity.Property(e => e.IdTipoUsuario).HasColumnName("idTipoUsuario");
entity.Property(e => e.Perfil)
.IsRequired()
.HasMaxLength(14)
.IsUnicode(false)
.HasColumnName("perfil");
});
modelBuilder.Entity<Usuario>(entity => {
entity.HasKey(e => e.IdUsuario);
entity.ToTable("Usuario");
entity.HasIndex(e => e.Email, "UQ_Usuario")
.IsUnique();
entity.Property(e => e.IdUsuario).HasColumnName("idUsuario");
entity.Property(e => e.Email)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("email");
entity.Property(e => e.IdTipoUsuario).HasColumnName("idTipoUsuario");
entity.Property(e => e.Senha)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false)
.HasColumnName("senha");
entity.HasOne(d => d.IdTipoUsuarioNavigation)
.WithMany(p => p.Usuarios)
.HasForeignKey(d => d.IdTipoUsuario)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_TipoUsuario_Usuario");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Interfaces/Controllers/Base/IStandardController.cs
using Microsoft.AspNetCore.Mvc;
namespace MedicalGroup.WebApi.Interfaces.Controllers.Base {
interface IStandardController<TEntity> {
IActionResult Get();
IActionResult Get(int id);
IActionResult Post(TEntity newEntity);
IActionResult Put(int id, TEntity newEntity);
IActionResult Delete(int id);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Controllers/HabilidadeController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using Senai.Hroads.WebApi.Repositories;
namespace Senai.Hroads.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class HabilidadeController : ControllerBase, IHabilidadeController {
IHabilidadeRepository _skillRepository { get; set; }
public HabilidadeController() {
_skillRepository = new HabilidadeRepository();
}
/// <summary>
/// Lista a quantidade de habilidades.
/// </summary>
/// <returns>Retorna um objeto JSON, com a quantidade de habilidades.</returns>
[HttpGet("amount-skills")]
public IActionResult GetAmountSkills() {
throw new System.NotImplementedException();
}
/// <summary>
/// Lista as habilidades, de forma ascendente pelo Id.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de habilidades ordenada de forma ascendente.</returns>
[HttpGet("order/byId/asc")]
public IActionResult GetAscendingOrderById() {
throw new System.NotImplementedException();
}
/// <summary>
/// Lista as habilidades e os tipos das habilidades.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de habilidades e tipos de habilidades.</returns>
[HttpGet("skill&types")]
public IActionResult GetSkillsAndTypes() {
throw new System.NotImplementedException();
}
/// <summary>
/// Lista todas as habilidades.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de classes.</returns>
[HttpGet]
public IActionResult Get() {
return Ok(_skillRepository.ListAll());
}
/// <summary>
/// Busca apenas uma habilidade.
/// </summary>
/// <param name="id">O id da habilidade que será buscada.</param>
/// <returns>Retorna um objeto JSON, da classe buscada.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
return Ok(_skillRepository.SearchById(id));
}
/// <summary>
/// Cadastra uma nova habilidade.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(Habilidade newEntity) {
_skillRepository.Register(newEntity);
return StatusCode(201);
}
/// <summary>
/// Atualiza uma habilidade.
/// </summary>
/// <param name="id">O id da habilidade escolhida a ser atualizada.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Habilidade newEntity) {
_skillRepository.Update(id, newEntity);
return StatusCode(204);
}
/// <summary>
/// Deleta uma habilidade.
/// </summary>
/// <param name="id">O id da habilidade que será deletada.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
_skillRepository.Delete(id);
return StatusCode(204);
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Domains/EstudiosDomain.cs
namespace Senai.InLock.WebApi.Domains {
public class EstudiosDomain {
public int idEstudio { get; set; }
public string nome { get; set; }
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Interfaces/Repositories/IUsuarioRepository.cs
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
namespace MedicalGroup.WebApi.Interfaces.Repositories {
interface IUsuarioRepository : IStantardRepository<Usuario> {
Usuario Login(string email, string password);
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Repositories/MedicoRepository.cs
using MedicalGroup.WebApi.Contexts;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MedicalGroup.WebApi.Repositories {
public class MedicoRepository : IStantardRepository<Medico> {
MedicalGroupContext ctx = new MedicalGroupContext();
public void Delete(int id) {
ctx.Medicos.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Medico> ListAll() {
return ctx.Medicos.ToList();
}
public void Register(Medico newEntity) {
ctx.Medicos.Add(newEntity);
ctx.SaveChanges();
}
public Medico SearchById(int id) {
return ctx.Medicos.FirstOrDefault(m => m.IdMedico == id);
}
public void Update(int id, Medico newEntity) {
Medico doctorSought = ctx.Medicos.Find(id);
if(doctorSought != null) {
// UNDONE: doctorSought != null
}
ctx.Medicos.Update(doctorSought);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Controllers/TipoUsuarioController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller.Base;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using Senai.Hroads.WebApi.Repositories;
namespace Senai.Hroads.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class TipoUsuarioController : ControllerBase, IStandardController<TipoUsuario> {
IStandardRepository<TipoUsuario> _typeUserRepository { get; set; }
public TipoUsuarioController() {
_typeUserRepository = new TipoUsuarioRepository();
}
/// <summary>
/// Lista todos os tipos de usuário.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de tipos de usuário.</returns>
[Authorize]
[HttpGet]
public IActionResult Get() {
return Ok(_typeUserRepository.ListAll());
}
/// <summary>
/// Busca apenas um tipo de usuário.
/// </summary>
/// <param name="id">O id do tipo de usuário que será buscado.</param>
/// <returns>Retorna um objeto JSON, do tipo de usuário buscado.</returns>
[Authorize]
[HttpGet("{id}")]
public IActionResult Get(int id) {
return Ok(_typeUserRepository.SearchById(id));
}
/// <summary>
/// Cadastra um novo tipo de usuário.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(TipoUsuario newEntity) {
_typeUserRepository.Register(newEntity);
return StatusCode(201);
}
/// <summary>
/// Atualiza um tipo de usuário.
/// </summary>
/// <param name="id">O id do tipo de usuário escolhido a ser atualizado.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[Authorize]
[HttpPut("{id}")]
public IActionResult Put(int id, TipoUsuario newEntity) {
_typeUserRepository.Update(id, newEntity);
return StatusCode(204);
}
/// <summary>
/// Deleta um tipo de usuário.
/// </summary>
/// <param name="id">O id do tipo de usuário que será deletado.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[Authorize]
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
_typeUserRepository.Delete(id);
return StatusCode(204);
}
}
}
<file_sep>/1º Sprint-BD/desafios/HROADS/Modeling Scripts/Hroads_DML.sql
USE Senai_Hroads_Manha;
INSERT INTO dbo.TipoHabilidade(tipo)
VALUES ('Ataque'),
('Defesa'),
('Cura'),
('Magia');
INSERT INTO dbo.Habilidade(nome, idTipoHabilidade)
VALUES ('Lança Mortal', 1),
('Escudo Supremo', 2),
('Recuperar Vida', 3);
INSERT INTO dbo.Classe(nome)
VALUES ('Bárbaro'),
('Cruzado'),
('Caçadora de Demônios'),
('Monge'),
('Necromante'),
('Feiticeiro'),
('Arcantista');
INSERT INTO dbo.Classe_Habilidade(idClasse, idHabilidade)
VALUES (1, 1),
(1, 2),
(2, 2),
(3, 1),
(4, 3),
(4, 2),
(6, 3);
INSERT INTO dbo.Personagem(nome, idClasse, vida, mana, dtAtualizacao, dtCricao)
VALUES ('DeuBug', 1, 100, 80, '26/04/2021', '18/01/2019'),
('BitBug', 4, 70, 100, '26/04/2021', '17/03/2016'),
('Fer8', 7, 75, 60, '26/04/2021', '18/03/2018');<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/ClinicaController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Controllers.Base;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using MedicalGroup.WebApi.Repositories;
using System;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ClinicaController : ControllerBase, IStandardController<Clinica> {
IStantardRepository<Clinica> _clinicRepository { get; set; }
public ClinicaController() {
_clinicRepository = new ClinicaRepository();
}
/// <summary>
/// Deleta uma clinica.
/// </summary>
/// <param name="id">O id da clinica que será deletada.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
try {
_clinicRepository.Delete(id);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Lista todos as clinicas.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de clinicas.</returns>
[Authorize(Roles = "1")]
[HttpGet]
public IActionResult Get() {
try {
return Ok(_clinicRepository.ListAll());
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Busca apenas uma clinica.
/// </summary>
/// <param name="id">O id da clinica que será buscada.</param>
/// <returns>Retorna um objeto JSON, da clinica buscada.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
try {
return Ok(_clinicRepository.SearchById(id));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Cadastra uma nova clinica.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(Clinica newEntity) {
try {
_clinicRepository.Register(newEntity);
return StatusCode(201);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Atualiza uma clinica.
/// </summary>
/// <param name="id">O id da clinica escolhida a ser atualizada.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Clinica newEntity) {
try {
_clinicRepository.Update(id, newEntity);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/PacienteController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Controllers.Base;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using MedicalGroup.WebApi.Repositories;
using System;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class PacienteController : ControllerBase, IStandardController<Paciente> {
IStantardRepository<Paciente> _patientRepository { get; set; }
public PacienteController() {
_patientRepository = new PacienteRepository();
}
/// <summary>
/// Deleta um paciente.
/// </summary>
/// <param name="id">O id do paciente que será deletado.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
try {
_patientRepository.Delete(id);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Lista todos os pacientes.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de pacientes.</returns>
[HttpGet]
public IActionResult Get() {
try {
return Ok(_patientRepository.ListAll());
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Busca apenas um paciente.
/// </summary>
/// <param name="id">O id do paciente que será buscado.</param>
/// <returns>Retorna um objeto JSON, do paciente buscado.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
try {
return Ok(_patientRepository.SearchById(id));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Cadastra um novo paciente.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(Paciente newEntity) {
try {
_patientRepository.Register(newEntity);
return StatusCode(201);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Atualiza um paciente.
/// </summary>
/// <param name="id">O id do paciente escolhido a ser atualizado.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Paciente newEntity) {
try {
_patientRepository.Update(id, newEntity);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/EnderecoController.cs
using Microsoft.AspNetCore.Mvc;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Controllers.Base;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using MedicalGroup.WebApi.Repositories;
using System;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class EnderecoController : ControllerBase, IStandardController<Endereco> {
IStantardRepository<Endereco> _addressRepository { get; set; }
public EnderecoController() {
_addressRepository = new EnderecoRepository();
}
/// <summary>
/// Deleta um endereço.
/// </summary>
/// <param name="id">O id do endereço que será deletado.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
try {
_addressRepository.Delete(id);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Lista todos os endereços.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de endereços.</returns>
[HttpGet]
public IActionResult Get() {
try {
return Ok(_addressRepository.ListAll());
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Busca apenas um endereço.
/// </summary>
/// <param name="id">O id do endereço que será buscado.</param>
/// <returns>Retorna um objeto JSON, do endereço buscado.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
try {
return Ok(_addressRepository.SearchById(id));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Cadastra um novo endereço.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[HttpPost]
public IActionResult Post(Endereco newEntity) {
try {
_addressRepository.Register(newEntity);
return StatusCode(201);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Atualiza um endereço.
/// </summary>
/// <param name="id">O id do endereço escolhido a ser atualizado.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Endereco newEntity) {
try {
_addressRepository.Update(id, newEntity);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Controllers/ClasseHabilidadeController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using Senai.Hroads.WebApi.Repositories;
namespace Senai.Hroads.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ClasseHabilidadeController : ControllerBase, IClasseHabilidadeController {
IClasseHabilidadeRepository _classSkillRepository { get; set; }
public ClasseHabilidadeController() {
_classSkillRepository = new ClasseHabilidadeRepository();
}
/// <summary>
/// Lista todas as classes e habilidades, que sejam correspondentes.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de classes e habilidades.</returns>
[HttpGet("corresponding")]
public IActionResult GetCorresponding() {
throw new System.NotImplementedException();
}
/// <summary>
/// Lista todas as classes e habilidades, que não sejam correspondentes.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de classes e habilidades.</returns>
[HttpGet("not-corresponding")]
public IActionResult GetNotCorresponding() {
throw new System.NotImplementedException();
}
/// <summary>
/// Lista todas as classes e habilidades.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de classes e habilidades.</returns>
[HttpGet]
public IActionResult Get() {
return Ok(_classSkillRepository.ListAll());
}
/// <summary>
/// Busca um registro(classe e habilidade).
/// </summary>
/// <param name="id">O id da classe e habilidade a ser buscado.</param>
/// <returns>Retorna um objeto JSON, da classe buscada.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
return Ok(_classSkillRepository.SearchById(id));
}
/// <summary>
/// Cadastra um registro(classe e habilidade).
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(ClasseHabilidade newEntity) {
_classSkillRepository.Register(newEntity);
return StatusCode(201);
}
/// <summary>
/// Atualiza um registro(classe e habilidade).
/// </summary>
/// <param name="id">O id registro escolhido a ser atualizada.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, ClasseHabilidade newEntity) {
_classSkillRepository.Update(id, newEntity);
return StatusCode(204);
}
/// <summary>
/// Deleta um registro(classe e habilidade).
/// </summary>
/// <param name="id"></param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
_classSkillRepository.Delete(id);
return StatusCode(204);
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/PersonagemRepository.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class PersonagemRepository : IPersonagemRepository {
HroadsContext ctx = new HroadsContext();
public void Delete(int id) {
//Personagem soughtCharacter = ctx.Personagems.Find(id);
ctx.Personagems.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Personagem> ListAll() {
return ctx.Personagems.Include(p => p.IdClasseNavigation).ToList();
}
public List<Personagem> ListCorresponding() {
throw new System.NotImplementedException();
}
public List<Personagem> ListNotCorresponding() {
throw new System.NotImplementedException();
}
public void Register(Personagem newEntity) {
ctx.Personagems.Add(newEntity);
ctx.SaveChanges();
}
public Personagem SearchById(int id) {
return ctx.Personagems.FirstOrDefault(p => p.IdPersonagem == id);
}
public void Update(int id, Personagem newEntity) {
//Personagem soughtCharacter = ctx.Personagems.Find(id);
Personagem soughtCharacter = SearchById(id);
if(soughtCharacter != null) {
soughtCharacter.Nome = newEntity.Nome;
soughtCharacter.IdClasse = newEntity.IdClasse;
soughtCharacter.Vida = newEntity.Vida;
soughtCharacter.Mana = newEntity.Mana;
soughtCharacter.DtAtualizacao = newEntity.DtAtualizacao;
soughtCharacter.DtCricao = newEntity.DtCricao;
}
ctx.Personagems.Update(soughtCharacter);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Repositories/IHabilidadeRepository.cs
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
namespace Senai.Hroads.WebApi.Interfaces.Repositories {
interface IHabilidadeRepository : IStandardRepository<Habilidade> {
Habilidade AmountSkills();
List<Habilidade> AscendingOrderById();
List<Habilidade> ListSkillsAndTypes();
}
}
<file_sep>/2º Sprint-Back_End/exercicios/Peoples/Modeling Scripts/people_DML.sql
USE Peoples;
INSERT INTO Funcionario (nome, sobrenome, dtNasc)
VALUES (
'Catarina', 'Strada', '11/08/1990'
), (
'Tadeu', 'Vitelli', '08/03/1991'
);<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Repositories/Base/IStandardRepository.cs
using System.Collections.Generic;
namespace Senai.Hroads.WebApi.Interfaces.Repositories.Base {
interface IStandardRepository<TEntity> {
List<TEntity> ListAll();
TEntity SearchById(int id);
void Register(TEntity newEntity);
void Update(int id, TEntity newEntity);
void Delete(int id);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Controllers/PersonagemController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using Senai.Hroads.WebApi.Repositories;
using System;
namespace Senai.Hroads.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class PersonagemController : ControllerBase, IPersonagemController {
IPersonagemRepository _characterRepository { get; set; }
public PersonagemController() {
_characterRepository = new PersonagemRepository();
}
/// <summary>
/// Lista todos os personagens, que sejam correspondentes.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de personagens.</returns>
[Authorize]
[HttpGet("corresponding")]
public IActionResult GetCorresponding() {
throw new NotImplementedException();
}
/// <summary>
/// Lista todos os personagens, que não sejam correspondentes.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de personagens.</returns>
[Authorize]
[HttpGet("not-corresponding")]
public IActionResult GetNotCorresponding() {
throw new NotImplementedException();
}
/// <summary>
/// Lista todos os personagens.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de personagens.</returns>
[Authorize]
[HttpGet]
public IActionResult Get() {
return Ok(_characterRepository.ListAll());
}
/// <summary>
/// Busca apenas um personagem.
/// </summary>
/// <param name="id">O id do personagem que será buscado.</param>
/// <returns>Retorna um objeto JSON, da classe buscada.</returns>
[Authorize]
[HttpGet("{id}")]
public IActionResult Get(int id) {
return Ok(_characterRepository.SearchById(id));
}
/// <summary>
/// Cadastra uma novo habilidade.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "2")]
[HttpPost]
public IActionResult Post(Personagem newEntity) {
_characterRepository.Register(newEntity);
return StatusCode(201);
}
/// <summary>
/// Atualiza um personagem.
/// </summary>
/// <param name="id">O id do personagem escolhida a ser atualizada.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[Authorize]
[HttpPut("{id}")]
public IActionResult Put(int id, Personagem newEntity) {
_characterRepository.Update(id, newEntity);
return StatusCode(204);
}
/// <summary>
/// Deleta um personagem.
/// </summary>
/// <param name="id">O id do personagem que será deletado.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[Authorize]
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
_characterRepository.Delete(id);
return StatusCode(204);
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Domains/TipoUsuario.cs
namespace Senai.InLock.WebApi.Domains {
public class TipoUsuario {
public int idTipoUsuario { get; set; }
public string titulo { get; set; }
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Interfaces/Controller/IUsuarioController.cs
using Microsoft.AspNetCore.Mvc;
using Senai.InLock.WebApi.Domains;
namespace Senai.InLock.WebApi.Interfaces.Controller {
interface IUsuarioController : IStandardController<UsuarioDomain> {
IActionResult Login(UsuarioDomain login);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Controller/IClasseController.cs
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller.Base;
namespace Senai.Hroads.WebApi.Interfaces.Controller {
interface IClasseController : IStandardController<Classe> {
IActionResult GetNames();
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/TipoUsuarioRepository.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class TipoUsuarioRepository : IStandardRepository<TipoUsuario> {
HroadsContext ctx = new HroadsContext();
public void Delete(int id) {
ctx.TipoUsuarios.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<TipoUsuario> ListAll() {
return ctx.TipoUsuarios.ToList();
}
public void Register(TipoUsuario newEntity) {
ctx.TipoUsuarios.Add(newEntity);
ctx.SaveChanges();
}
public TipoUsuario SearchById(int id) {
return ctx.TipoUsuarios.FirstOrDefault(tu => tu.IdTipoUsuario == id);
}
public void Update(int id, TipoUsuario newEntity) {
TipoUsuario typeUserSought = SearchById(id);
if(typeUserSought != null) {
typeUserSought.Tipo = newEntity.Tipo;
}
ctx.TipoUsuarios.Update(typeUserSought);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/TipoHabilidadeRepository.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class TipoHabilidadeRepository : IStandardRepository<TipoHabilidade> {
HroadsContext ctx = new HroadsContext();
public void Delete(int id) {
ctx.TipoHabilidades.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<TipoHabilidade> ListAll() {
return ctx.TipoHabilidades.ToList();
}
public void Register(TipoHabilidade newEntity) {
ctx.TipoHabilidades.Add(newEntity);
ctx.SaveChanges();
}
public TipoHabilidade SearchById(int id) {
return ctx.TipoHabilidades.FirstOrDefault(th => th.IdTipoHabilidade == id);
}
public void Update(int id, TipoHabilidade newEntity) {
TipoHabilidade typeSkillSought = SearchById(id);
if(typeSkillSought != null) {
typeSkillSought.Tipo = newEntity.Tipo;
}
ctx.TipoHabilidades.Update(typeSkillSought);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/Peoples/Senai.Peoples/Senai.Peoples.WebApi/Domains/Funcionario.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace Senai.Peoples.WebApi.Domains {
/// <summary>
/// Classe que representa a entidade Funcionario.
/// </summary>
public class Funcionario {
public int idFuncionario { get; set; }
[Required(ErrorMessage ="O nome do funcionário é obrigatório")]
public string nome { get; set; }
public string sobrenome { get; set; }
[DataType(DataType.Date)]
public DateTime dtNasc { get; set; }
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Domains/Clinica.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace MedicalGroup.WebApi.Domains
{
public partial class Clinica
{
public Clinica()
{
Medicos = new HashSet<Medico>();
}
public int IdClinica { get; set; }
public string HoraFuncionamento { get; set; }
public string Cnpj { get; set; }
public string NomeFantasia { get; set; }
public string RazaoSocial { get; set; }
public int IdEndereco { get; set; }
public virtual Endereco IdEnderecoNavigation { get; set; }
public virtual ICollection<Medico> Medicos { get; set; }
}
}
<file_sep>/4º Sprint-Front_End/SP Medical Group/frontend/src/pages/login/Login.jsx
import React, { Component } from "react";
import axios from "axios";
import { parseJwt, usuarioAutenticado } from "../../services/auth";
import "../../assets/css/login.css";
import imgBackground from "../../assets/img/png/2674_souprofissional_compress.webp";
import imgLogo from "../../assets/img/png/logo_spmedgroup_v1.png";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
senha: "",
erroMensagem: "",
isLoading: false,
};
}
efetuaLogin = (event) => {
event.preventDefault();
this.setState({ erroMensagem: "", isLoading: true });
axios
.post("http://localhost:5000/api/login", {
email: this.state.email,
senha: this.state.senha,
})
.then((resposta) => {
if (resposta.status === 200) {
localStorage.setItem("usuario-login", resposta.data.token); // salva o token no localStorage,
console.log("Meu token é: " + resposta.data.token); // exibe o token no console do navegador
this.setState({ isLoading: false }); // e define que a requisição terminou
let base64 = localStorage.getItem("usuario-login").split(".")[1]; // Define a variável base64 que vai receber o payload do token
console.log(base64); // Exibe no console o valor presente na variável base64
console.log(window.atob(base64)); // Exibe no console o valor convertido de base64 para string
console.log(JSON.parse(window.atob(base64))); // Exibe no console o valor convertido da string para JSON
console.log(parseJwt().role); // Exibe no console apenas o tipo de usuário logado
const { history } = this.props;
if (
parseJwt().role === "1" ||
parseJwt().role === "2" ||
parseJwt().role === "3"
) {
history.push("/consulta");
console.log("estou logado: " + usuarioAutenticado());
} else {
history.push("/");
}
}
})
.catch(() => {
this.setState({
erroMensagem: "E-mail ou senha inválidos! Tente novamente.",
isLoading: false,
});
});
};
atualizaStateCampo = (campo) => {
this.setState({ [campo.target.name]: campo.target.value });
};
render() {
return (
<div>
<img
className="img-bg"
src={imgBackground}
alt="imagem background"
/>
<section className="model-login">
<img
className="img-logo"
src={imgLogo}
alt="Logo Medical Group"
/>
<form onSubmit={this.efetuaLogin}>
<div className="item">
<label
for="login-email"
className="label label-one"
style={{ display: "grid" }}
>
Email
</label>
<input
id="login-email"
className="inputs-text login"
type="text"
name="email"
value={this.state.email}
onChange={this.atualizaStateCampo}
/>
</div>
<div className="item">
<label
for="login-password"
className="label label-two"
style={{ display: "grid" }}
>
Password
</label>
<input
id="login-password"
className="inputs-text login"
type="password"
name="senha"
value={this.state.senha}
onChange={this.atualizaStateCampo}
/>
</div>
<p style={{ color: "red", textAlign: "center" }}>
{this.state.erroMensagem}
</p>
{this.state.isLoading === true && (
<div className="item">
<button
type="submit"
id="btn__login"
className="btn btn-login"
disabled
>
Loading...
</button>
</div>
)}
{this.state.isLoading === false && (
<div className="item">
<button
type="submit"
id="btn__login"
className="btn btn-login"
disabled={
this.state.email === "" || this.state.senha === ""
? "none"
: ""
}
>
Login
</button>
</div>
)}
</form>
</section>
</div>
);
}
}
export default Login;
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Repositories/IPersonagemRepository.cs
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
namespace Senai.Hroads.WebApi.Interfaces.Repositories {
interface IPersonagemRepository : IStandardRepository<Personagem> {
List<Personagem> ListCorresponding();
List<Personagem> ListNotCorresponding();
}
}
<file_sep>/4º Sprint-Front_End/SP Medical Group/frontend/src/components/Main.jsx
import React, { useState, useEffect } from "react";
import { Redirect } from "react-router-dom";
import axios from "axios";
import { parseJwt, usuarioAutenticado } from "../services/auth";
import "../assets/css/main.css";
import imgGear from "../assets/img/svg/gear3.svg";
import imgDescription from "../assets/img/png/add-description-doctor.png";
import imgConfirmation from "../assets/img/png/confirmation-doctor.png";
function Main() {
const [listaConsulta, setListaConsulta] = useState([]);
const [visible, setVisible] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [medico, setMedico] = useState("");
const [especialidade, setEspecialidade] = useState("");
const [paciente, setPaciente] = useState("");
const [dtConsulta, setDtConsulta] = useState("");
const [listaConsultaMedico, setListaConsultaMedico] = useState([]);
const [listaConsultaPaciente, setListaConsultaPaciente] = useState([]);
const user = usuarioAutenticado() && parseJwt().role;
function buscarListaConsulta() {
axios("http://localhost:5000/api/consulta", {
headers: {
Authorization: "Bearer " + localStorage.getItem("usuario-login"),
},
})
.then((response) => {
if (response.status === 200) {
setListaConsulta(response.data);
}
})
.catch((error) => console.log(error));
}
function buscarListaConsultaMedico() {
const name00 = parseJwt().email.split("@")[0];
const name = name00.split(".")[0] + " " + name00.split(".")[1];
axios(`http://localhost:5000/api/consulta/filter/medico/${name}`, {
headers: {
Authorization: "Bearer " + localStorage.getItem("usuario-login"),
},
})
.then((response) => {
if (response.status === 200) {
setListaConsultaMedico(response.data);
}
})
.catch((error) => console.log(error));
}
function buscarListaConsultaPaciente() {
const name00 = parseJwt().email.split("@")[0];
const name = name00.split(".")[0];
axios(`http://localhost:5000/api/consulta/filter/paciente/${name}`, {
headers: {
Authorization: "Bearer " + localStorage.getItem("usuario-login"),
},
})
.then((response) => {
if (response.status === 200) {
setListaConsultaPaciente(response.data);
}
})
.catch((error) => console.log(error));
}
useEffect(buscarListaConsulta, []);
useEffect(buscarListaConsultaMedico, []);
useEffect(buscarListaConsultaPaciente, []);
function cadastrarConsulta(event) {
event.preventDefault();
setIsLoading(true);
let consulta = {};
axios
.post("http://localhost:5000/api/consulta", consulta, {
headers: {
Authorization: "Bearer " + localStorage.getItem("usuario-login"),
},
})
.then((resposta) => {
if (resposta.status === 201) {
console.log("Evento cadastrado!");
buscarListaConsulta();
setIsLoading(false);
}
})
.catch((erro) => {
console.log(erro);
setIsLoading(false);
});
}
return (
<main>
<div
className="main_lista"
style={visible ? { display: "block" } : { display: "none" }}
>
<div style={{ height: "65vh" }}>
{(user === "1"
? listaConsulta
: user === "2"
? listaConsultaMedico
: user === "3" && listaConsultaPaciente
).map((consulta) => {
const situation = consulta.idSituacaoNavigation.tipo;
return (
<>
<div
key={consulta.idConsulta}
className="container-item"
>
<div className="doctor-patient">
<div className="doctor-data">
<p>
Médico: {consulta.idMedicoNavigation.nome}
</p>
<p>
Especialidade:
{" " +
consulta.idMedicoNavigation
.idEspecialidadeNavigation.nome}
</p>
</div>
<div className="patient-data">
<p>
Paciente:{" "}
{consulta.idPacienteNavigation.nome}
</p>
<p>Consulta: {consulta.dtAgendamento}</p>
</div>
</div>
<div className="description">
<p>{consulta.descricao}</p>
</div>
<div className="situation-config">
{situation === "Agendada" && (
<div
className="situation-p"
style={{ backgroundColor: "#0cc2fe" }}
>
<p>{consulta.idSituacaoNavigation.tipo}</p>
</div>
)}
{situation === "Realizada" && (
<div
className="situation-p"
style={{ backgroundColor: "#18F235" }}
>
<p>{consulta.idSituacaoNavigation.tipo}</p>
</div>
)}
{situation === "Cancelada" && (
<div
className="situation-p"
style={{ backgroundColor: "#FF4D4D" }}
>
<p>{consulta.idSituacaoNavigation.tipo}</p>
</div>
)}
<div className="situation-update">
{user === "2" && (
<img
className="img-gear"
style={{ marginRight: "1em" }}
src={imgDescription}
alt="Icone, atualizar situação"
/>
)}
{user === "1" ? (
<img
className="img-gear"
src={imgGear}
alt="Icone, atualizar situação"
/>
) : (
user === "2" && (
<img
className="img-gear"
src={imgConfirmation}
alt="Icone, atualizar situação"
/>
)
)}
</div>
</div>
</div>
<hr className="hr-line" />
</>
);
})}
</div>
{user === "1" && (
<section className="footer-btn">
<button
type="button"
className="btn-cadastro btn-cadastrar_consulta"
onClick={() => {
setVisible(false);
}}
>
Nova Consulta
</button>
</section>
)}
</div>
<div
className="main_cadastro"
style={!visible ? { display: "block" } : { display: "none" }}
>
<div className="item-back">
<div className="lines-back">
<div className="line line-up"></div>
<div className="line line-down"></div>
</div>
<p
onClick={() => {
setVisible(!visible);
}}
>
Voltar
</p>
</div>
<form
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
onSubmit={cadastrarConsulta}
>
<section className="section-container">
<div style={{ marginRight: "1.5em" }}>
<div className="section-item">
<label for="doctor" className="labels">
Médico
</label>
<input
type="text"
id="doctor"
className="doctor input-field"
name="medico"
value={medico}
onChange={(event) => setMedico(event.target.value)}
/>
</div>
<div className="section-item">
<label for="specialty" className="labels">
Especialidade
</label>
<input
type="text"
id="specialty"
className="specialty input-field"
name="especialidade"
value={especialidade}
onChange={(event) =>
setEspecialidade(event.target.value)
}
/>
</div>
</div>
<div style={{ marginLeft: "1.5em" }}>
<div className="section-item">
<label for="patient" className="labels">
Paciente
</label>
<input
type="text"
id="patient"
className="patient input-field"
name="paciente"
value={paciente}
onChange={(event) => setPaciente(event.target.value)}
/>
</div>
<div className="section-item">
<label for="consultation-date" className="labels">
Data da Consulta
</label>
<input
type="text"
id="consultation-date"
className="consultation-date input-field"
name="dtConsulta"
value={dtConsulta}
onChange={(event) =>
setDtConsulta(event.target.value)
}
/>
</div>
</div>
</section>
{/* <div className="section-item">
<label for="description" className="labels">
Descrição
</label>
<input
type="text"
id="description"
className="consultation-date input-field"
name=""
value=""
placeholder=""
onChange=""
/>
</div> */}
<button
type="submit"
style={{ marginTop: "6em" }}
className="btn-cadastro btn-cadastrar_consulta"
>
Cadastrar
</button>
</form>
</div>
</main>
);
}
export default Main;
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Controller/IHabilidadeController.cs
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller.Base;
namespace Senai.Hroads.WebApi.Interfaces.Controller {
interface IHabilidadeController : IStandardController<Habilidade> {
IActionResult GetAmountSkills();
IActionResult GetAscendingOrderById();
IActionResult GetSkillsAndTypes();
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Controller/IPersonagemController.cs
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller.Base;
namespace Senai.Hroads.WebApi.Interfaces.Controller {
interface IPersonagemController : IStandardController<Personagem> {
IActionResult GetCorresponding();
IActionResult GetNotCorresponding();
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Interfaces/Repositories/IClasseHabilidadeRepository.cs
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
namespace Senai.Hroads.WebApi.Interfaces.Repositories {
interface IClasseHabilidadeRepository : IStandardRepository<ClasseHabilidade> {
List<ClasseHabilidade> ListCorresponding();
List<ClasseHabilidade> ListNotCorresponding();
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/ConsultaController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Controllers.Base;
using MedicalGroup.WebApi.Interfaces.Repositories;
using MedicalGroup.WebApi.Repositories;
using System;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ConsultaController : ControllerBase, IStandardController<Consulta> {
IConsultaRepository _queryRepository { get; set; }
public ConsultaController() {
_queryRepository = new ConsultaRepository();
}
/// <summary>
/// Deleta uma consulta.
/// </summary>
/// <param name="id">O id da consulta que será deletada.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[Authorize(Roles = "1")]
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
try {
_queryRepository.Delete(id);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Lista todas as consultas.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de consulta.</returns>
[Authorize(Roles = "1,2,3")]
[HttpGet]
public IActionResult Get() {
try {
return Ok(_queryRepository.ListAll());
}
catch(Exception error) {
return BadRequest(error);
}
}
[Authorize(Roles = "2")]
[HttpGet("filter/medico/{name}")]
public IActionResult GetMedico(string name) {
try {
return Ok(_queryRepository.ListMedico(name));
}
catch(Exception error) {
return BadRequest(error);
}
}
[Authorize(Roles = "3")]
[HttpGet("filter/paciente/{name}")]
public IActionResult GetPaciente(string name) {
try {
return Ok(_queryRepository.ListPaciente(name));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Busca apenas uma consulta.
/// </summary>
/// <param name="id">O id da consulta que será buscada.</param>
/// <returns>Retorna um objeto JSON, da consulta buscada.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
try {
return Ok(_queryRepository.SearchById(id));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Cadastra uma nova consulta.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1,2")]
[HttpPost]
public IActionResult Post(Consulta newEntity) {
try {
_queryRepository.Register(newEntity);
return StatusCode(201);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Atualiza uma consulta.
/// </summary>
/// <param name="id">O id da consulta escolhida a ser atualizada.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[Authorize(Roles = "1,2")]
[HttpPut("{id}")]
public IActionResult Put(int id, Consulta newEntity) {
try {
_queryRepository.Update(id, newEntity);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/1º Sprint-BD/SP Medical Group/Modeling Scripts/SP_MedGroup_DQL.sql
USE SP_MedicalGroup;
SELECT * FROM Endereco;<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/UsuarioRepository.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class UsuarioRepository : IUsuarioRepository {
HroadsContext ctx = new HroadsContext();
public void Delete(int id) {
ctx.Usuarios.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Usuario> ListAll() {
return ctx.Usuarios.Include(p => p.IdTipoUsuarioNavigation).ToList();
}
public Usuario Login(string email, string password) {
return ctx.Usuarios.FirstOrDefault(u => u.Email == email && u.Senha == password);
}
public void Register(Usuario newEntity) {
ctx.Usuarios.Add(newEntity);
ctx.SaveChanges();
}
public Usuario SearchById(int id) {
return ctx.Usuarios.FirstOrDefault(p => p.IdUsuario == id);
}
public void Update(int id, Usuario newEntity) {
Usuario soughtUser = SearchById(id);
if(soughtUser != null) {
soughtUser.Email = newEntity.Email;
soughtUser.Senha = newEntity.Senha;
soughtUser.IdTipoUsuario = newEntity.IdTipoUsuario;
}
ctx.Usuarios.Update(soughtUser);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Interfaces/Repositories/IConsultaRepository.cs
using System.Collections.Generic;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
namespace MedicalGroup.WebApi.Interfaces.Repositories {
interface IConsultaRepository : IStantardRepository<Consulta> {
List<Consulta> ListMedico(string name);
List<Consulta> ListPaciente(string name);
}
}<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Controllers/MedicoController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Controllers.Base;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using MedicalGroup.WebApi.Repositories;
using System;
namespace MedicalGroup.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class MedicoController : ControllerBase, IStandardController<Medico> {
IStantardRepository<Medico> _doctorRepository { get; set; }
public MedicoController() {
_doctorRepository = new MedicoRepository();
}
/// <summary>
/// Deleta um médico.
/// </summary>
/// <param name="id">O id do médico que será deletado.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
try {
_doctorRepository.Delete(id);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Lista todos os médicos.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de médicos.</returns>
[HttpGet]
public IActionResult Get() {
try {
return Ok(_doctorRepository.ListAll());
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Busca apenas um médico.
/// </summary>
/// <param name="id">O id do médico que será buscado.</param>
/// <returns>Retorna um objeto JSON, do médico buscado.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
try {
return Ok(_doctorRepository.SearchById(id));
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Cadastra um novo médico.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(Medico newEntity) {
try {
_doctorRepository.Register(newEntity);
return StatusCode(201);
}
catch(Exception error) {
return BadRequest(error);
}
}
/// <summary>
/// Atualiza um médico.
/// </summary>
/// <param name="id">O id do médico escolhido a ser atualizado.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Medico newEntity) {
try {
_doctorRepository.Update(id, newEntity);
return StatusCode(204);
}
catch(Exception error) {
return BadRequest(error);
}
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Repositories/UsuarioRepository.cs
using Microsoft.EntityFrameworkCore;
using MedicalGroup.WebApi.Contexts;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace MedicalGroup.WebApi.Repositories {
public class UsuarioRepository : IUsuarioRepository {
MedicalGroupContext ctx = new MedicalGroupContext();
public void Delete(int id) {
ctx.Usuarios.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Usuario> ListAll() {
return ctx.Usuarios.ToList();
}
public Usuario Login(string email, string password) {
return ctx.Usuarios.FirstOrDefault(u => u.Email == email && u.Senha == password);
}
public void Register(Usuario newEntity) {
ctx.Usuarios.Add(newEntity);
ctx.SaveChanges();
}
public Usuario SearchById(int id) {
return ctx.Usuarios.FirstOrDefault(u => u.IdUsuario == id);
}
public void Update(int id, Usuario newEntity) {
Usuario searchedUser = ctx.Usuarios.Find(id);
if(searchedUser != null) {
// UNDONE: searchedUser != null
}
ctx.Usuarios.Update(searchedUser);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Interfaces/Repository/IUsuarioRepository.cs
using Senai.InLock.WebApi.Domains;
namespace Senai.InLock.WebApi.Interfaces {
interface IUsuarioRepository : IStandardRepository<UsuarioDomain> {
UsuarioDomain Login(string email, string password);
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Controllers/ClasseController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Controller;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using Senai.Hroads.WebApi.Repositories;
namespace Senai.Hroads.WebApi.Controllers {
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ClasseController : ControllerBase, IClasseController {
IClasseRepository _classRepository { get; set; }
public ClasseController() {
_classRepository = new ClasseRepository();
}
/// <summary>
/// Lista, somente, os nome de todas as classes.
/// </summary>
/// <returns>Retorna uma lista JSON, com os nomes das classes.</returns>
[HttpGet("names")]
public IActionResult GetNames() {
throw new System.NotImplementedException();
}
/// <summary>
/// Lista todas as classes.
/// </summary>
/// <returns>Retorna um objeto JSON, com a lista de classes.</returns>
[HttpGet]
public IActionResult Get() {
return Ok(_classRepository.ListAll());
}
/// <summary>
/// Busca apenas uma classe.
/// </summary>
/// <param name="id">O id da classe que será buscada.</param>
/// <returns>Retorna um objeto JSON, da classe buscada.</returns>
[HttpGet("{id}")]
public IActionResult Get(int id) {
return Ok(_classRepository.SearchById(id));
}
/// <summary>
/// Cadastra uma nova classe.
/// </summary>
/// <param name="newEntity">Objeto que será cadastrado.</param>
/// <returns>Retorna um StatusCode 201(Created).</returns>
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(Classe newEntity) {
_classRepository.Register(newEntity);
return StatusCode(201);
}
/// <summary>
/// Atualiza uma classe.
/// </summary>
/// <param name="id">O id da classe escolhida a ser atualizada.</param>
/// <param name="newEntity">Objeto com as novas informações.</param>
/// <returns>Retorna um StatusCode 204(No Content).</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, Classe newEntity) {
_classRepository.Update(id, newEntity);
return StatusCode(204);
}
/// <summary>
/// Deleta uma classe.
/// </summary>
/// <param name="id">O id da classe que será deletada.</param>
/// <returns>Retorna StatusCode 204(No Content).</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id) {
_classRepository.Delete(id);
return StatusCode(204);
}
}
}
<file_sep>/4º Sprint-Front_End/SP Medical Group/frontend/src/pages/consulta/Consulta.jsx
import React, { Component } from "react";
import "../../assets/css/consulta.css";
import Aside from "../../components/Aside";
import Header from "../../components/Header";
import Main from "../../components/Main";
class Consulta extends Component {
render() {
return (
<div className="queries-body">
<section className="modelPage">
<Aside />
<div className="header-main">
<Header />
<Main />
</div>
</section>
</div>
);
}
}
export default Consulta;
<file_sep>/2º Sprint-Back_End/SP Medical Group/Modeling/Scripts/SP_MedGroup_DML.sql
USE SP_MedicalGroup;
INSERT INTO dbo.Endereco (logradouro, numero, bairro, cidade, estado, cep)
VALUES (
'<NAME>', '532', 'Santa Cecília', 'São Paulo', 'SP', ''
), (
'Rua Vitória', '120', '<NAME>', 'Barueri', 'SP', '06402030'
), (
'Rua Vere<NAME>', '66', 'Santa Luzia', 'Ribeirão Pires', 'SP', '09405380'
);
INSERT INTO dbo.Clinica (horaFuncionamento, cnpj, nomeFantasia, razaoSocial, idEndereco)
VALUES (
'07:00-20:00', '86400902000130', 'Clínica Possarle', 'SP Medical Group', 1
);
INSERT INTO dbo.Especialidade (nome)
VALUES (
'Acupuntura'
), (
'Anestesiologia'
), (
'Angiologia'
), (
'Cardiologia'
), (
'Cirurgia Cardiovascular'
), (
'Cirurgia da Mão'
), (
'Cirurgia do Aparelho Digestivo'
), (
'Cirurgia Geral'
), (
'Cirurgia Pediátrica'
), (
'Cirurgia Torácica'
), (
'Cirugia Vascular'
), (
'Dermatologia'
), (
'Radioterapia'
), (
'Urologia'
), (
'Pediatria'
), (
'Psiquiatria'
);
INSERT INTO dbo.Situacao (tipo)
VALUES (
'Agendada'
), (
'Cancelada'
), (
'Realizada'
);
INSERT INTO dbo.TipoUsuario (perfil)
VALUES (
'Administrador'
), (
'Médico'
), (
'Paciente'
);
INSERT INTO dbo.Usuario (email, senha, idTipoUsuario)
VALUES (
'<EMAIL>', '<PASSWORD>', 2
), (
'<EMAIL>', '789456', 3
), (
'<EMAIL>', '123789', 1
), (
'<EMAIL>', '741852', 2
), (
'<EMAIL>', '963852', 3
), (
'<EMAIL>', '159753', 2
);
INSERT INTO dbo.Paciente (nome, telefone, dtNasc, rg, cpf, idUsuario, idEndereco)
VALUES (
'Fernando', '11936586987', '06/08/1999', '369478125', '12345678974', 2, 2
), (
'João', '11945878596', '07/04/1998', '256789482', '45678925896', 5, 3
);
INSERT INTO dbo.Medico (nome, crm, idUsuario, idEspecialidade, idClinica)
VALUES (
'<NAME>', '54369SP', 1, 2, 1
), (
'<NAME>', '53789SP', 4, 16, 1
), (
'<NAME>', '68741SP', 6, 15, 1
);
INSERT INTO dbo.Consulta (dtAgendamento, descricao, idSituacao, idMedico, idPaciente)
VALUES (
'06/09/2021 07:00', 'Texto...', 1, 2, 1
), (
'10/03/2021 08:00', 'Texto...', 3, 1, 2
), (
'25/05/2021 10:30', 'Texto...', 2, 3, 1
);
<file_sep>/2º Sprint-Back_End/exercicios/InLock/Senai.InLock/Senai.InLock.WebApi/Interfaces/Repository/IJogosRepository.cs
using Senai.InLock.WebApi.Domains;
using System.Collections.Generic;
namespace Senai.InLock.WebApi.Interfaces {
interface IJogosRepository : IStandardRepository<JogosDomain> {
List<JogosDomain> ListGamesStudios();
List<JogosDomain> ListStudiosGames();
}
}
<file_sep>/4º Sprint-Front_End/exercicios/desafio_processo_seletivo/src/pages/InfoGitHub.jsx
import { Component } from "react";
class Home extends Component {
constructor(props) {
super(props);
this.state = {
listRepositories: [],
name: "",
currentSort: "default",
};
}
componentDidMount() {
this.SearchRepositories();
}
componentWillUnmount() {}
SearchRepositories = () => {
fetch(`https://api.github.com/users/rafaelgckto/repos`)
.then((response) => response.json())
.then((data) => this.setState({ listRepositories: data }))
.catch((error) => console.log(error));
};
onSortChange = () => {
const { currentSort } = this.state;
let nextSort;
if (currentSort === "down") nextSort = "up";
else if (currentSort === "up") nextSort = "default";
else if (currentSort === "default") nextSort = "down";
this.setState({
currentSort: nextSort,
});
console.log(this.state.currentSort);
};
test = () => {
let teste00 = this.state.listRepositories;
let teste01 = [],
teste02 = [];
for (let i = 0; i < teste00.length; i++) {
teste01[i] = teste00[i].created_at;
}
let teste03 = teste01.sort().reverse();
for (let j = 0; j < teste03.length; j++) {
teste02.push(teste03[j]);
}
return teste02;
//console.log(teste02);
};
render() {
const { listRepositories } = this.state;
const { currentSort } = this.state;
const sortTypes = {
up: {
class: "sort-up",
fn: (a, b) => a.created_at - b.created_at,
},
down: {
class: "sort-down",
fn: (a, b) => b.created_at - a.created_at,
},
default: {
class: "sort",
fn: (a, b) => a,
},
};
return (
<div>
<main>
<section>
<h3>Lista de repositorios do(a) CONTA</h3>
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Decription</th>
<th>Creation</th>
<th>Size</th>
</tr>
</thead>
{listRepositories.length > 0 && (
<tbody>
{[...listRepositories]
.sort(sortTypes[currentSort].fn)
.map((list) => {
return (
<tr key={list.id}>
<td>{list.id}</td>
<td>{list.name}</td>
<td>{list.description}</td>
<td>{list.created_at}</td>
<td>{list.size}</td>
</tr>
);
})}
</tbody>
)}
<tfoot></tfoot>
</table>
</section>
{/* <button type="button" onClick={this.onSortChange}>
opa
</button> */}
{/* <section>
<h3>Pesquisa de Campo</h3>
<form>
<div>
<input
type="text"
value={this.state.name}
onChange={this.ChangeStateName}
placeholder="Nome de perfil(github) do cidadão"
/>
<button
type="submit"
disabled={this.state.name === "" ? "none" : ""}
>
Pesquisar
</button>
</div>
</form>
<div></div>
</section> */}
</main>
</div>
);
}
}
export default Home;
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/ViewModel/LoginViewModel.cs
using System.ComponentModel.DataAnnotations;
namespace MedicalGroup.WebApi.ViewModel {
public class LoginViewModel {
[Required(ErrorMessage = "Informe o e-mail do usuário!")]
public string Email { get; set; }
[Required(ErrorMessage = "Informe a senha do usuário!")]
public string Senha { get; set; }
}
}
<file_sep>/1º Sprint-BD/desafios/HROADS/Modeling Scripts/Hroads_DQL.sql
USE Senai_Hroads_Manha;
-- Atualizar o nome do personagem Fer8 para Fer7.
UPDATE dbo.Personagem
SET nome = 'Fer7'
WHERE dbo.Personagem.idPersonagem = 3;
-- Atualizar o nome da classe de Necromante para Necromancer.
UPDATE dbo.Classe
SET nome = 'Necromancer'
WHERE dbo.Classe.idClasse = 5;
-- Selecionar todos os personagens.
SELECT *
FROM dbo.Personagem;
-- Selecionar todas as classes.
SELECT *
FROM dbo.Classe;
-- Selecionar somente o nome das classes.
SELECT dbo.Classe.nome
FROM dbo.Classe;
-- Selecionar todas as habilidades.
SELECT *
FROM dbo.Habilidade;
-- Realizar contagem de quantas habilidades estão cadastradas.
SELECT COUNT(dbo.Habilidade.idHabilidade) AS [Qtd. d/ Habilidades]
FROM dbo.Habilidade;
-- Selecionar somente os id's das habilidades classificando-ospor ordem crescente.
SELECT *
FROM dbo.Habilidade
ORDER BY dbo.Habilidade.idHabilidade ASC;
-- Selecionar todos os tipos de habilidades.
SELECT *
FROM dbo.TipoHabilidade;
-- Selecionar todas as habilidades e a quais tipos de habilidades elas fazem parte.
SELECT H.idHabilidade, H.nome AS [Habilidade], TH.tipo AS [Tipo]
FROM dbo.Habilidade AS H
INNER JOIN dbo.TipoHabilidade AS TH
ON H.idTipoHabilidade = TH.idTipoHabilidade;
-- Selecionar todos os personagem e suas respectivas classes.
SELECT P.idPersonagem, P.nome AS [Personagem], C.nome AS [Classe], P.vida AS [Vida], P.mana AS [Mana], P.dtAtualizacao AS [Dt. Atualização], P.dtCricao AS [Dt. Criação]
FROM dbo.Personagem AS P
INNER JOIN dbo.Classe AS C
ON P.idClasse = C.idClasse;
-- Selecionar todos os personagens e as classes (mesmo que elas não tenham correspondência).
SELECT P.idPersonagem, P.nome AS [Personagem], C.nome AS [Classe], P.vida AS [Vida], P.mana AS [Mana], P.dtAtualizacao AS [Dt. Atualização], P.dtCricao AS [Dt. Criação]
FROM dbo.Personagem AS P
LEFT JOIN dbo.Classe AS C
ON P.idClasse = C.idClasse;
-- Selecionar todas as classes e suas respectivas habilidades.
SELECT *
FROM dbo.Classe_Habilidade;
-- Selecionar todas as habilidades e suas classes (somente as que possuem correspondência).
SELECT C.nome AS [Classe], H.nome AS [Habilidade]
FROM dbo.Classe_Habilidade AS CH
INNER JOIN dbo.Classe AS C
ON CH.idClasse = C.idClasse
INNER JOIN dbo.Habilidade AS H
ON CH.idHabilidade = H.idHabilidade;
-- Selecionar todas as habilidades e suas classes (mesmo que elas não tenham correspondência).
SELECT C.nome AS [Classe], H.nome AS [Habilidade]
FROM dbo.Classe_Habilidade AS CH
RIGHT JOIN dbo.Classe AS C
ON CH.idClasse = C.idClasse
LEFT JOIN dbo.Habilidade AS H
ON CH.idHabilidade = H.idHabilidade;<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Repositories/PacienteRepository.cs
using MedicalGroup.WebApi.Contexts;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
using System.Linq;
namespace MedicalGroup.WebApi.Repositories {
public class PacienteRepository : IStantardRepository<Paciente> {
MedicalGroupContext ctx = new MedicalGroupContext();
public void Delete(int id) {
ctx.Pacientes.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Paciente> ListAll() {
return ctx.Pacientes.ToList();
}
public void Register(Paciente newEntity) {
ctx.Pacientes.Add(newEntity);
ctx.SaveChanges();
}
public Paciente SearchById(int id) {
return ctx.Pacientes.FirstOrDefault(p => p.IdPaciente == id);
}
public void Update(int id, Paciente newEntity) {
Paciente soughtPatient = ctx.Pacientes.Find(id);
if(soughtPatient != null) {
// UNDONE: soughtPatient != null
}
ctx.Pacientes.Update(soughtPatient);
ctx.SaveChanges();
}
}
}
<file_sep>/1º Sprint-BD/exercicios/1.4 - optus/Optus_DQL.sql
USE Optus;
SELECT * FROM Usuario;
SELECT * FROM Artista;
SELECT * FROM Album;
SELECT * FROM Estilo;
SELECT * FROM Album_Estilo;
SELECT U.nome AS [Usuário], U.email AS [E-mail], U.senha AS [Senha]
FROM Usuario AS U
WHERE permissao = 0;
SELECT *
FROM Album
WHERE dtLancamento = '2012';
SELECT nome, email
FROM Usuario
WHERE email = '<EMAIL>' AND senha = '<PASSWORD>';
SELECT AR.nome AS [Artista], E.nome AS [Estilo]
FROM Album_Estilo AS AE
INNER JOIN Album AS AL ON AE.idAlbum = AL.idAlbum
INNER JOIN Artista AS AR ON AL.idArtista = AR.idArtista
INNER JOIN Estilo AS E ON AE.idEstilo = E.idEstilo
WHERE AL.ativo = 1;<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Domains/Personagem.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Senai.Hroads.WebApi.Domains
{
public partial class Personagem
{
public int IdPersonagem { get; set; }
public string Nome { get; set; }
public int? IdClasse { get; set; }
public decimal? Vida { get; set; }
public decimal? Mana { get; set; }
public DateTime? DtAtualizacao { get; set; }
public DateTime? DtCricao { get; set; }
public virtual Classe IdClasseNavigation { get; set; }
}
}
<file_sep>/2º Sprint-Back_End/exercicios/HROADS/Senai.Hroads/Senai.Hroads.WebApi/Repositories/HabilidadeRepository.cs
using Microsoft.EntityFrameworkCore;
using Senai.Hroads.WebApi.Contexts;
using Senai.Hroads.WebApi.Domains;
using Senai.Hroads.WebApi.Interfaces.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace Senai.Hroads.WebApi.Repositories {
public class HabilidadeRepository : IHabilidadeRepository {
HroadsContext ctx = new HroadsContext();
public Habilidade AmountSkills() {
throw new System.NotImplementedException();
}
public List<Habilidade> AscendingOrderById() {
throw new System.NotImplementedException();
}
public List<Habilidade> ListSkillsAndTypes() {
throw new System.NotImplementedException();
}
public List<Habilidade> ListAll() {
return ctx.Habilidades.Include(h => h.IdTipoHabilidadeNavigation).ToList();
}
public Habilidade SearchById(int id) {
return ctx.Habilidades.FirstOrDefault(h => h.IdHabilidade == id);
}
public void Register(Habilidade newEntity) {
ctx.Habilidades.Add(newEntity);
ctx.SaveChanges();
}
public void Update(int id, Habilidade newEntity) {
Habilidade skillSought = ctx.Habilidades.Find(id);
if(skillSought != null) {
skillSought.Nome = newEntity.Nome;
skillSought.IdTipoHabilidade = newEntity.IdTipoHabilidade;
}
ctx.Habilidades.Update(skillSought);
ctx.SaveChanges();
}
public void Delete(int id) {
Habilidade skillSought = ctx.Habilidades.Find(id);
ctx.Habilidades.Remove(skillSought);
ctx.SaveChanges();
}
}
}
<file_sep>/2º Sprint-Back_End/SP Medical Group/MedicalGroup.WebApi/Repositories/ClinicaRepository.cs
using MedicalGroup.WebApi.Contexts;
using MedicalGroup.WebApi.Domains;
using MedicalGroup.WebApi.Interfaces.Repositories.Base;
using System.Collections.Generic;
using System.Linq;
namespace MedicalGroup.WebApi.Repositories
{
public class ClinicaRepository : IStantardRepository<Clinica>
{
MedicalGroupContext ctx = new MedicalGroupContext();
public void Delete(int id)
{
ctx.Clinicas.Remove(SearchById(id));
ctx.SaveChanges();
}
public List<Clinica> ListAll()
{
return ctx.Clinicas.ToList();
}
public void Register(Clinica newEntity)
{
ctx.Clinicas.Add(newEntity);
ctx.SaveChanges();
}
public Clinica SearchById(int id)
{
return ctx.Clinicas.FirstOrDefault(c => c.IdClinica == id);
}
public void Update(int id, Clinica newEntity)
{
Clinica soughtClinic = ctx.Clinicas.Find(id);
if (soughtClinic != null)
{
// UNDONE: soughtClinic != null
}
ctx.Clinicas.Update(soughtClinic);
ctx.SaveChanges();
}
}
}
|
a300c9f6fe3c7e78a23ca17f3540e6e290d51bc8
|
[
"JavaScript",
"C#",
"SQL"
] | 79 |
C#
|
rafaelgckto/Senai-Dev
|
82c7dd0332dee8029ff0a0b7068b30a0da81b3b1
|
e586a9faaecb01f5268fcb3e4809c9d100a9095f
|
refs/heads/master
|
<repo_name>thanakijwanavit/Villa2<file_sep>/Villa2/SystemTypeExtension/Collections+Extension.swift
//
// Collections+Extension.swift
// Villa2
//
// Created by <NAME> on 4/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
extension Collection {
func enumeratedArray() -> Array<(offset: Int, element: Self.Element)> {
return Array(self.enumerated())
}
}
<file_sep>/Villa2/SystemTypeExtension/StringExtension.swift
//
// StringExtension.swift
// Villa2
//
// Created by <NAME> on 3/27/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
extension String{
var floatValue:Float{
if let float = Float(self){
return float
} else {
debugPrint("error converting string \(self) to float \n please check in stringExtension file , returning 0")
return Float(0)
}
}
}
extension String: Error {
}
extension String: LocalizedError {
public var errorDescription: String? { return self }
}
//pat first letter
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
<file_sep>/Villa2/SystemTypeExtension/ImageExtension.swift
//
// ImageExtension.swift
// Villa2
//
// Created by <NAME> on 4/3/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
extension UIImage{
func resizedImage(targetSize:CGSize)->UIImage{
return ImageManipulation.resizeImage(image: self, targetSize: targetSize)
}
}
extension UIImage{
func imageByMakingWhiteBackgroundTransparent() -> UIImage? {
let image = UIImage(data: self.jpegData(compressionQuality: 1.0)!)!
let rawImageRef: CGImage = image.cgImage!
let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
UIGraphicsBeginImageContext(image.size);
let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result
}
}
extension UIImage {
func imageWithColor(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: 0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0);
context.setBlendMode(.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
context.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
extension UIImage {
func withBackground(color: UIColor, opaque: Bool = true) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
guard let ctx = UIGraphicsGetCurrentContext() else { return self }
defer { UIGraphicsEndImageContext() }
let rect = CGRect(origin: .zero, size: size)
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height))
ctx.draw(cgImage!, in: rect)
return UIGraphicsGetImageFromCurrentImageContext() ?? self
}
}
<file_sep>/Villa2/View/Observables/ProductList.swift
//
// ProductDataSource.swift
// villaEcommerce
//
// Created by <NAME> on 1/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
class ProductList: ObservableObject {
@Published var products:[ProductRaw]
init(products: [ProductRaw]) {
self.products = products
}
var cart:[ProductRaw] {
let cartProducts = self.products.filter { (product) -> Bool in
// var mutableProduct = product
return product.isInCart
}
return cartProducts
}
func getQuantityInCart(sku:SKU)->Int {
return 0
// if let productID = self.findBySku(sku: sku){
// return self.products[productID].quantityInCart
// } else {
// debugPrint("error in file Productlist, Cant find product sku:\(sku) in the product list using function getQuantityInCart")
// return 0
// }
}
func setQuantityInCart(sku:SKU, quantity:Int){
if let productID = self.findBySku(sku: sku){
self.products[productID].quantityInCart = quantity
} else {
debugPrint("error in file Productlist, Cant find product sku:\(sku) in the product list using function setQuantityInCart")
}
}
var cartTotal:Float {
var sum:Float = 0
// debugPrint("cart is :", self.cart)
for product in self.cart {
debugPrint("price is :", product.price,"quantity is :", product.quantityInCart)
sum += product.price * Float(product.quantityInCart)
debugPrint("sum is ", sum)
}
return sum
}
// var filteredProspects: [Prospect] {
// switch filter {
// case .none:
// return prospects.people
// case .contacted:
// return prospects.people.filter { $0.isContacted }
// case .uncontacted:
// return prospects.people.filter { !$0.isContacted }
// }
// }
func findProductBySku(sku:SKU)->ProductRaw?{
if let productIndex = self.findBySku(sku: sku){
return self.products[productIndex]
} else {
return nil
}
}
func findProductsBySku(skus:[SKU])->[ProductRaw]{
var productList:[ProductRaw] = []
for sku in skus{
if let product = self.findProductBySku(sku: sku){
productList.append(product)
}
}
return productList
}
func findBySku(sku:SKU)->Int?{
if let index = self.products.firstIndex(where: { (selectedProduct) -> Bool in
return selectedProduct.sku == sku
}) {
return index
}
debugPrint("error findBySku cant find product")
return nil
}
func findBySkus(skus:[SKU])->[Int]{
var productIDList:[Int] = []
for sku in skus{
if let productID = self.findBySku(sku: sku) {
productIDList.append(productID)
}
}
return productIDList
}
}
class SampleProductList{
static var productList:ProductList {
get {
return ProductList(products: self.products)
}
set (newValue){
self.products = newValue.products
}
}
static var products:[ProductRaw] =
[
ProductRaw(name: "Banana", image: #imageLiteral(resourceName: "Banana"), price: 50, sku: "221224869864295", category:"fruit", description:"blah blah jdshaflkhsafkldhsfkldhjlkhja dklhdalkjhklhkhahkfajhkahdf jkhlkhklhjkhklh jhkhklhklhklhjklh oituttuiott tiptiotiotoit [otpotpotoitoi tiotoiutoi", quantityInCart: 4),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "36596234234249", category:"fruit", description:"blah blah"),
ProductRaw(name: "orange", image: #imageLiteral(resourceName: "orange"), price: 80, sku: "3896292432342369", category:"fruit", description:"blah blah"),
ProductRaw(name: "pen", image: #imageLiteral(resourceName: "pen"), price: 80, sku: "3892335324234369", category:"fruit", description:"blah blah", isRecommended: true),
ProductRaw(name: "pen", image: #imageLiteral(resourceName: "pen"), price: 80, sku: "38923532344369", category:"fruit", description:"blah blah", isRecommended: true),
ProductRaw(name: "pen", image: #imageLiteral(resourceName: "pen"), price: 80, sku: "38925392369", category:"fruit", description:"blah blah", isRecommended: true),
ProductRaw(name: "pen", image: #imageLiteral(resourceName: "pen"), price: 80, sku: "3896322369", category:"fruit", description:"blah blah", isRecommended: true),
ProductRaw(name: "pen", image: #imageLiteral(resourceName: "pen"), price: 80, sku: "3852339692369", category:"fruit", description:"blah blah", isRecommended: true),
ProductRaw(name: "pen", image: #imageLiteral(resourceName: "pen"), price: 80, sku: "387435692369", category:"fruit", description:"blah blah", isRecommended: true),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "3653734249", category:"fruit", description:"blah blah"),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "36594754249", category:"fruit", description:"blah blah"),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "3659374534249", category:"fruit", description:"blah blah"),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "36596475249", category:"fruit", description:"blah blah"),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "36596374249", category:"fruit", description:"blah blah"),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "3659374249", category:"fruit", description:"blah blah"),
ProductRaw(name: "Apple", image: #imageLiteral(resourceName: "Apple"), price: 100, sku: "365375434249", category:"fruit", description:"blah blah", quantityInCart: 4)
]
}
<file_sep>/Villa2/View/SettingsView/LoginView.swift
import UIKit
import SwiftUI
import AuthenticationServices
struct LoginView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var user: CurrentUser
@Binding var showLogin:Bool
@State var appleSignInDelegates: SignInWithAppleDelegates! = nil
var body: some View {
ZStack {
Color(.secondarySystemFill).edgesIgnoringSafeArea(.all)
VStack(spacing: 10) {
Image("VillaLogo1")
.resizable()
.scaledToFit()
// UserAndPassword()
// .padding()
SignInWithApple()
.frame(width: 280, height: 60)
.onTapGesture(perform: showAppleLogin)
LoginWithFB()
.frame(width: 280, height: 60)
SignUp()
.frame(width: 280, height: 60)
LoginDebugButton(showLogin: self.$showLogin)
}
}
.onAppear {
self.performExistingAccountSetupFlows()
}
}
private func showAppleLogin() {
let request = ASAuthorizationAppleIDProvider().createRequest()
request.requestedScopes = [.fullName, .email]
performSignIn(using: [request])
}
/// Prompts the user if an existing iCloud Keychain credential or Apple ID credential is found.
private func performExistingAccountSetupFlows() {
#if !targetEnvironment(simulator)
// Note that this won't do anything in the simulator. You need to
// be on a real device or you'll just get a failure from the call.
let requests = [
ASAuthorizationAppleIDProvider().createRequest(),
ASAuthorizationPasswordProvider().createRequest()
]
performSignIn(using: requests)
#endif
}
private func performSignIn(using requests: [ASAuthorizationRequest]) {
appleSignInDelegates = SignInWithAppleDelegates(window: window) { success in
if success {
// update UI
debugPrint("sign in successful")
} else {
// show the user an error
debugPrint("sign in error")
}
}
let controller = ASAuthorizationController(authorizationRequests: requests)
controller.delegate = appleSignInDelegates
controller.presentationContextProvider = appleSignInDelegates
controller.performRequests()
}
}
struct LoginDebugButton:View {
@EnvironmentObject var user:CurrentUser
@Binding var showLogin:Bool
var body: some View {
Button(action: {
self.user.isLoggedIn.toggle()
self.showLogin.toggle()
}) {
Text("debugLogin")
}
.frame(width: 280, height: 60)
.background(Color.black)
.foregroundColor(.white)
.font(.headline)
}
}
struct LoginWithFB:View {
@EnvironmentObject var user:CurrentUser
var body: some View {
Button(action: {
//
}) {
Image("FBLoginButton")
.renderingMode(.original)
.resizable()
}
}
}
struct SignUp:View {
@EnvironmentObject var user:CurrentUser
var body: some View {
Button(action: {
self.user.isLoggedIn.toggle()
}) {
ZStack{
Color.gray
Text("Sign up")
.font(.headline)
}
}
.buttonStyle(PlainButtonStyle())
}
}
#if DEBUG
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
Group {
LoginView(showLogin: .constant(true))
.environmentObject(CurrentUser())
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
LoginView(showLogin: .constant(true))
.environmentObject(CurrentUser())
.background(Color(.systemBackground))
.environment(\.colorScheme, .light)
}
}
}
#endif
<file_sep>/Villa2/View/Tab1HomeView/CartView/CartViewHeaderCell.swift
//
// CartViewHeaderCell.swift
// Villa2
//
// Created by <NAME> on 3/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct CartViewHeaderCell: View {
// @EnvironmentObject var productList:ProductList
@State var animationAmount:Double = 1
var cartTotal:Float
var numberOfProducts:Int
var body: some View {
VStack{
HStack {
Text("Subtotal ( \(self.numberOfProducts) items):")
Text("฿ \(self.cartTotal.noDecimalPoints)")
.foregroundColor(.orange)
.rotation3DEffect(.degrees(animationAmount), axis: (x: 0, y: 1, z: 0))
// .scaleEffect(animationAmount)
// .animation(
// Animation.easeInOut(duration: 1.8)
// .delay(0.2)
// .repeatForever(autoreverses: true)
// )
.onAppear {
withAnimation( Animation.easeInOut(duration: 2)
.repeatForever(autoreverses: true)
){
self.animationAmount = 20
}
}
}
}
.font(.system(size: 20, weight: .heavy, design: .default))
.padding()
}
}
struct CartViewHeaderCell_Previews: PreviewProvider {
static var previews: some View {
Group {
CartViewHeaderCell(cartTotal: 5.0, numberOfProducts: 5)
.background(Color(.systemBackground))
.environment(\.colorScheme, .light)
.previewLayout(.sizeThatFits)
CartViewHeaderCell(cartTotal: 4.0, numberOfProducts: 5)
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewLayout(.sizeThatFits)
}
// .environmentObject(SampleProductList.productList)
}
}
<file_sep>/Villa2/View/HelperViews/ProductCoreCollectionView/ProductCoreCollectionViewTable.swift
import SwiftUI
import CoreData
struct ProductCoreCollectionViewTable: View {
@Binding var disableImageAnimation:Bool
@Binding var bindingResultLimit:Int
@Binding var sidebar:Bool
var isSingleProduct:Bool
var fetchRequest:FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
//var for the more button
@State var offsetVal:CGFloat = -100
let filter:String
let resultLimit:Int
let cat1:String
let cat2:String
// let g:GeometryProxy
let width:CGFloat
var drag: some Gesture {
DragGesture()
.onChanged { _ in self.offsetVal = 0}
}
init(filter: String, disableImageAnimation:Binding<Bool>, resultLimit: Int, bindingResultLimit: Binding<Int>, sidebar: Binding<Bool>, cat1:String, cat2:String, width:CGFloat, isSingleProduct:Bool){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = resultLimit
// debugPrint("cat1 is \(cat1), cat2 is \(cat2)")
let cat1Predicate = NSPredicate(format: cat1.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat1,cat1,cat1,cat1)
let cat2Predicate = NSPredicate(format: cat2.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat2,cat2,cat2,cat2)
let searchPredicate = NSPredicate(format: filter.count > 0 ? "(name CONTAINS[c] %@) OR (metaKeywords CONTAINS[c] %@) ":"TRUEPREDICATE", filter.count > 0 ? filter:"*",filter.count > 0 ? filter:"*")
let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [cat1Predicate, cat2Predicate,searchPredicate])
// let sortDescriptor = NSSortDescriptor(key: "sku", ascending: true)
request.predicate = andPredicate
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
self._disableImageAnimation = disableImageAnimation
self._bindingResultLimit = bindingResultLimit
self._sidebar = sidebar
self.filter = filter
self.resultLimit = resultLimit
self.cat1 = cat1
self.cat2 = cat2
self.width = width
self.isSingleProduct = isSingleProduct
}
var body: some View {
return
GeometryReader{ g in
ScrollView(.horizontal,showsIndicators: false) {
HStack(alignment: .center){
Spacer().frame(width: (self.width + 50) / 4, height: (self.width / 4) + 200)
ForEach(self.productCores, id:\.self){ p in
ProductCoreCollectionViewCell(product: p,disableImageAnimation: self.$disableImageAnimation,sidebar: self.$sidebar, imageWidth: self.width / 3, globalG: g, isSingleProduct: self.isSingleProduct)
.frame(width: (self.width + 50) / 4, height: (self.width / 4) + 250)
.offset(x: self.offsetVal, y: 0)
}
}
}
}
.frame( width: self.width, height: (self.width / 4) + 250)
// .overlay(Rectangle().stroke(lineWidth: 1))
}
}
struct ProductCoreCollectionViewTable_Previews: PreviewProvider {
static var previews: some View {
let context = SampleProductCore.context
return GeometryReader { g in
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 5, bindingResultLimit: .constant(5), sidebar: .constant(false),cat1: "",cat2: "", width: 400, isSingleProduct: true)
.modifier(SubViewPreviewModifier(context: context))
}
}
}
<file_sep>/Villa2/View/Tab1HomeView/Body/HomeView.swift
//
// ProductsTable.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import KingfisherSwiftUI
import CoreData
struct HomeView: View {
var fetchRequest:FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
@EnvironmentObject var catList:ProductCategoryList
@Environment(\.managedObjectContext) var moc
@State private var currentCatLabel:String = "Highlight"
var mainCat:[ProductCategory] { get {self.catList.products.childrenData[0].childrenData}}
var bannerList = ["villaBanner1","villaBanner2","villaBanner3","villaBanner4"]
init(){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = 20
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
}
var body: some View {
GeometryReader { g in
// VStack{
ScrollView(.vertical, showsIndicators: true) {
self.searchTab(g: g)
self.seperationLine(g: g)
self.fullSizeBanners(g: g)
// self.quarterSizeBanners()
// self.villaLogo(g: g)
self.searchIconsSection(g: g)
self.quarterSizeBanners()
self.recommendedProductChoices(g: g)
self.scrollingBanner(g:g)
self.recommendedProducts(g: g)
}
.frame(width: g.size.width)
.onTapGesture {
UIApplication.shared.endEditing()
}
// }
}
}
// MARK:- UI items
func fullSizeBanners(g:GeometryProxy) -> some View {
KFImage(URL(string: "https://villa-banners-sg.s3-ap-southeast-1.amazonaws.com/Promotion/900x350_Pr_Eng_OUTLINED+(1).jpg")!)
.resizable()
.scaledToFit()
}
func quarterSizeBanners()-> some View {
HStack{
KFImage(URL(string: "https://villa-banners-sg.s3-ap-southeast-1.amazonaws.com/verticalBanners/305x397-Coolhaus.jpg")!)
.resizable()
.scaledToFit()
KFImage(URL(string: "https://villa-banners-sg.s3-ap-southeast-1.amazonaws.com/verticalBanners/305x397-Coolhaus.jpg")!)
.resizable()
.scaledToFit()
KFImage(URL(string: "https://villa-banners-sg.s3-ap-southeast-1.amazonaws.com/verticalBanners/305x397-Coolhaus.jpg")!)
.resizable()
.scaledToFit()
KFImage(URL(string: "https://villa-banners-sg.s3-ap-southeast-1.amazonaws.com/verticalBanners/305x397-Coolhaus.jpg")!)
.resizable()
.scaledToFit()
}
}
func searchIconsSection(g:GeometryProxy)-> some View {
VStack{
Text("Filter by categories")
.font(.title)
FilterIconsNavigationLinkTable(isOdd: true)
.environment(\.managedObjectContext, self.moc)
FilterIconsNavigationLinkTable(isOdd: false)
.environment(\.managedObjectContext, self.moc)
}
}
func scrollingBanner(g:GeometryProxy)-> some View {
ScrollView(.horizontal){
HStack(spacing: 10) {
ForEach(self.bannerList, id: \.self){ imName in
Image(uiImage: UIImage(named: imName)!.resizedImage(targetSize: CGSize(width: 400, height: 400)))
}
}
.padding(.leading, 10)
}.frame(height: 190)
}
func villaLogo(g: GeometryProxy)-> some View {
KFImage(URL(string: "https://villa-images-sg.s3-ap-southeast-1.amazonaws.com/villaHeader.png")!)
.resizable()
.scaledToFit()
.background(Color.white)
}
func icons(label:String, image:UIImage, activated:Bool)-> some View {
ZStack(alignment: .bottom){
Rectangle()
.foregroundColor(.blue)
.cornerRadius(10)
.frame(width: 60, height: 30)
.opacity(activated ? 0.8:0.2)
VStack{
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(width: 60, height: 40)
Text(label)
.font(.system(size: 10))
.allowsTightening(true)
.minimumScaleFactor(0.5)
.lineLimit(2)
.frame(width: 60, height: 30)
}
}
}
func recommendedProductChoices(g: GeometryProxy)-> some View{
// let activated:Bool = false
let catLabels = ["Highlight","Bestsellers","Promotions","Seasonal"]
let catImages = [#imageLiteral(resourceName: "bestSeller-1"),#imageLiteral(resourceName: "bestseller"),#imageLiteral(resourceName: "promotion"),#imageLiteral(resourceName: "seasonal")]
// var currentCat = "Highlight"
return VStack{
HStack{
ForEach(0..<catLabels.count, id: \.self){ id in
Button(action: {
self.currentCatLabel = catLabels[id]
}, label: {
self.icons(label: catLabels[id], image: catImages[id], activated: self.currentCatLabel == catLabels[id])
})
.padding()
}
}
.buttonStyle(PlainButtonStyle())
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false),cat1: self.currentCatLabel == "Highlight" ? "147694":"" ,cat2: "", width: g.size.width, isSingleProduct: false)
}
}
func recommendedProducts(g: GeometryProxy)-> some View {
VStack{
Text("Highlight")
.font(.title)
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false),cat1: "147694",cat2: "", width: g.size.width, isSingleProduct: false)
.padding(.vertical, 20)
Text("Bestsellers")
.font(.title)
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(false), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false),cat1: "",cat2: "", width: g.size.width, isSingleProduct: false)
Text("Promotions")
.font(.title)
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(false), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false) ,cat1: "38153",cat2: "", width: g.size.width, isSingleProduct: false)
}
}
func searchTab(g: GeometryProxy)-> some View{
NavigationLink(destination: SearchViewController(mainCatID: -1).environment(\.managedObjectContext, self.moc)) {
HStack {
Image("searchIcon")
.renderingMode(.original)
.resizable()
.scaledToFit()
.padding(.horizontal)
Text("All Products")
.font(.headline)
.padding(.horizontal)
Spacer()
}
}
.buttonStyle(PlainButtonStyle())
.frame(width: g.size.width , height: 40, alignment: .leading)
}
func seperationLine(g:GeometryProxy)-> some View {
Rectangle()
.frame(width: g.size.width, height: 2, alignment: .center)
.foregroundColor(Color(.systemGray6))
}
}
#if DEBUG
struct ProductsTable_Previews: PreviewProvider {
static var previews: some View {
return Group {
HomeView()
.environment(\.colorScheme, .dark)
}
.environment(\.managedObjectContext, SampleProductCore.context)
.environmentObject(ProductCategoryList(productCategory: SampleCategory.category))
}
}
#endif
<file_sep>/Villa2/CoreData/Categories+CoreDataProperties.swift
//
// Categories+CoreDataProperties.swift
// Villa2
//
// Created by <NAME> on 3/25/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//
import Foundation
import CoreData
extension Categories {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Categories> {
return NSFetchRequest<Categories>(entityName: "Categories")
}
@NSManaged public var categoryList: Data?
public var decodedCategoryList:ProductCategory? {
get {
if let data = categoryList{
return decodeData(responseType: ProductCategory.self, data: data)
} else {
debugPrint("categoryList is empty")
return nil
}
}
set(inputData) {
if let data = encodeData(data: inputData){
self.categoryList = data
debugPrint("categories written to core data")
} else {
debugPrint("encodingDataFailed")
}
}
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewController/SideBar/ButtonStyle/SeachSideViewIconsButtonStyle.swift
//
// SeachSideViewButtonStyle.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import KingfisherSwiftUI
struct SideIconsButtonStyle: ButtonStyle {
var activated:Bool
var width:CGFloat
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.background(configuration.isPressed ? Color.red : self.activated ? Color.red:Color.gray)
.cornerRadius(10)
// .frame(width: self.width)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewNavigation/NavigationBarItems/SearchViewNavigationBarTrailingItems.swift
//
// SearchViewNavigationBarTrailingItems.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct SearchViewNavigationBarTrailingItems: View {
@Environment(\.managedObjectContext) var moc
@EnvironmentObject var catList:ProductCategoryList
@Binding var searchBar: Bool
// init(){
// UINavigationBar.appearance().height
// }
var body: some View {
HStack{
// SearchBar(text: self.$filter, showCat: self.$showCat, sidebar: self.$sidebar,disableImageAnimation: self.$disableImageAnimation, resultLimit: self.$resultLimit, isSearching: self.$isSearching)
// .gesture(drag)
// ScrollView(.horizontal, showsIndicators: false) {
// HStack{
// ForEach(0...5, id: \.self){
// Text("\($0)")
// }
// }
// }
Image(systemName: "magnifyingglass")
.onTapGesture {
self.searchBar.toggle()
}
.padding()
NavigationLink(destination:
CartView()
.environment(\.managedObjectContext, self.moc)
, label: {
GoToCartButton(isCheckout: .constant(false), showModal: .constant(false))
})
}
}
}
struct SearchViewNavigationBarTrailingItems_Previews: PreviewProvider {
static var previews: some View {
SearchViewNavigationBarTrailingItems(searchBar: .constant(false))
}
}
<file_sep>/Villa2/CoreData/ProductCore+CoreDataClass.swift
//
// ProductCore+CoreDataClass.swift
// Villa2
//
// Created by <NAME> on 3/28/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//
import Foundation
import CoreData
@objc(ProductCore)
public class ProductCore: NSManagedObject {
}
<file_sep>/Villa2/View/Observables/CurrentUser.swift
//
// User.swift
// swiftuiHE
//
// Created by <NAME> on 3/10/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct UserInfo{
var name:String?
var age:Int?
var isLoggedIn:Bool
var address:String = ""
}
class CurrentUser:ObservableObject {
@Published var userInfo:UserInfo
init(isLoggedIn:Bool, name:String?){
self.userInfo = UserInfo(name: name, isLoggedIn: isLoggedIn)
}
init(){
self.userInfo = SampleCurrentUser.userInfo
}
var isLoggedIn:Bool {
get {
return self.userInfo.isLoggedIn
}
set (newValue){
self.userInfo.isLoggedIn = newValue
}
}
var name:String? {
get {
return self.userInfo.name
}
set(newValue) {
self.userInfo.name = newValue
}
}
var age:Int? {
get {
return self.userInfo.age
}
set (newValue){
self.userInfo.age = newValue
}
}
}
class PresentationStatus:ObservableObject {
@Published var profile = false
}
class SampleCurrentUser{
static var userInfo:UserInfo = UserInfo(name: "nic", isLoggedIn: true, address: "Two E 55th St, New York, NY 10022")
static var user: CurrentUser {
get {
return CurrentUser(isLoggedIn: SampleCurrentUser.userInfo.isLoggedIn, name: SampleCurrentUser.userInfo.name)
}
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewController/TopBar/MainCatSearchIcons.swift
//
// SearchTopFilterTableView.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import CoreData
struct MainCatSearchIcons: View{
var mainCat:[ProductCategory]
@Binding var currentCat: Int
@Binding var currentSubCat: Int
@Binding var sidebar:Bool
@Binding var resultLimit:Int
var body: some View {
ScrollView([.horizontal], showsIndicators: false){
HStack(spacing: 10) {
// all wildcard
Group {
Button(action :{
self.currentCat = -1
self.currentSubCat = -1
self.sidebar = false
self.incrementalIncreaseProducts()
}){
VStack{
Image("all")
.resizable()
.scaledToFit()
.frame(width:30,height:30)
Text("All")
.font(.system(size: 10))
.allowsTightening(true)
.minimumScaleFactor(0.5)
.lineLimit(2)
.frame(width: 30, height: 10)
}
// Text("All")
// .font(.headline)
// .frame(height: 30)
// .padding()
}
.buttonStyle(TopIconsButtonStyle(activated: -1 == self.currentCat))
}
ForEach(0..<self.mainCat.count, id: \.self){catId in
Group {
if self.mainCat[catId].isActive && self.mainCat[catId].name != "Gourmet" {
Button(action :{
self.currentCat = catId
self.currentSubCat = -1
self.sidebar = true
self.incrementalIncreaseProducts()
}){
VStack{
Image(uiImage: UIImage(named: self.mainCat[catId].name) ?? UIImage(named: "Grocery")!)
.resizable()
.scaledToFit()
.frame(width: 30, height: 30)
Text(self.mainCat[catId].name)
.font(.system(size: 10))
.allowsTightening(true)
.minimumScaleFactor(0.5)
.lineLimit(2)
.frame(width: 30, height: 10)
}
}
.buttonStyle(TopIconsButtonStyle(activated: catId == self.currentCat))
}
}
}
}.frame(height: 50)
}//.frame(width: 250)
}
private func incrementalIncreaseProducts(){
self.resultLimit = 20
}
}
<file_sep>/Villa2/API/MagentoApi.swift
//
// MagentoApi.swift
// Villa2
//
// Created by <NAME> on 3/24/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//import Foundation
//
// MagentoApi.swift
// VillaCoreData
//
// Created by <NAME> on 3/22/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import Kingfisher
class MagentoApi{
class func getProducts(page:Int)->ProductsCodable?{
let endpoint = MagentoApi.Endpoints.products(String(page))
let url = endpoint.url
let semaphore = DispatchSemaphore(value: 0)
var products: ProductsCodable?
guard url != nil else {
debugPrint("invalid url")
return nil
}
MagentoApi.taskForGETMagento(url: url!, responseType: ProductsCodable.self) { (p, e) in
guard e == nil else {
debugPrint("error fetching data", e?.localizedDescription ?? "")
return
}
products = p
semaphore.signal()
debugPrint("getProduct recieved response")
}
_ = semaphore.wait(timeout: .distantFuture)
return products
}
class func getCategories()->ProductCategory?{
let endpoint = MagentoApi.Endpoints.categories
let url = endpoint.url
let semaphore = DispatchSemaphore(value: 0)
var categories: ProductCategory?
guard url != nil else {
debugPrint("invalid url")
return nil
}
MagentoApi.taskForGETMagento(url: url!, responseType: ProductCategory.self) { (p, e) in
guard e == nil else {
debugPrint("error fetching data", e?.localizedDescription ?? "")
return
}
categories = p
semaphore.signal()
debugPrint("getCategory recieved api response")
}
_ = semaphore.wait(timeout: .distantFuture)
return categories
}
enum Endpoints {
static let base = "https://dwdqzrgarxx36.cloudfront.net/rest/V1"
// static let imageBase = "https://dwdqzrgarxx36.cloudfront.net/pub/media/catalog/product"
// https://villa-images-sg.s3-ap-southeast-1.amazonaws.com/imageBySku/0056383
static let imageSku = "https://villa-images-sg.s3-accelerate.amazonaws.com/imageBySku/"
static let imageBase = "https://villa-images-sg.s3-accelerate.amazonaws.com"
static let imageSlow = "https://villa-images-sg.s3-ap-southeast-1.amazonaws.com"
static let alternativeImageBase = "https://dwdqzrgarxx36.cloudfront.net/pub/media/catalog/product"
static let categoriesUrl = "https://dwdqzrgarxx36.cloudfront.net/rest/V1/categories"
// static let apiKeyParam = "?api_key=\(TMDBClient.apiKey)"
case products(String)
case image(String)
case categories
case alternativeImage(String)
var stringValue: String {
switch self {
case .alternativeImage(let imageUrl): return Endpoints.alternativeImageBase + imageUrl
case .products(let page): return Endpoints.base + "/products?searchCriteria[pageSize]=100&searchCriteria[currentPage]=\(page)"
case .image(let imageUrl): return Endpoints.imageSku + imageUrl
case .categories: return Endpoints.categoriesUrl
}
}
var url: URL? {
if let url = URL(string: stringValue) {
return url
} else {
debugPrint("error parsing url", stringValue)
return nil
}
}
}
/// download images ///
class func getMagentoImage(imageUrlString:String, sku:String , completion : @escaping (UIImage?, String)->Void){
let endpoint = MagentoApi.Endpoints.image(imageUrlString)
let url = endpoint.url
MagentoApi.downloadImage(url: url!) { (downloadedImage) in
if let downloadedImage = downloadedImage {
completion(downloadedImage, sku)
} else {
debugPrint("magento borderless images not found")
// get alternative image
let alternativeEndpoint = MagentoApi.Endpoints.alternativeImage(imageUrlString)
let alternativeUrl = alternativeEndpoint.url
if let alternativeUrl = alternativeUrl {
debugPrint("calling to the url", alternativeUrl)
MagentoApi.downloadImage(url: alternativeUrl) { (downloadedImage) in
if let downloadedImage = downloadedImage {
completion(downloadedImage, sku)
}
}
} else {
debugPrint("error parsing image url")
}
}
completion(nil, sku)
}
}
class func downloadImage(url:URL , completion : @escaping (UIImage?)->Void){
let resource = ImageResource(downloadURL: url)
KingfisherManager.shared.retrieveImage(with: resource, options: nil, progressBlock: nil) { result in
switch result {
case .success(let value):
print("Image: \(value.image). Got from: \(value.cacheType)")
completion(value.image as UIImage)
case .failure(let error):
print("Error: \(error)")
completion(nil)
}
}
}
///
class func taskForGETMagento<ResponseType: Decodable>(url: URL, responseType: ResponseType.Type, completion: @escaping (ResponseType?, Error?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(CredentialsApi.magentoApiKey, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
DispatchQueue.main.async {
completion(nil, error)
}
return
}
let decoder = JSONDecoder()
do {
let responseObject = try decoder.decode(ResponseType.self, from: data)
completion(responseObject, nil)
} catch {
debugPrint("error parsing object", error)
do {
let errorResponse = try decoder.decode(MagentoError.self, from: data) as Error
completion(nil, errorResponse)
} catch {
debugPrint("error parsing error response", data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? String
if let json = json {
// let index = json.index(json.startIndex, offsetBy: 10)
debugPrint("json received")
debugPrint(json)
} else {
debugPrint("json received but slicing error")
}
completion(nil, error)
} catch {
debugPrint("data is not json", error)
completion(nil, error)
}
}
}
}
task.resume()
}
}
//struct MagentoApi_Previews: PreviewProvider {
// static var previews: some View {
// /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
// }
//}
<file_sep>/Villa2/View/Observables/ProductRaw.swift
//
// Product.swift
// villaEcommerce
//
// Created by <NAME> on 1/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import UIKit
struct ProductRaw: Hashable{
let name:String
var image:UIImage{
didSet {
if self.image != #imageLiteral(resourceName: "Apple"){
NotificationCenter.default.post(name: Notification.Name("download\(self.sku)"), object: nil)
}
}
}
let price:Float
let sku:String
// var id = UUID()
let category:String?
var categoryIds:[String]? = []
let description:String?
var isFavourite:Bool = false
var isRecommended:Bool = false
var isInHistory:Bool = false
var imageURL:String?
var rankingScore:Float = 0
var metaKeywords: String?
var specialPrice:Float?
var quantityInCart:Int = 0
var priceDescription : String {
get{
"฿ \(String(format: "%.2f" ,price))"
}
}
var isInCart:Bool {
return self.quantityInCart > 0
}
func hash(into hasher: inout Hasher) {
hasher.combine(sku)
}
}
<file_sep>/Villa2/View/tabViewElements/Tabs.swift
//
// TabsView.swift
// tabBarControllerDemo
//
// Created by <NAME> on 3/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct Tab1View: View {
var body: some View {
HomeViewNavigationController()
}
}
struct Tab2View: View {
var body: some View {
SearchViewNavigationController()
}
}
struct Tab3View: View {
var body: some View {
Text("chat View")
}
}
struct Tab4View: View {
var body: some View {
// CartView()
Text("Tab4")
}
}
#if DEBUG
struct TabsView_Previews: PreviewProvider {
static var previews: some View {
Group{
Tab1View()
.previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro Max"))
Tab1View()
.environment(\.colorScheme, .dark)
Tab2View()
Tab3View()
Tab4View()
}
.previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro"))
.environmentObject(CurrentUser(isLoggedIn: false, name: "stamp"))
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(RootGeometry(geometry: nil))
.environmentObject(PresentationStatus())
.environmentObject(TabStatus())
}
}
#endif
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewNavigation/SearchViewNavigationController.swift
//
// Tab2View.swift
// Villa2
//
// Created by <NAME> on 3/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct SearchViewNavigationController: View {
var body: some View {
return
NavigationView{
SearchViewController()
.onTapGesture {
UIApplication.shared.endEditing()
}
}
}
}
struct SearchViewNavigationController_Previews: PreviewProvider {
// let productCat = ProductCategoryList(productCategory: SampleCategory.category)
static var previews: some View {
Group {
NavigationView{
SearchViewController()
}
.environment(\.colorScheme, .dark)
NavigationView{
SearchViewController()
}
.environment(\.colorScheme, .light)
}
.environmentObject(ProductCategoryList(productCategory: SampleCategory.category))
.environmentObject(ShowProductModal())
.environment(\.managedObjectContext, SampleProductCore.context)
.background(Color(.systemBackground))
.previewLayout(.sizeThatFits)
}
}
extension UINavigationController {
override open func viewDidLoad() {
super.viewDidLoad()
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.95)
appearance.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 30)]
let standardAppearance = UINavigationBarAppearance()
standardAppearance.configureWithTransparentBackground()
standardAppearance.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.90)
standardAppearance.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 30)]
// update the appearance
navigationBar.standardAppearance = standardAppearance
navigationBar.scrollEdgeAppearance = standardAppearance
navigationBar.compactAppearance = appearance
}
}
<file_sep>/Villa2/SigninWithAppleContents/WebApi.swift
import Foundation
struct WebApi {
static func Register(user: UserData, identityToken: Data?, authorizationCode: Data?) throws -> Bool {
return true
}
}
<file_sep>/Villa2/View/Tab1HomeView/NavigationBar/HomeViewNavigationBarTrailingItems.swift
//
// NavigationBarTrailingItems.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct HomeViewNavigationBarTrailingItems: View {
@EnvironmentObject var user:CurrentUser
@EnvironmentObject var productList:ProductList
@EnvironmentObject var tabStatus:TabStatus
@Environment(\.managedObjectContext) var moc
var body: some View {
HStack{
if user.isLoggedIn {
Button(action: {
self.user.isLoggedIn.toggle()
}){
Text("Logout")
}
}
NavigationLink(destination:
CartView()
.environment(\.managedObjectContext, moc)
) {
GoToCartButton(isCheckout: .constant(false), showModal: .constant(false))
.environment(\.managedObjectContext, moc)
}
}
}
}
struct NavigationBarTrailingItems_Previews: PreviewProvider {
static var previews: some View {
Group {
HomeViewNavigationBarTrailingItems()
.environmentObject(SampleCurrentUser.user)
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(TabStatus())
.background(Color(.systemBackground))
.environment(\.colorScheme, .light)
.previewLayout(.sizeThatFits)
HomeViewNavigationBarTrailingItems()
.environmentObject(SampleCurrentUser.user)
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(TabStatus())
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewLayout(.sizeThatFits)
}
}
}
<file_sep>/Villa2/bin/ProductImageBackground.swift
////
//// ProductImageBackground.swift
//// Villa2
////
//// Created by <NAME> on 3/14/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct ProductImageBackground: View {
// var width:CGFloat
// var body: some View {
// Color(UIColor.systemBackground)
// .opacity(0.0)
// .frame(width: self.width+5 , height: self.width+5 )
// .clipShape(
// RoundedRectangle(cornerRadius: width/7)
// )
//// .padding(10)
// .overlay(
// RoundedRectangle(cornerRadius: width/7)
// .stroke(Color.green.opacity(0.0), lineWidth: 5)
// )
//// .shadow(radius: 1)
// }
//}
//
//struct ProductImageBackground_Previews: PreviewProvider {
// static var previews: some View {
// Group {
// ProductImageBackground(width: 50)
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
//
//
// ProductImageBackground(width: 50)
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .light)
// .previewLayout(.sizeThatFits)
// }
//
// }
//}
<file_sep>/Villa2/bin/InnerProductImage.swift
////
//// InnerProductImage.swift
//// Villa2
////
//// Created by <NAME> on 3/14/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct InnerProductImage: View {
// var product:ProductRaw
// var width:CGFloat
// var body: some View {
// Image(uiImage: self.product.image)
// .resizable()
// .renderingMode(.original)
// .frame(width: self.width, height: self.width)
//// .foregroundColor(.purple)
// .padding()
// }
//}
//
//struct InnerProductImage_Previews: PreviewProvider {
// static var previews: some View {
// Group {
// InnerProductImage(product: SampleProductList.products[1], width: 30)
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
// InnerProductImage(product: SampleProductList.products[1], width: 30)
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .light)
// .previewLayout(.sizeThatFits)
// }
// }
//}
<file_sep>/Villa2/View/SettingsView/ProfilePage.swift
//
// ProfilePage.swift
// swiftuiHE
//
// Created by <NAME> on 3/10/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct ProfilePage: View {
@EnvironmentObject var user:CurrentUser
var body: some View {
VStack{
ProfileImage()
.environmentObject(self.user)
HStack{
Text("Name:")
.padding()
Spacer()
Text(user.name ?? "")
.padding()
Spacer()
}
.font(.largeTitle)
HStack{
Text("Age:")
.padding()
Spacer()
Text("\(user.age ?? 0)")
.padding()
Spacer()
}
.font(.largeTitle)
}
}
}
struct ProfileImage: View{
@EnvironmentObject var user:CurrentUser
var body: some View {
GeometryReader { geometry in
Image("imagemock")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geometry.size.width - 80, height: geometry.size.width, alignment: .center)
.padding(.all, 20)
.clipShape(Circle())
.shadow(radius: 10)
.overlay(Circle().stroke(Color.gray, lineWidth: 15))
}
}
}
#if DEBUG
struct ProfilePage_Previews: PreviewProvider {
static var previews: some View {
Group {
ProfilePage()
.environmentObject(CurrentUser(isLoggedIn: true, name: "nic"))
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
ProfilePage()
.environmentObject(CurrentUser(isLoggedIn: true, name: "nic"))
.background(Color(.systemBackground))
.environment(\.colorScheme, .light)
}
}
}
#endif
<file_sep>/Villa2/View/Modifiers/TextModifier/ListTextTitleViewModifier.swift
//
// ListTextTitleViewModifier.swift
// Villa2
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import CoreData
struct ListTextTitleViewModifier: ViewModifier {
func body(content: Content) -> some View {
content
.font(.headline)
.lineLimit(1)
.frame(width: 100,alignment: .leading)
}
}
<file_sep>/Villa2/bin/SmallProductCell.swift
//
//import SwiftUI
//
//struct SmallProductCell: View {
// @EnvironmentObject var rootGeometry:RootGeometry
// @EnvironmentObject var productList:ProductList
// @State var product:ProductRaw
//
//
// var body: some View {
//
// let quantity = Binding<Int>(get: {
// return self.productList.getQuantityInCart(sku: self.product.sku)
//
// },
// set: {
// self.productList.setQuantityInCart(sku: self.product.sku, quantity: $0)
// debugPrint("quantity in cart is set to:", $0)
// debugPrint("test getting product quantity:", self.productList.getQuantityInCart(sku: self.product.sku))
//
// })
//
//
// return GeometryReader{ g in
// HStack(alignment: .top){
//
// VStack(alignment: .center){
// // product image
// Button(action: {
// }){
// ProductImage(overrideWidth: Float(g.size.width/8) ,product: self.product)
// .frame(width: g.size.width/4)
// .scaledToFit()
//
// }
// .buttonStyle(BorderlessButtonStyle())
//
//
// HStack{
//
// // all button suite
// ProductQuantityButton(product: self.product, quantity: quantity)
// .padding()
// .animation(nil)
//
//
//
// //add item to favourite
// // Button(action: {
// // self.product.isFavourite.toggle()
// // }){
// // Image(systemName: product.isFavourite ? "star":"star.fill")
// // }
// // .padding()
// // .buttonStyle(BorderlessButtonStyle())
//
//
// }
// }
//
// // product description and button
// ProductDescription(product: self.$product, quantity: quantity)
// // .environmentObject(self.rootGeometry)
// // .environmentObject(self.productList)
// }
// }
//
// }
//
// private func imageWidth()->CGFloat{
// return (self.rootGeometry.geometry?.size.width ?? 300) / 3
// }
//}
//
//struct SmallProductCell_Previews: PreviewProvider {
// static var previews: some View {
// Group{
// SmallProductCell(product: SampleProductList.products[0])
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
//
// SmallProductCell(product: SampleProductList.products[1])
// .previewLayout(.sizeThatFits)
//
// SmallProductCell(product: SampleProductList.products[0])
// .previewLayout(.sizeThatFits)
//
// }
// .environmentObject(SampleProductList.productList)
// .environmentObject(RootGeometry(geometry: nil))
// .previewLayout(.sizeThatFits)
// }
//}
<file_sep>/Villa2/CoreData/CatLinearCore+CoreDataClass.swift
//
// CatLinearCore+CoreDataClass.swift
// Villa2
//
// Created by <NAME> on 3/31/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CatLinearCore)
public class CatLinearCore: NSManagedObject {
}
<file_sep>/Villa2/View/SettingsView/StoreSelector.swift
//
// StoreSelector.swift
// Villa2
//
// Created by <NAME> on 5/8/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct StoreSelector: View {
let storeList:[DefaultStore.storeLocation] = [.bangkok, .huahin, .phuket, .others]
let storeDescriptionList:[String] = ["Bangkok", "HuaHin", "Phuket", "Others"]
@Binding var isDisplayed:Bool
init(isDisplayed:Binding<Bool>){
self._isDisplayed = isDisplayed
}
var body: some View {
VStack{
Text("Which store would you like to shop in?")
.font(.headline)
.bold()
.padding()
ForEach(0..<storeList.count){ i in
Button(action: {
DefaultStore.currentStore = self.storeList[i]
self.dismissDisplay()
}) {
Text(self.storeDescriptionList[i])
.font(.callout)
}
.buttonStyle(BorderlessButtonStyle())
.foregroundColor(.gray)
.frame(width: 100, height: 50, alignment: .center)
.overlay(Capsule().stroke(lineWidth: 5).foregroundColor(.blue).opacity(0.5))
.padding()
}
}
.onAppear{
self.dismissDisplay()
}
}
func dismissDisplay (){
if let currentStore = DefaultStore.currentStore{
debugPrint(currentStore)
self.isDisplayed = false
}
}
}
struct StoreSelector_Previews: PreviewProvider {
static var previews: some View {
StoreSelector(isDisplayed: .constant(true))
}
}
<file_sep>/Villa2/View/Modifiers/ImageModifier/ImageModifier.swift
//
// ImageModifier.swift
// Villa2
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
protocol ImageModifier {
/// `Body` is derived from `View`
associatedtype Body : View
/// Modify an image by applying any modifications into `some View`
func body(image: Image) -> Self.Body
}
extension Image {
func modifier<M>(_ modifier: M) -> some View where M: ImageModifier {
modifier.body(image: self)
}
}
<file_sep>/Villa2/CoreData/ProductCoreWrapper.swift
//
// ProductCoreWrapper.swift
// Villa2
//
// Created by <NAME> on 4/3/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
class ProductCoreWrapper:ObservableObject{
@Published var productCore:ProductCore
init(productCore:ProductCore){
self.productCore = productCore
}
}
<file_sep>/Villa2/CoreData/CatLinearCore+CoreDataProperties.swift
//
// CatLinearCore+CoreDataProperties.swift
// Villa2
//
// Created by <NAME> on 3/31/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//
import Foundation
import CoreData
extension CatLinearCore {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CatLinearCore> {
return NSFetchRequest<CatLinearCore>(entityName: "CatLinearCore")
}
@NSManaged public var id: Int16
@NSManaged public var parentId: Int16
@NSManaged public var name: String?
@NSManaged public var position: Int16
@NSManaged public var level: Int16
@NSManaged public var children: String?
@NSManaged public var includeInMenu: Bool
}
<file_sep>/Villa2/View/Modifiers/PreviewModifier/DarkSubViewPreviewModifier.swift
//
// SuperPreviewModifier.swift
// Villa2
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import CoreData
struct DarkSubViewPreviewModifier: ViewModifier {
var context:NSManagedObjectContext
func body(content: Content) -> some View {
content
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewLayout(.sizeThatFits)
.environment(\.managedObjectContext, context)
}
}
<file_sep>/Villa2/View/SettingsView/MenuView.swift
//
// SideMenuView.swift
// swiftuiHE
//
// Created by <NAME> on 3/10/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct MenuView: View {
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var user: CurrentUser
@EnvironmentObject var presentation: PresentationStatus
var body: some View {
NavigationView{
VStack(alignment: .leading) {
NavigationLink(destination: ProfilePage().environmentObject(self.user)) {
HStack {
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Profile")
.foregroundColor(.gray)
.font(.headline)
Spacer()
}
}
.padding()
NavigationLink(destination: DeliveryLocation(isDisplayed: .constant(true))) {
HStack {
Image(systemName: "map")
.foregroundColor(.gray)
.imageScale(.large)
Text("Delivery Location")
.foregroundColor(.gray)
.font(.headline)
Spacer()
}
}
.padding()
NavigationLink(destination: StoreFinder()) {
HStack {
Image("store")
.modifier(IconsModifier())
.foregroundColor(.gray)
.imageScale(.large)
Text("Store Finder")
.foregroundColor(.gray)
.font(.headline)
Spacer()
}
}
.padding()
NavigationLink(destination: ProfilePage()) {
HStack {
Image(systemName: "envelope")
.foregroundColor(.gray)
.imageScale(.large)
Text("Messages")
.foregroundColor(.gray)
.font(.headline)
}
}
.padding()
NavigationLink(destination: ProfilePage()) {
HStack {
Image(systemName: "gear")
.foregroundColor(.gray)
.imageScale(.large)
Text("Settings")
.foregroundColor(.gray)
.font(.headline)
}
}
.padding()
Spacer()
}
.navigationBarTitle("Settings")
}
}
}
struct MenuView_Previews: PreviewProvider {
static var previews: some View {
MenuView()
}
}
<file_sep>/Villa2/View/HelperViews/Buttons/AddToCartButton.swift
//
// AddToCartButton.swift
// Villa2
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct AddToCartButton: View {
@Binding var quantityInCart: Int
var width: CGFloat
var body: some View {
ZStack(alignment: .leading){
HStack(alignment: .center) {
// remove button
Button(action: {
// Actions
self.quantityInCart += 1
}) {
Text(self.width > 100 ? "Add to Cart": "Add")
.frame(height: self.width/3)
}
}
.onTapGesture {
self.quantityInCart += 1
}
.buttonStyle(BorderlessButtonStyle())
.frame(width: width, height: 33, alignment: .center)
.padding(.horizontal)
.overlay(Capsule().stroke(
Color.blue.opacity(0.5),lineWidth: 5)
)
}
}
}
struct AddToCartButton_Previews: PreviewProvider {
static var previews: some View {
AddToCartButton(quantityInCart: .constant(2), width: 100)
}
}
<file_sep>/Villa2/bin/ProductDescription.swift
////
//// ProductDescription.swift
//// Villa2
////
//// Created by <NAME> on 3/13/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct ProductDescription: View {
// @EnvironmentObject var rootGeometry:RootGeometry
// @EnvironmentObject var productList:ProductList
//
// @Binding var product: ProductRaw
// @Binding var quantity: Int
//
// var body: some View {
//
// VStack(alignment:.leading){
// Text(product.name)
// .font(.headline)
// .padding(.leading)
// .padding(.trailing)
// .animation(nil)
//
//
// Text("\(product.description ?? "") " + String(repeating: " ", count: 100))
// .font(.body)
// .lineLimit(5)
// .padding(.leading)
// .padding(.trailing)
// .animation(nil)
//
// //// the control buttons
//// HStack{
////
//// // all button suite
//// ProductQuantityButton(product: $product, quantity: $quantity)
//// .environmentObject(productList)
//// .padding()
////
////
//// //add item to favourite
//// Button(action: {
//// self.product.isFavourite.toggle()
//// }){
//// Image(systemName: product.isFavourite ? "star":"star.fill")
//// }
//// .padding()
//// .buttonStyle(BorderlessButtonStyle())
//// // remove item from cart
////// Button(action: {
////// self.product.quantityInCart = 0
////// }){
////// Image(systemName: "trash")
////// }
////// .padding()
////// .buttonStyle(BorderlessButtonStyle())
////
//// }
//
//
// }
//// .frame(maxHeight: self.maxHeight())
// }
//
// private func maxHeight()->CGFloat{
// return (self.rootGeometry.geometry?.size.width ?? 300) / 3
// }
//}
//
//#if DEBUG
//
//struct ProductDescription_Previews: PreviewProvider {
// static var previews: some View {
// Group {
// ProductDescription(product: .constant(SampleProductList.products[0]), quantity: .constant(5))
//
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
//
// ProductDescription(product: .constant(SampleProductList.products[0]), quantity: .constant(5))
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .light)
// .previewLayout(.sizeThatFits)
// }
// .environmentObject(RootGeometry(geometry: nil))
// .environmentObject(SampleProductList.productList)
//
// }
//}
//#endif
<file_sep>/Villa2/View/tabViewElements/TabBarControllerView.swift
//
// ContentView.swift
// tabBarControllerDemo
//
// Created by <NAME> on 3/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct TabBarControllerView: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
// @Environment(\.window) var window: UIWindow?
//Getting number of products
@EnvironmentObject var user:CurrentUser
var numberOfProducts:Int{
var totalProducts = 0
for product in productCores{
totalProducts += product.quantityInCart
}
return totalProducts
}
var fetchRequest: FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
init(){
//get number of products in cart form coredata
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = 100
let predicate = NSPredicate(format: "isInCart == TRUE")
request.predicate = predicate
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
}
var body: some View {
return ZStack {
UITabBarWrapper([
TabBarElement(tabBarElementItem: .init(title: "First", image: UIImage(systemName: "house.fill")!)) {
Tab1View()
},
// TabBarElement(tabBarElementItem: .init(title: "Second", image: UIImage(systemName: "rectangle.3.offgrid")!)) {
// Tab2View()
// },
// TabBarElement(tabBarElementItem: .init(title: "Chat", image: UIImage(systemName: "message")!)) {
// Tab3View()
// },
TabBarElement(tabBarElementItem: .init(title: "Wallet", image: UIImage(systemName: "creditcard.fill")!, badge: 5.string)) {
WalletMainView()
},
TabBarElement(tabBarElementItem: .init(title: "Settings", image: UIImage(systemName: "gear")!)) {
MenuView()
.environmentObject(self.user)
},
])
.edgesIgnoringSafeArea(.all)
}
}
}
struct TabBarControllerView_Previews: PreviewProvider {
static var previews: some View {
Group{
TabBarControllerView()
.previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro Max"))
TabBarControllerView()
.previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro Max"))
.environment(\.colorScheme, .dark)
}
.environmentObject(SampleProductList.productList)
.environmentObject(RootGeometry(geometry: nil))
.environmentObject(CurrentUser(isLoggedIn: false, name: "stamp"))
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(PresentationStatus())
.environment(\.colorScheme, .dark)
.environmentObject(TabStatus())
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewProductTable/ProductCoreTableCell.swift
//
// ProductCoreTableCell.swift
// Villa2
//
// Created by <NAME> on 3/28/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct ProductCoreTableCell: View {
var product:ProductCore
var width:CGFloat
//cat data
@EnvironmentObject var catList:ProductCategoryList
var mainCat:[ProductCategory] { get {self.catList.products.childrenData[0].childrenData}}
var currentMainCat:ProductCategory? {get {self.mainCat.first { (cat) -> Bool in
return cat.id.string == self.product.cat1 || cat.id.string == self.product.cat2 || cat.id.string == self.product.cat3 || cat.id.string == self.product.cat4
}}}
var currentSubCat:ProductCategory? {
self.currentMainCat?.childrenData.first(where: { (cat) -> Bool in
return cat.id.string == self.product.cat1 || cat.id.string == self.product.cat2 || cat.id.string == self.product.cat3 || cat.id.string == self.product.cat4
})
}
@Binding var disableImageAnimation:Bool
@Binding var sidebar:Bool
@Environment(\.managedObjectContext) var moc
@ObservedObject var productCoreWrapper:ProductCoreWrapper
@Binding var isSearching:Bool
init(product:ProductCore,disableImageAnimation:Binding<Bool>, sidebar:Binding<Bool>, isSearching:Binding<Bool>, width:CGFloat){
let productCoreWrapper = ProductCoreWrapper(productCore: product)
self.productCoreWrapper = productCoreWrapper
self.product = productCoreWrapper.productCore
self._disableImageAnimation = disableImageAnimation
self._sidebar = sidebar
self._isSearching = isSearching
self.width = width
}
// MARK:- main body
var body: some View {
let quantity = Binding<Int>(get: {
return self.product.quantityInCart
},
set: {
self.product.quantityInCart = $0
try? self.moc.save()
})
return VStack(alignment: .leading){
if isSearching{
self.catLabel()
}
HStack(alignment:.top,spacing: 5){
//image and quantity selector
VStack(alignment: .leading) {
self.productImage()
}
.padding(.leading)
//description and price
VStack(alignment: .leading){
self.nameButton()
HStack(alignment: .center){
self.priceLabel()
Spacer()
if !isSearching{
cartOrQuantityButton(quantity: quantity, sideBar: self.sidebar, product: self.product)
}
}
}
}
.font(.system(size: 20, weight: .semibold, design: .default))
}.frame(width: self.width)
}
// MARK: - UIViews
func catLabel()-> some View {
Text("\(self.currentMainCat?.name ?? "") -> \(self.currentSubCat?.name ?? "")")
}
func nameButton()-> some View {
NavigationLink(destination: SingleProductCoreView(product: self.product, showModal: .constant(false))) {
self.nameLabel()
}
.buttonStyle(PlainButtonStyle())
}
func nameLabel()-> some View {
return
HStack{
Text("\(product.name ?? "")")
.font(.system(size: 20))
.lineLimit(2)
.padding(.trailing)
.allowsTightening(true)
Spacer()
}
}
func priceLabel()-> some View {
Text(self.product.priceDescription)
.lineLimit(1)
.allowsTightening(true)
.font(.footnote)
.frame(width:70)
.animation(.easeInOut(duration: 1))
}
func productImage()-> some View {
NavigationLink(destination: SingleProductCoreView(product: self.product, showModal: .constant(false))) {
ProductCoreImage(disableImageAnimation: self.$disableImageAnimation, width: self.isSearching ? 40: 80, productCore: product)
.opacity(1)
.padding(.horizontal)
}
.buttonStyle(PlainButtonStyle())
}
// MARK: - functions
func reloadUI(){
DispatchQueue.main.async {
self.sidebar.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.sidebar.toggle()
}
}
}
}
struct cartOrQuantityButton: View {
@Binding var quantity:Int
var sideBar:Bool
var product:ProductCore
var isInCart:Bool {
self.product.isInCart
}
var body: some View{
HStack{
Spacer()
if !isInCart {
self.addToCartButton(quantity: $quantity)
} else {
self.quantityButton(quantity: $quantity)
}
Spacer()
}
}
func addToCartButton(quantity: Binding<Int>) -> some View {
AddToCartButton(quantityInCart: quantity, width: self.sideBar ? 60 : 120)
.padding(.horizontal, 7.0)
.padding(.top)
}
func quantityButton(quantity: Binding<Int>)-> some View {
ProductCoreQuantityButton(product: self.product, quantity: quantity, width: self.sideBar ? 60 : 120)
.padding(.horizontal, 7.0)
}
}
#if DEBUG
struct ProductCoreTableCell_Previews: PreviewProvider {
static var previews: some View {
let productCore = SampleProductCore.productCore
return Group {
ProductCoreTableCell(product: productCore, disableImageAnimation: .constant(true), sidebar: .constant(false), isSearching: .constant(false), width: 300)
ProductCoreTableCell(product: productCore, disableImageAnimation: .constant(true), sidebar: .constant(false), isSearching: .constant(false), width: 200)
ProductCoreTableCell(product: productCore, disableImageAnimation: .constant(true), sidebar: .constant(false), isSearching: .constant(false), width: 400)
}
.modifier(DarkSubViewPreviewModifier(context: SampleProductCore.context))
}
}
#endif
<file_sep>/Villa2/View/Modifiers/TextModifier/MultilineTextModifier.swift
//
// ListTextDetailViewModifier.swift
// Villa2
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import CoreData
struct MultilineTextModifier: ViewModifier {
func body(content: Content) -> some View {
content
.fixedSize(horizontal: false, vertical: true)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewProductTable/SearchViewProductTable.swift
//
// FormSectionProductTable.swift
// Villa2
//
// Created by <NAME> on 3/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
import KingfisherSwiftUI
struct SearchViewProductTable: View {
@EnvironmentObject var productList:ProductList
@EnvironmentObject var rootGeometry:RootGeometry
@Binding var disableImageAnimation:Bool
@Binding var bindingResultLimit:Int
@Binding var sidebar:Bool
@Binding var isSearching:Bool
var searchBarEmpty:Bool
var fetchRequest:FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
var width: CGFloat
//var for the more button
let filter:String
let resultLimit:Int
let cat1:String
let cat2:String
init(filter: String, disableImageAnimation:Binding<Bool>, resultLimit: Int, bindingResultLimit: Binding<Int>, sidebar: Binding<Bool>, cat1:String, cat2:String, isSearching:Binding<Bool>, width: CGFloat){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = resultLimit
// debugPrint("cat1 is \(cat1), cat2 is \(cat2)")
let cat1Predicate = NSPredicate(format: cat1.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat1,cat1,cat1,cat1)
let cat2Predicate = NSPredicate(format: cat2.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat2,cat2,cat2,cat2)
let searchPredicate = NSPredicate(format: filter.count > 0 ? "(name CONTAINS[c] %@) OR (metaKeywords CONTAINS[c] %@) ":"TRUEPREDICATE", filter.count > 0 ? filter:"*",filter.count > 0 ? filter:"*")
let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [cat1Predicate, cat2Predicate,searchPredicate])
request.predicate = andPredicate
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
self._disableImageAnimation = disableImageAnimation
self._bindingResultLimit = bindingResultLimit
self._sidebar = sidebar
self._isSearching = isSearching
self.filter = filter
self.resultLimit = resultLimit
self.cat1 = cat1
self.cat2 = cat2
self.searchBarEmpty = filter.isEmpty
self.width = width
}
var body: some View {
return
// List{
ScrollView {
VStack(alignment: .leading){
KFImage(URL(string: "https://villa-banners-sg.s3-ap-southeast-1.amazonaws.com/Promotion/lamoon-1-free-1-900x350-eng.jpg")!)
.resizable()
.scaledToFit()
.cornerRadius(10)
.padding(.leading, 40)
.padding(.trailing, 20)
.frame(width: self.width)
.animation(.easeInOut(duration: 1))
ForEach(productCores, id:\.self){ p in
ProductCoreTableCell(product: p,disableImageAnimation: self.$disableImageAnimation,sidebar: self.$sidebar, isSearching: self.$isSearching, width: self.width)
}
}
.frame(minWidth: 200, maxWidth: self.width)
//more button
MoreButton(filter: self.filter, resultLimit: self.resultLimit, bindingResultLimit: self.$bindingResultLimit, cat1: self.cat1, cat2: self.cat2)
}
// .frame(minWidth: 300)
// .frame(width: self.width)
}
}
#if DEBUG
struct FormSectionProductTable_Previews: PreviewProvider {
static var previews: some View {
let context = SampleProductCore.context
return Group{
SearchViewProductTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(100), sidebar: .constant(false),cat1: "",cat2: "", isSearching: .constant(false), width: 400)
.modifier(SubViewPreviewModifier(context: context))
SearchViewProductTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(100), sidebar: .constant(true),cat1: "",cat2: "", isSearching: .constant(false), width: 300)
.modifier(SubViewPreviewModifier(context: context))
SearchViewProductTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(100), sidebar: .constant(false),cat1: "",cat2: "", isSearching: .constant(false), width: 500)
.modifier(SubViewPreviewModifier(context: context))
.previewDevice("IPhone 11 Pro Max")
}
}
}
#endif
<file_sep>/Villa2/View/HelperViews/ProductCoreCollectionView/ProductCoreCollectionViewCell.swift
//
// ProductCell.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct ProductCoreCollectionViewCell: View {
var product:ProductCore
@Binding var disableImageAnimation:Bool
@Binding var sidebar:Bool
@EnvironmentObject var showProductModal:ShowProductModal
@Environment(\.managedObjectContext) var moc
@ObservedObject var productCoreWrapper:ProductCoreWrapper
var isSingleProduct:Bool
@State var showModal:Bool = false
var globalG: GeometryProxy
var imageWidth:CGFloat = 200
init(product:ProductCore,disableImageAnimation:Binding<Bool>, sidebar:Binding<Bool>, imageWidth: CGFloat?, globalG:GeometryProxy, isSingleProduct:Bool){
let productCoreWrapper = ProductCoreWrapper(productCore: product)
self.productCoreWrapper = productCoreWrapper
self.product = productCoreWrapper.productCore
self._disableImageAnimation = disableImageAnimation
self._sidebar = sidebar
if let imageWidth = imageWidth {
self.imageWidth = imageWidth
}
self.globalG = globalG
self.isSingleProduct = isSingleProduct
}
var body: some View {
let quantity = Binding<Int>(get: {
return self.product.quantityInCart
},
set: {
self.product.quantityInCart = $0
try? self.moc.save()
})
return
GeometryReader{ g in
VStack(alignment:.center,spacing: 5){
//image and quantity selector
VStack(alignment: .leading) {
NavigationLink(destination: SingleProductCoreView(product: self.product, showModal: self.$showModal)) {
ProductCoreImage(disableImageAnimation: self.$disableImageAnimation, width: self.imageWidth , productCore: self.product)
.opacity(1)
.rotation3DEffect(.init(degrees: Double(g.frame(in: .global).minX - g.size.width) * 0.05), axis: (x: 0, y: 10, z: 0))
.scaleEffect(self.scaleValue(g: g, globalg: self.globalG))
.padding(.horizontal)
}
.isDetailLink(false)
}
//description and price
VStack(alignment: .center){
Text("\(self.product.name ?? "")")
.lineLimit(3)
.modifier(MultilineTextModifier())
.fixedSize(horizontal: false, vertical: true)
.allowsTightening(true)
.truncationMode(.tail)
.font(.body)
.background(Color(UIColor.systemBackground))
.minimumScaleFactor(0.5)
.onTapGesture {
self.showSingleProduct()
}
.frame(width: self.imageWidth - 20, height: 100)
Text(self.product.priceDescription)
.lineLimit(1)
.allowsTightening(true)
.font(.footnote)
.frame(width: self.imageWidth)
HStack{
if !self.product.isInCart {
AddToCartButton(quantityInCart: quantity, width: self.imageWidth - 70)
.padding(.top, 10)
} else {
ProductCoreQuantityButton(product: self.product, quantity: quantity, width: self.imageWidth - 50)
}
}
}
}
.animation(.easeInOut(duration: 1))
.font(.system(size: 20, weight: .semibold, design: .default))
}
}
func scaleValue(g:GeometryProxy,globalg:GeometryProxy)->CGFloat{
let localMid = g.frame(in: .global).midX
let globalMid = globalg.frame(in: .global).midX
let diff = localMid - globalMid
let isNegative = (localMid - globalMid) < 0
let multiplier:CGFloat = 0.0003
let initial:CGFloat = 1
if isNegative {
return initial - CGFloat(-diff) * multiplier
} else {
return initial - CGFloat(diff) * multiplier
}
}
func scale(g: GeometryProxy)->CGFloat{
let distance = (g.frame(in: .global).minX - g.size.width)
if -80...80 ~= distance{
return 1
} else if -200...200 ~= distance{
return 0.9
} else {
return 0.8
}
}
func showSingleProduct(){
debugPrint("tapped")
if isSingleProduct{
withAnimation(Animation.linear(duration: 1)){
self.showProductModal.product = self.product
}
} else {
}
}
func reloadUI(){
DispatchQueue.main.async {
self.sidebar.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.sidebar.toggle()
}
}
}
}
#if DEBUG
struct ProductCoreCollectionViewCell_Previews: PreviewProvider {
static var previews: some View {
let productCore = SampleProductCore.productCore
return GeometryReader { g in
Group {
ProductCoreCollectionViewCell(product: productCore, disableImageAnimation: .constant(true), sidebar: .constant(false), imageWidth: 200, globalG: g, isSingleProduct: false)
}
.modifier(DarkSubViewPreviewModifier(context: SampleProductCore.context))
}
}
}
#endif
<file_sep>/Villa2/View/Modifiers/ImageModifier/IconsModifier.swift
//
// IconsModifier.swift
// Villa2
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
struct IconsModifier: ImageModifier{
func body(image: Image) -> some View {
image
// .renderingMode(.original)
.resizable()
.scaledToFit()
.frame(width: 30, height: 30, alignment: .center)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewNavigation/NavigationBarItems/SearchViewNavigationBarLeadingItems.swift
//
// NavigationBarLeadingItems.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct SearchViewNavigationBarLeadingItems: View {
// @Binding var sidebar:Bool
@Binding var currentCat: Int
@Binding var currentSubCat: Int
@Binding var sidebar:Bool
@Binding var resultLimit:Int
@EnvironmentObject var catList:ProductCategoryList
var mainCat:[ProductCategory] { get {self.catList.products.childrenData[0].childrenData}}
var body: some View {
HStack{
if self.currentCat != -2 {
MainCatSearchIcons(mainCat: self.mainCat, currentCat: self.$currentCat, currentSubCat: self.$currentSubCat, sidebar: self.$sidebar, resultLimit: self.$resultLimit )
.frame(width: 250)
}
// .gesture(drag)
// Button(action: {self.sidebar.toggle()}){
// Image(systemName: "line.horizontal.3")
// .frame(width: 40, height: 40)
// }
// Button(action: {
// self.deleteAllItems()
// }){
// Image(systemName: "trash")
// }
// .frame(width: 40, height: 40)
//
// Button(action: {
// self.fetchApi()
// }){
// Image(systemName: "gobackward")
// }
// .frame(width: 40, height: 40)
// .buttonStyle(DefaultButtonStyle())
}
// .frame(height:200)
}
}
extension SearchViewNavigationBarLeadingItems{
func fetchApi(){
(UIApplication.shared.delegate as! AppDelegate).persistentContainer.performBackgroundTask { (backgroundContext) in
S3Api.getProductCores(context: backgroundContext)
self.reloadUI()
}
}
func reloadUI(){
DispatchQueue.main.async {
self.sidebar.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
self.sidebar.toggle()
}
}
}
func deleteAllItems(){
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductCore")
// Create Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try moc.execute(batchDeleteRequest)
try moc.save()
moc.reset()
self.reloadUI()
debugPrint("all items deleted")
} catch {
// Error Handling
debugPrint("error deleting and saving")
}
}
}
struct SearchViewNavigationBarLeadingItems_Previews: PreviewProvider {
static var previews: some View {
SearchViewNavigationBarLeadingItems(currentCat: .constant(1), currentSubCat: .constant(1), sidebar: .constant(true), resultLimit: .constant(10))
}
}
<file_sep>/Villa2/View/HelperViews/ModalViewIndicator.swift
//
// ModalViewIndicator.swift
// Villa2
//
// Created by <NAME> on 3/29/20.
// Copyright © 2020 tenxor. All rights reserved.
//
// Credit <NAME>
//https://stackoverflow.com/questions/58493192/is-there-a-standard-way-to-display-a-modal-view-indicator
//
import SwiftUI
struct ModalViewIndicator: View {
var body: some View {
GeometryReader{ g in
HStack{
Spacer()
Image(systemName: "minus")
.resizable()
.font(Font.title.weight(.heavy))
.foregroundColor(Color(UIColor.tertiaryLabel))
.frame(width: g.size.width / 5, height: 10, alignment: .center)
Spacer()
}
// .padding(4)
.padding(.top, 8)
}
.frame( height: 21, alignment: .center)
}
}
struct ModalViewIndicator_Previews: PreviewProvider {
static var previews: some View {
Text("ModalViewIndicator")
.sheet(isPresented: .constant(true)) {
VStack {
ModalViewIndicator()
GeometryReader { geometry in
Image(systemName: "sun.dust.fill")
.resizable()
.frame(
width: geometry.size.width/2,
height: geometry.size.width/2,
alignment: .center
)
}
}
}
}
}
<file_sep>/Villa2/bin/SingleProductView.swift
////
//// SingleProductView.swift
//// Villa2
////
//// Created by <NAME> on 3/13/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct SingleProductView: View {
// @EnvironmentObject var productList:ProductList
// @Binding var productID:Int
//
// var product:ProductRaw{
// get {
// return self.productList.products[self.productID]
// }
// }
// var body: some View {
// var quantity: Binding<Int> = Binding(get: {
// return self.productList.products[self.productID].quantityInCart
// }, set: {
// self.productList.products[self.productID].quantityInCart = $0
// })
//
// return GeometryReader{ g in
// NavigationView{
// Form{
// Section{
// SingleProductImageSection(productID: self.$productID, g: g)
// }
// .frame(alignment: .center)
//
// Section {
// VStack (alignment: .leading) {
// HStack(alignment: .center){
// Text("Name").font(.headline)
// .frame(width: g.size.width/3)
//
// Text(self.product.name)
// .font(.subheadline)
// .frame(width: g.size.width * 2/3, alignment: .leading)
// }
//
// HStack(alignment: .center){
// Text("Price").font(.headline)
// .frame(width: g.size.width/3)
//
// Text(self.product.priceDescription)
// .font(.subheadline)
// .frame(width: g.size.width * 2/3, alignment: .leading)
// }.padding(.vertical)
//
//
//
//
// // product quantity button
// HStack {
// Spacer()
// ProductQuantityButton(product: self.product, quantity: quantity)
// Spacer()
// }.padding(.vertical)
//
//
//
// HStack {
//// Spacer()
// ZStack{
// Color.blue
// Button(action : {}){
// Text("Buy Now")
// .foregroundColor(.white)
// .font(.headline)
// }.buttonStyle(BorderlessButtonStyle())
// }
// .frame(width: g.size.width)
//// Spacer()
// }.padding(.vertical)
//
//
// HStack {
// Spacer()
// Button(action : {}){
// Text("Add to Cart")
// }
// .frame(width: g.size.width)
// Spacer()
// }.padding(.vertical)
//
// }
//
//
// Section {
// VStack(alignment: .center){
// Text("Description").font(.headline)
// .frame(width: g.size.width/3)
// .padding()
//
// Text(self.product.description ?? "")
// .font(.subheadline)
// .frame(width: g.size.width * 8/10, alignment: .leading)
// }
// }
//
//
//
// }
// .navigationBarTitle(Text(self.productList.products[self.productID].name), displayMode: .automatic)
// .navigationBarItems(trailing: Button(action : {
//
// }){
// Capsule()
// })
// }}}
// }
//}
//
//
//
//struct SingleProductImageSection: View {
// @EnvironmentObject var productList:ProductList
// @Binding var productID:Int
// var g: GeometryProxy
// var body: some View {
// HStack{
// Spacer()
// Image(uiImage: self.productList.products[self.productID].image)
// .resizable()
// .frame(width: g.size.width * (3/5), height: g.size.width * (3/5), alignment: .center)
// Spacer()
// }
// }
//}
//
//
//struct SingleProductView_Previews: PreviewProvider {
// static var previews: some View {
// SingleProductView(productID: .constant(0))
// .environmentObject(SampleProductList.productList)
// }
//}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/Buttons/MoreButton.swift
//
// MoreButton.swift
// Villa2
//
// Created by <NAME> on 4/3/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct MoreButton: View {
var fetchRequest:FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
var resultLimit:Int
@Binding var bindingResultLimit:Int
init(filter: String, resultLimit: Int, bindingResultLimit: Binding<Int>, cat1:String, cat2:String){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
//request for 1 more than the limit
request.fetchLimit = resultLimit + 1
// debugPrint("cat1 is \(cat1), cat2 is \(cat2)")
let cat1Predicate = NSPredicate(format: cat1.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat1,cat1,cat1,cat1)
let cat2Predicate = NSPredicate(format: cat2.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat2,cat2,cat2,cat2)
let searchPredicate = NSPredicate(format: filter.count > 0 ? "(name CONTAINS[c] %@) OR (metaKeywords CONTAINS[c] %@) ":"TRUEPREDICATE", filter.count > 0 ? filter:"*",filter.count > 0 ? filter:"*")
let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [cat1Predicate, cat2Predicate,searchPredicate])
request.predicate = andPredicate
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
self.resultLimit = resultLimit
//attach binding
self._bindingResultLimit = bindingResultLimit
}
var body: some View {
Button(action: {
self.bindingResultLimit += 40
}){
Text("more")
}
.disabled(productCores.count > resultLimit ? false:true)
.padding(.bottom,100)
}
}
//struct MoreButton_Previews: PreviewProvider {
// static var previews: some View {
// MoreButton()
// }
//}
<file_sep>/Villa2/CoreData/ProductCore+CustomExtension.swift
//
// ProductCore+CustomExtension.swift
// Villa2
//
// Created by <NAME> on 3/31/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import KingfisherSwiftUI
import CoreData
// all the extensions
extension ProductCore{
public var quantityInCart: Int {
get {
return Int(self.numberInCart)
}
set {
self.numberInCart = Int16(newValue)
self.updateCart()
}
}
public var image:UIImage {
get {
if let imageUrl = self.imageUrl{
if let data = self.imageData, let image = UIImage(data: data),UIImage(data: data) != UIImage(named: IMAGE_PLACEHOLDER){
debugPrint("image exist in coredata, returning")
return image
} else {
debugPrint("imageData is blank or placeholder, returning placeholder")
return UIImage(named: IMAGE_PLACEHOLDER)!
}
} else {
debugPrint("imageUrl is blank, returning placeholder")
return UIImage(named: IMAGE_PLACEHOLDER)!
}
// debugPrint("Unknown image download error, returning placeholder")
// return UIImage(named: IMAGE_PLACEHOLDER)!
}
set {
self.imageData = newValue.pngData()
}
}
public var priceDescription : String {
get{
// debugPrint("price is", self.price)
// debugPrint("price description is", String(format: "%.2f" ,Float(self.price)))
return "฿ \(String(format: "%.2f" ,Float(self.price)))"
}
}
func updateCart(){
if self.numberInCart > 0 {
self.isInCart = true
} else {
self.isInCart = false
}
}
func addImage(url:String){
self.imageUrl = url
}
public var wrappedUrl:URL {
let endpoint = MagentoApi.Endpoints.image(self.sku ?? "villaHeader.png")
if let url = endpoint.url {
return url
} else {
//Placeholder please dont forget to edit
return URL(string: "https://villa-images-sg.s3-ap-southeast-1.amazonaws.com/villaPlaceholder.png")!
}
}
public var wrappedAlternativeUrl:URL {
let endpoint = MagentoApi.Endpoints.alternativeImage(self.imageUrl ?? "villaHeader.png")
if let url = endpoint.url {
return url
} else {
//Placeholder please dont forget to edit
return URL(string: "https://villa-images-sg.s3-ap-southeast-1.amazonaws.com/villaPlaceholder.png")!
}
}
public var kfImage: some View {
return KFImage(self.wrappedUrl)
.placeholder{
KFImage(self.wrappedAlternativeUrl)
.placeholder{
ImagePlaceholder.productPlaceholderImage()
}
.resizable()
.renderingMode(.original)
.scaledToFit()
}
.resizable()
.renderingMode(.original)
.scaledToFit()
}
// // get category
// func category(){
// let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
// request.fetchLimit = 200
//// debugPrint("cat1 is \(cat1), cat2 is \(cat2)")
// let cat1Predicate = NSPredicate(format: cat1.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat1,cat1,cat1,cat1)
// let cat2Predicate = NSPredicate(format: cat2.count > 0 ? "(cat1 LIKE[c] %@) OR (cat2 LIKE[c] %@) OR (cat3 LIKE[c] %@) OR (cat4 LIKE[c] %@)":"TRUEPREDICATE", cat2,cat2,cat2,cat2)
// let searchPredicate = NSPredicate(format: filter.count > 0 ? "(name CONTAINS[c] %@) OR (metaKeywords CONTAINS[c] %@) ":"TRUEPREDICATE", filter.count > 0 ? filter:"*",filter.count > 0 ? filter:"*")
//
// let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [cat1Predicate, cat2Predicate,searchPredicate])
// request.predicate = andPredicate
// request.sortDescriptors = []
// }
}
<file_sep>/Villa2/View/SettingsView/ActionList.swift
//
// ActionList.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct ActionList: View {
var actions:[Action] = [
Action(name: "call", pageName: "call", image: Image(systemName: "phone")),
Action(name: "message", pageName: "message", image: Image(systemName: "message")),
Action(name: "video", pageName: "video call", image: Image(systemName: "video"))
]
var body: some View {
VStack(spacing: 20){
ForEach(actions, id: \.name){ action in
AnyView{
HStack{
Text(action.name)
}
}
}
}
}
}
struct ActionList_Previews: PreviewProvider {
static var previews: some View {
ActionList()
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/Buttons/QuantityButtons/CartQuantityButtons.swift
//
// CartButton.swift
// Villa2
//
// Created by <NAME> on 4/3/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct CartQuantityButtons: View {
var numberOfProducts:Int{
var totalProducts = 0
for product in productCores{
totalProducts += product.quantityInCart
}
return totalProducts
}
var fetchRequest: FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
@Binding var isCheckout:Bool
@Binding var showModal:Bool
init(isCheckout:Binding<Bool>, showModal:Binding<Bool>){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = 100
let predicate = NSPredicate(format: "isInCart == TRUE")
request.predicate = predicate
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
self._isCheckout = isCheckout
self._showModal = showModal
}
var body: some View {
ZStack(alignment: .topTrailing){
HStack{
Image(systemName: self.numberOfProducts > 0 ? "cart.fill":"cart")
.resizable()
.frame(width: 20, height: 20, alignment: .topTrailing)
Spacer()
}
.frame(width: 28, height: 30)
if self.numberOfProducts > 0 {
ZStack{
Circle()
.foregroundColor(.white)
Image(systemName: "\(self.numberOfProducts <= 50 ? String(self.numberOfProducts):"plus").circle.fill")
.resizable()
}
.frame(width: 15, height: 15, alignment: .topTrailing)
.foregroundColor(.red)
}
}
// .onTapGesture {
// self.isCheckout = true
// self.showModal = true
// }
}
}
struct CartButton_Previews: PreviewProvider {
static var previews: some View {
CartQuantityButtons(isCheckout: .constant(false), showModal: .constant(false))
.previewLayout(.sizeThatFits)
}
}
<file_sep>/Villa2/bin/ProductQuantityButton.swift
////
//// ProductQuantityButton.swift
//// Villa2
////
//// Created by <NAME> on 3/14/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct ProductQuantityButton: View {
// @EnvironmentObject var productList:ProductList
//
// var product: ProductRaw
// @Binding var quantity: Int
//
// var body: some View {
// ZStack(alignment: .leading){
// Capsule()
// .frame(width: 120, height: 40, alignment: .center)
// .foregroundColor(Color(UIColor.systemGray6))
//
// HStack(alignment: .center) {
//
// // add button
// ProductModifierButton(quantity: $quantity, productButtonType: .remove)
// .environmentObject(productList)
//
//
// // quantity text field
// TextField("quantity", value: $quantity, formatter: self.numberFormatter)
// .keyboardType(.numberPad)
// .multilineTextAlignment(.center)
//
// // remove button
// ProductModifierButton(quantity: $quantity, productButtonType: .add)
// .environmentObject(productList)
//
// }
// .frame(width: 120, height: 40, alignment: .center)
// .overlay(Capsule().stroke(
// Color.blue.opacity(0.2),lineWidth: 5)
// )
// .padding(.trailing)
// }
//
// }
//
// private var numberFormatter: NumberFormatter {
// let nf = NumberFormatter()
// nf.allowsFloats = false
// nf.maximumIntegerDigits = 2
// nf.minimumIntegerDigits = 1
// nf.minimum = 0
// return nf
// }
//
//}
//
////enum ProductButtonType: String{
//// case add = "plus"
//// case remove = "minus"
////}
//
//struct ProductModifierButton: View{
// @Binding var quantity:Int
//// @Binding var product:ProductRaw
// let productButtonType:ProductButtonType
// @EnvironmentObject var productList:ProductList
//
// var body: some View {
// Button(action: {
// switch self.productButtonType{
// case .add:
// self.quantity += 1
// case .remove:
// if self.quantity > 0 {
// self.quantity -= 1
// }
// }
// }){
// Image(systemName: self.productButtonType.rawValue)
// }
// .padding(12)
// .buttonStyle(BorderlessButtonStyle())
// }
//}
//
//#if DEBUG
//
//struct ProductQuantityButton_Previews: PreviewProvider {
// static var previews: some View {
//
// Group{
//
// ProductQuantityButton(product: SampleProductList.products[2], quantity: .constant(5))
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .light)
// .previewLayout(.sizeThatFits)
// .environmentObject(SampleProductList.productList)
//
//
// ProductQuantityButton(product: SampleProductList.products[2], quantity: .constant(5))
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
// .environmentObject(SampleProductList.productList)
//
//
// ProductCell(product: SampleProductList.products[0])
// .environmentObject(RootGeometry(geometry: nil))
// .environmentObject(SampleProductList.productList)
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
// .environmentObject(SampleProductList.productList)
//
//
//
// ProductModifierButton(quantity: .constant(5), productButtonType: .add)
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
// .environmentObject(SampleProductList.productList)
//
// }
//
// }
//}
//#endif
<file_sep>/Villa2/bin/ProductTableFormView.swift
////
//// ProductTableFormView.swift
//// Villa2
////
//// Created by <NAME> on 3/21/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct ProductTableFormView: View {
// @EnvironmentObject var productList:ProductList
// @EnvironmentObject var rootGeometry:RootGeometry
//// @Binding var selectedItem:Int
//// @Binding var presentProduct:Bool
// var body: some View {
// GeometryReader { geometry in
// ScrollView{
//// Form{
//// Section{
//// ScrollView{
// ForEach(self.productList.products.prefix(through: 4), id:\.self){ product in
// ProductCell(product: product)
//// }
//// }
////
//// }
// }
// }
// }
// }
//}
//
//struct ProductTableFormView_Previews: PreviewProvider {
// static var previews: some View {
// Group {
// ProductTableFormView()
// .background(Color(.systemBackground))
//
// ProductTableFormView()
// .background(Color(.systemBackground))
//
// .environment(\.colorScheme, .dark)
// }
// .previewDevice("iPhone X")
// .environmentObject(SampleProductList.productList)
// .environmentObject(RootGeometry(geometry: nil))
// }
//}
<file_sep>/Villa2/SystemTypeExtension/Float.swift
//
// Float.swift
// Villa2
//
// Created by <NAME> on 3/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
extension Float{
var twoDecimalPoints:String {
return String(format: "%.2f", self)
}
var noDecimalPoints:String {
return String(format: "%.f", self)
}
}
<file_sep>/Villa2/SceneDelegate.swift
//
// SceneDelegate.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import UIKit
import SwiftUI
import CoreData
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// create product cat list
let productCat:ProductCategoryList = ProductCategoryList(productCategory: SampleCategory.category)
let catLinear = S3Api.getCatLinear()
if let fetchedCatProducts = fetchCatFromCoreData(context: context){
if let decodedProductCat = fetchedCatProducts.decodedCategoryList{
// use the fetched data to update product cat
productCat.products = decodedProductCat
} else {
debugPrint("decoding product from core data failed")
}
} else {
debugPrint("products not in core data")
}
DispatchQueue.global(qos: .background).async {
if let downloadedCategories = MagentoApi.getCategories() {
DispatchQueue.main.async {
productCat.products = downloadedCategories
//save to core data
if let fetchedCatProducts = fetchCatFromCoreData(context: context){
fetchedCatProducts.decodedCategoryList = downloadedCategories
// try? context.save()
CoreDataFunctions.saveContext()
} else {
debugPrint("Cat product empty, creating a new one")
let newCat = Categories(context: context)
newCat.decodedCategoryList = downloadedCategories
// try? context.save()
CoreDataFunctions.saveContext()
}
}
debugPrint("categories downloaded decoded successfully")
}
}
// create product list
var productRawList:ProductList = SampleProductList.productList
//update core data
appDelegate.persistentContainer.performBackgroundTask { (backgroundContext) in
debugPrint("updating product cores")
let products = S3Api.getProductCores(context: backgroundContext)
if let products = products {
debugPrint("product update succesfully ",products.first?.description ?? "product description is blank")
} else {
debugPrint("products are not updated")
}
}
let contentView = TabBarControllerView()
.environment(\.window, window)
.environment(\.managedObjectContext, context)
.environmentObject(productRawList)
.environmentObject(RootGeometry(geometry: nil))
.environmentObject(CurrentUser())
.environmentObject(PresentationStatus())
.environmentObject(TabStatus())
.environmentObject(productCat)
.environmentObject(ShowProductModal())
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidEnterBackground(_ scene: UIScene) {
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
struct SceneDelegate_Previews: PreviewProvider {
static var previews: some View {
Text("Hello, World!")
}
}
<file_sep>/Villa2/API/S3Api.swift
//
// S3GetProducts.swift
// Villa2
//
// Created by <NAME> on 3/27/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import CoreData
import Foundation
class S3Api{
class func getProducts()->[ProductCodable]?{
let endpoint = S3Api.Endpoints.products
let url = endpoint.url
let semaphore = DispatchSemaphore(value: 0)
var products: [ProductCodable]?
guard url != nil else {
debugPrint("invalid url")
return nil
}
debugPrint("getting products")
S3Api.taskForGETS3(url: url!, responseType: [ProductCodable].self) { (p, e) in
guard e == nil else {
debugPrint("error fetching data", e?.localizedDescription ?? "")
return
}
products = p
semaphore.signal()
debugPrint("api products response recieved")
}
_ = semaphore.wait(timeout: .distantFuture)
return products
}
class func getProductRaws()->[ProductRaw]?{
let productCodables = S3Api.getProducts()
var productRaws:[ProductRaw] = []
if let productCodables = productCodables{
for productCodable in productCodables{
productRaws.append(productCodable.toProductRaw)
}
}
if productRaws.count > 1 {
return productRaws
} else {
return nil
}
}
class func getProductCores(context:NSManagedObjectContext)->[ProductCore]?{
let productCodables = S3Api.getProducts()
var productCores:[ProductCore] = []
let isFirstRun = !UserDefaults.standard.bool(forKey: "firstProductCoreLoad")
debugPrint("isFirstRun",isFirstRun)
if let productCodables = productCodables{
debugPrint("products have decoded successfully")
for productCodable in productCodables{
productCores.append(productCodable.toProductCore(context: context, firstRun: isFirstRun))
if productCores.count.quotientAndRemainder(dividingBy: 1000).remainder == 0 {
// debugPrint("1000 products has been added")
do {
try context.save()
context.reset()
// debugPrint("context saved and reset")
} catch {
debugPrint("context save error")
}
}
}
}
debugPrint("error summary for products request",ErrorCount.requestErrorCount)
do {
try context.save()
context.reset()
} catch {
debugPrint("saving error line 77 GetProductsCores")
}
if productCores.count > 1 {
UserDefaults.standard.set(true, forKey: "firstProductCoreLoad")
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductCore")
do {
let count = try context.count(for: fetchRequest)
debugPrint("coredata has \(count) items")
} catch {
debugPrint("count error")
}
return productCores
} else {
return nil
}
}
class func getCatLinear()->[ProductCatLinearizedCodable]?{
let endpoint = S3Api.Endpoints.catList
let url = endpoint.url
let semaphore = DispatchSemaphore(value: 0)
var cat: [ProductCatLinearizedCodable]?
guard url != nil else {
debugPrint("invalid url")
return nil
}
debugPrint("getting products")
S3Api.taskForGETS3(url: url!, responseType: ProductCatLinearizedCodableContainer.self) { (c, e) in
guard e == nil else {
debugPrint("error fetching data", e?.localizedDescription ?? "")
return
}
if let c = c{
cat = c.items
} else {
debugPrint("cat returned is nil")
}
semaphore.signal()
debugPrint("api linearized cat response recieved")
}
_ = semaphore.wait(timeout: .distantFuture)
return cat
}
enum Endpoints {
static let base = "https://villa-products-sg.s3-ap-southeast-1.amazonaws.com/products.json"
static let gzip = "https://d18ug7ix877nj9.cloudfront.net/products.gzip"
static let catListUrl = "https://d18ug7ix877nj9.cloudfront.net/catList.json"
case products
case productsGzip
case catList
var stringValue: String {
switch self {
case .products: return Endpoints.base
case .productsGzip: return Endpoints.gzip
case .catList: return Endpoints.catListUrl
}
}
var url: URL? {
if let url = URL(string: stringValue) {
return url
} else {
debugPrint("error parsing url", stringValue)
return nil
}
}
}
class func taskForGETS3<ResponseType: Decodable>(url: URL, responseType: ResponseType.Type, completion: @escaping (ResponseType?, Error?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
debugPrint("api call to \(url) made")
guard let data = data else {
DispatchQueue.main.async {
completion(nil, error)
}
return
}
let decoder = JSONDecoder()
do {
let responseObject = try decoder.decode(ResponseType.self, from: data)
completion(responseObject, nil)
} catch {
debugPrint("error parsing object", error)
do {
let errorResponse = try decoder.decode(MagentoError.self, from: data) as Error
completion(nil, errorResponse)
} catch {
debugPrint("error parsing error response", data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
debugPrint("json received", json)
} catch {
debugPrint("data is not json", error)
completion(nil, error)
}
}
}
}
task.resume()
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SingleProductView/Modifiers/SingleProductViewModifier.swift
//
// SingleProductViewModifiers.swift
// Villa2
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
struct SingleProductCoreImageModifier: ViewModifier {
@Binding var largeImage:Bool
@Binding var imageRotation: Double
func body(content: Content) -> some View {
content
.rotation3DEffect(.init(degrees: self.imageRotation), axis: (x: 0, y: 1, z: 0))
.onTapGesture {
withAnimation(.interpolatingSpring(stiffness: 50, damping: 5)){
self.largeImage.toggle()
if self.largeImage {
self.imageRotation = 10
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
withAnimation(.interpolatingSpring(stiffness: 2, damping: 1)){
self.imageRotation = 0
}
}
} else {
self.imageRotation = 0
}
}
}
.pinchToZoom()
}
}
<file_sep>/Villa2/API/HelperFunctions.swift
//
// GeneralFunctions.swift
// Villa2
//
// Created by <NAME> on 3/25/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import CoreData
import Foundation
import UIKit
import KingfisherSwiftUI
import SwiftUI
func decodeData<ResponseType: Decodable>(responseType: ResponseType.Type, data:Data)->ResponseType?{
let decoder = JSONDecoder()
do {
let responseObject = try decoder.decode(ResponseType.self, from: data)
return responseObject
} catch {
debugPrint("error parsing object", error)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
debugPrint("json decoded is", json)
return nil
} catch {
debugPrint("data is not json", error)
return nil
}
}
}
func encodeData<ResponseType: Encodable>(data: ResponseType)->Data?{
let encoder = JSONEncoder()
do {
let data = try encoder.encode(data)
return data
} catch {
debugPrint("failed to encode data", error)
return nil
}
}
func fetchCatFromCoreData(context:NSManagedObjectContext)->Categories?{
let catFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Categories")
do {
let fetchedCat = try context.fetch(catFetchRequest) as! [Categories]
if let firstItem = fetchedCat.first {
debugPrint("core data category fetched")
return firstItem
} else {
debugPrint("core data category is empty")
return nil
}
} catch {
debugPrint("Failed to fetch cat from coreData: \(error)")
return nil
}
}
func checkIfProductExist(context:NSManagedObjectContext ,sku: String) -> ProductCore? {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductCore")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "sku == %@" ,sku)
// fetchRequest.predicate = NSPredicate(format: "type == %@" ,type)
do {
let fetchedProduct = try context.fetch(fetchRequest) as! [ProductCore]
// debugPrint("fetch successful")
return fetchedProduct.first
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo), maybe product is not in coredata")
return nil
}
}
//Variables
let IMAGE_PLACEHOLDER = "VillaPlaceholder"
class ImageManipulation{
static func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage ?? UIImage(named: "VillaPlaceholder")!
}
}
class ErrorCount{
static var requestErrorCount:[String:Int] = [:]
static func addRequestError(topic:String, number:Int){
if ErrorCount.requestErrorCount[topic] == nil {
ErrorCount.requestErrorCount[topic] = 0
}
ErrorCount.requestErrorCount.updateValue(ErrorCount.requestErrorCount[topic,default: 0] + number, forKey: topic)
}
static var productImageErrorCount = 0
// static var
}
class CoreDataFunctions{
class func saveContext(){
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
}
class ImagePlaceholder {
struct productPlaceholderImage: View {
var body: some View {
KFImage(URL(string: "https://villa-images-sg.s3-ap-southeast-1.amazonaws.com/villaPlaceholder.png")!)
.resizable()
.renderingMode(.original)
.scaledToFit()
}
}
}
<file_sep>/Villa2/View/Observables/QuantityBinder.swift
//
// QuantityBinder.swift
// Villa2
//
// Created by <NAME> on 3/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
//
//struct QualityBinder{
// @EnvironmentObject var productList:ProductList
// @Binding var product:Binding<ProductRaw>
//
// let quantity = Binding<Int>(get: {
// return self.productList.getQuantityInCart(sku: self.product.sku)
//
// },
// set: {
// self.productList.setQuantityInCart(sku: self.product.sku, quantity: $0)
// debugPrint("quantity in cart is set to:", $0)
// debugPrint("test getting product quantity:", self.productList.getQuantityInCart(sku: self.product.sku))
//
// })
//
//
// init(product: Binding<ProductRaw>) {
// self.product = product
// }
//}
//
<file_sep>/Villa2/API/CredentialsApi.swift
//
// CredentialsApi.swift
// VillaCoreData
//
// Created by <NAME> on 3/22/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
class CredentialsApi{
static let magentoApiKey = "Bearer ma63uofuch34xgygs5g4euo3kht9935y"
}
<file_sep>/Villa2/View/Tab1HomeView/CartView/CartProductTableCell.swift
//
// CartProductTableCell.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct CartProductTableCell: View {
@State var disableAnimation:Bool
@ObservedObject var productCoreWrapper:ProductCoreWrapper
@Environment(\.managedObjectContext) var moc
var product:ProductCore
init(disableAnimation:Bool ,product:ProductCore){
//set up products
var productCoreWrapper_ = ProductCoreWrapper(productCore: product)
self.productCoreWrapper = productCoreWrapper_
self.product = productCoreWrapper_.productCore
//set up others
self._disableAnimation = State(initialValue: disableAnimation)
}
var body: some View {
var quantity:Binding<Int> = Binding<Int>(get: {
return self.product.quantityInCart
},set: {
self.product.quantityInCart = $0
try? self.moc.save()
})
return VStack{
HStack{
//image and quantity selector
VStack(alignment: .leading) {
ProductCoreImage(disableImageAnimation: self.$disableAnimation, width: 100, productCore: self.product)
.padding()
CartQuantityButton(quantity: quantity)
.padding(.leading)
.padding(.bottom)
}
//description and price
VStack(alignment: .leading){
Text(product.name ?? "")
.lineLimit(1)
.padding(.trailing)
.padding(.bottom)
Text("\(self.product.productDescription ?? "" ) \(String(repeating: " ", count: 100))")
.fixedSize(horizontal: false, vertical: true)
.font(.body)
// .fontWeight(.light)
// .multilineTextAlignment(.leading)
.lineLimit(4)
.padding(.trailing)
Text("\(self.product.priceDescription)")
.padding(.trailing)
.padding(.top)
.lineLimit(1)
}
}
.font(.system(size: 20, weight: .semibold, design: .default))
}
}
}
struct CartProductTableCell_Previews: PreviewProvider {
static var previews: some View {
Group {
CartProductTableCell(disableAnimation: false, product: SampleProductCore.productCore)
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(RootGeometry(geometry: nil))
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewLayout(.sizeThatFits)
CartProductTableCell(disableAnimation: false, product: SampleProductCore.productCore)
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(RootGeometry(geometry: nil))
.background(Color(.systemBackground))
.environment(\.colorScheme, .light)
.previewLayout(.sizeThatFits)
}
.environment(\.managedObjectContext, SampleProductCore.context)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewController/Extension/SearchViewController+Extension.swift
//
// SearchViewController+Extension.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import KingfisherSwiftUI
import CoreData
extension SearchViewController{
func sidebarWidth(g: GeometryProxy)->CGFloat{
return g.size.width / 4
}
func deleteAllItems(){
let moc = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductCore")
// Create Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try moc.execute(batchDeleteRequest)
try moc.save()
moc.reset()
self.reloadUI()
debugPrint("all items deleted")
} catch {
// Error Handling
debugPrint("error deleting and saving")
}
}
func fetchApi(){
(UIApplication.shared.delegate as! AppDelegate).persistentContainer.performBackgroundTask { (backgroundContext) in
S3Api.getProductCores(context: backgroundContext)
self.reloadUI()
}
}
// updateui
func reloadUI(){
DispatchQueue.main.async {
self.sidebar.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
self.sidebar.toggle()
}
}
moc.refreshAllObjects()
}
func dragValue(translation:CGSize, sidebar:Binding<Bool>, showCat:Binding<Bool>){
if translation.width < -50 {
withAnimation {
self.sidebar = false
debugPrint("hiding sidebar")
}
} else if translation.width > 50{
withAnimation{
self.sidebar = true
}
}
if translation.height > 100 {
withAnimation{
self.showCat = true
}
} else if translation.height < -100{
withAnimation{
debugPrint("hiding cat")
self.showCat = false
}
}
}
func productTableWidth(g:GeometryProxy)->CGFloat{
return self.sidebar ? g.size.width - self.sidebarWidth(g: g) : g.size.width
}
}
<file_sep>/Villa2/View/tabViewElements/TabBarElements.swift
//
// TabBarElements.swift
// tabBarControllerDemo
//
// Created by <NAME> on 3/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
// 1
struct TabBarElementItem {
var title: String
var image: UIImage
var badge: String?
}
// 2
protocol TabBarElementView: View {
associatedtype Content
var content: Content { get set }
var tabBarElementItem: TabBarElementItem { get set }
}
struct TabBarElement: TabBarElementView {
var tabBarElementItem: TabBarElementItem
internal var content: AnyView
init<Content: View>(tabBarElementItem: TabBarElementItem, // 3
@ViewBuilder _ content: () -> Content) {
self.tabBarElementItem = tabBarElementItem
self.content = AnyView(content()) // 5
}
var body: some View {
self.content
}
}
struct TabBarElement_Previews: PreviewProvider {
static var previews: some View {
TabBarElement(tabBarElementItem: .init(
title: "first",
image: UIImage(systemName: "house.fill")!
)
){
Text("hello world")
}
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SingleProductView/SingleProductCoreViewAssets/MinusLabel.swift
//
// MinusLabel.swift
// Villa2
//
// Created by <NAME> on 4/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct MinusLabel: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct MinusLabel_Previews: PreviewProvider {
static var previews: some View {
MinusLabel()
}
}
<file_sep>/Villa2/View/HelperViews/Buttons/ProductCoreQuantityButton.swift
//
// ProductCoreButton.swift
// Villa2
//
// Created by <NAME> on 3/28/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct ProductCoreQuantityButton: View {
// @EnvironmentObject var productList:ProductList
var product: ProductCore
@Binding var quantity: Int
var width:CGFloat
var body: some View {
ZStack(alignment: .leading){
HStack(alignment: .center) {
// remove button
Button(action: {
// Actions
if self.quantity > 0 {
self.quantity -= 1
debugPrint("reducting 1 product", "current quantity is \(self.quantity)")
} else {
debugPrint("cant reduct, prodcut q is 0")
}
}) {
Image(systemName: "minus")
.frame(width: width/4, height: width/4)
}
// quantity text field
Text(self.quantity.string)
.frame(width: width/2.5, height: width/3)
// add button
Button(action: {
// Actions
debugPrint("adding 1 product", "current quantity is \(self.quantity)")
self.quantity += 1
}) {
Image(systemName: "plus")
.frame(width: width/4, height: width/4)
}
}
.buttonStyle(BorderlessButtonStyle())
.frame(width: width, height: 33, alignment: .center)
.padding(.horizontal)
.overlay(Capsule().stroke(
Color.blue.opacity(0.5),lineWidth: 5)
)
}
}
private var numberFormatter: NumberFormatter {
let nf = NumberFormatter()
nf.allowsFloats = false
nf.maximumIntegerDigits = 2
nf.minimumIntegerDigits = 1
nf.minimum = 0
return nf
}
}
#if DEBUG
struct ProductCoreButton_Previews: PreviewProvider {
static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
static var previews: some View {
// let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let productCore = ProductCore(context: moc)
productCore.name = "testProduct"
productCore.numberInCart = 2
productCore.productDescription = "sdfaffa"
productCore.imageData = UIImage(systemName: "basket")?.pngData()!
return Group {
ProductCoreQuantityButton(product: productCore, quantity: .constant(2), width: 50)
}
}
}
#endif
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SingleProductView/SingleProductCoreView.swift
//
// SingleProductCoreView.swift
// Villa2
//
// Created by <NAME> on 3/29/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import KingfisherSwiftUI
struct SingleProductCoreView: View {
var product:ProductCore{
get {
return self.productCoreWrapper.productCore
}
}
@Environment(\.managedObjectContext) var moc
@Binding var showModal: Bool
@State var largeImage: Bool = false
@State var imageRotation:Double = 0
@ObservedObject var productCoreWrapper:ProductCoreWrapper
@State var imagePopUp:Bool = false
init(product:ProductCore, showModal:Binding<Bool>){
let productCoreWrapper = ProductCoreWrapper(productCore: product)
self.productCoreWrapper = productCoreWrapper
// self.product = productCoreWrapper.productCore
self._showModal = showModal
}
var body: some View {
return GeometryReader{ g in
VStack{
// ModalViewIndicator()
List{
Spacer()
//image
Section{
VStack(alignment: .center){
NavigationLink(destination: ZoomedImageView(product: self.product), isActive: self.$imagePopUp, label: {
Image(systemName: self.largeImage ? "minus.magnifyingglass":"plus.magnifyingglass")
.padding()
})
.buttonStyle(PlainButtonStyle())
// Button(action: {
// self.imagePopUp = true
//
// }) {
// Image(systemName: self.largeImage ? "minus.magnifyingglass":"plus.magnifyingglass")
// .padding()
// }
// .sheet(isPresented: self.$imagePopUp, content: {
// ZoomedImageView(product: self.product)
// })
//
// .frame(width: g.size.width, alignment: .trailing)
SingleProductCoreImageSection(product: self.product, g: g, largeImage: self.$largeImage)
.modifier(SingleProductCoreImageModifier(largeImage: self.$largeImage, imageRotation: self.$imageRotation))
.frame(width: g.size.width, alignment: .center)
}
}
.modifier(CenterNoInsetModifier())
//name and price
Section {
VStack (alignment: .leading) {
//name
HStack(alignment: .center){
Text("Name")
.modifier(ListTextTitleViewModifier())
Text(self.product.name ?? "")
.modifier(ListTextDetailViewModifier())
}
//price description
HStack(alignment: .center){
Text("Price")
.modifier(ListTextTitleViewModifier())
Text(self.product.priceDescription)
.modifier(ListTextDetailViewModifier())
}
.padding(.vertical)
// Notes to buyer
VStack(alignment:.leading){
Text("Notes to buyers")
.font(.headline)
Text("This is the note to buyers, put the product in the fridge and consume within 30 days, please read the labels carefully, if there is any abnormality, please do not consume")
.modifier(MultilineTextModifier())
.lineLimit(nil)
.padding()
}
}
}
// quantity buttons
if self.productCoreWrapper.productCore.quantityInCart == 0 {
// add to cart button
HStack {
Spacer()
AddToCartButton(quantityInCart: self.$productCoreWrapper.productCore.quantityInCart, width: 120)
Spacer()
}
.padding(.vertical)
} else {
HStack{
Spacer()
ProductCoreQuantityButton(product: self.product, quantity: self.$productCoreWrapper.productCore.quantityInCart, width: 120)
.padding()
Spacer()
}
}
//buy now button
HStack {
Spacer()
ZStack{
Color.blue
.cornerRadius(5)
Button(action : {}){
Text("Buy Now")
.foregroundColor(.white)
.font(.headline)
}.buttonStyle(BorderlessButtonStyle())
}
.frame(width: g.size.width/3, alignment: .center)
Spacer()
}
.padding(.vertical)
//pro description
VStack(alignment: .center){
Text("Description")
.modifier(TextTitleViewModifier())
Text(self.product.productDescription ?? "")
.font(.subheadline)
.frame(width: g.size.width * 8/10, alignment: .leading)
}
//similar products
Text("Similar products")
.font(.headline)
VStack {
//name
ProductCoreCollectionViewTable(filter: self.product.name?.components(separatedBy: " ").first ?? "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false),cat1: "",cat2: "", width: g.size.width, isSingleProduct: true)
.padding(.vertical, 20)
//cat 1
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false),cat1: self.product.cat1 ?? "",cat2: "", width: g.size.width, isSingleProduct: true)
.padding(.vertical, 20)
//cat 2
ProductCoreCollectionViewTable(filter: "", disableImageAnimation: .constant(true), resultLimit: 10, bindingResultLimit: .constant(10), sidebar: .constant(false),cat1: "",cat2: self.product.cat2 ?? "", width: g.size.width, isSingleProduct: true)
.padding(.vertical, 20)
}
}
.navigationBarTitle(Text(self.product.name ?? ""), displayMode: .inline)
}}
}
}
struct SingleProductCoreImageSection: View {
var product:ProductCore
var g: GeometryProxy
// @State private var dragAmount = CGSize.zero
// @State private var enabled = false
@Binding var largeImage:Bool
var body: some View {
HStack{
if !largeImage {Spacer()}
KFImage(self.product.wrappedUrl)
.placeholder{
KFImage(self.product.wrappedAlternativeUrl)
.placeholder{
ImagePlaceholder.productPlaceholderImage()
}
.resizable()
.scaledToFit()
}
.renderingMode(.original)
.resizable()
.scaledToFit()
.frame(width: largeImage ? g.size.width * 2 : g.size.width * (5/5) , height: largeImage ? g.size.width * 2 : g.size.width * (5/5), alignment: .center)
.cornerRadius(10)
if !largeImage {Spacer()}
}
// .onAppear{
// debugPrint("the product sku is",self.product.sku, "s3 link is",self.product.wrappedUrl, "magento link is", self.product.wrappedAlternativeUrl)
// }
}
}
struct SingleProductCoreView_Previews: PreviewProvider {
static var previews: some View {
let productCore = SampleProductCore.productCore
return Group {
SingleProductCoreView(product: productCore, showModal: .constant(true))
}
}
}
<file_sep>/Villa2/bin/ProductImage.swift
////
//// ProductImage.swift
//// Villa2
////
//// Created by <NAME> on 3/13/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//struct ProductImage: View {
// @EnvironmentObject var rootGeometry:RootGeometry
// @State var overrideWidth:Float?
// @State var imageAnimation:Double = -20
// var product: ProductRaw
// var body: some View {
// ZStack(alignment: .center){
//// ProductImageBackground(width: imageWidth())
//
// InnerProductImage(product: product, width: imageWidth())
// .opacity(1)
//
// }
// .rotation3DEffect(.degrees(self.imageAnimation), axis: (x: 0, y: 1, z: 0))
// .onAppear{
// withAnimation(.interpolatingSpring(stiffness: 2, damping: 1)){
// self.imageAnimation = 180
// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// withAnimation(.interpolatingSpring(stiffness: 2, damping: 1)){
// self.imageAnimation = 1
// }
// }
// }
// }
// }
//
// private func imageWidth()->CGFloat{
// if let overrideWidth = self.overrideWidth {
// return CGFloat(overrideWidth)
// }
// return 300 / 3
// }
//}
//
//struct ProductImage_Previews: PreviewProvider {
// static var previews: some View {
// Group {
// ProductImage(product: SampleProductList.products[0])
// .environmentObject(RootGeometry(geometry: nil))
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .light)
// .previewLayout(.sizeThatFits)
//
// ProductImage(product: SampleProductList.products[0])
// .environmentObject(RootGeometry(geometry: nil))
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
// }
//
// }
//}
<file_sep>/Villa2/bin/Cart.swift
//
//// Cart.swift
//// Villa2
////
//// Created by <NAME> on 3/13/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import Foundation
//import SwiftUI
//import Combine
//
//class Cart:ObservableObject{
// @Published var items:[ProductRaw] = []
//
// }
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewNavigation/Extension/SearchViewNavigationController+Extension.swift
//
// SearchViewNavigationController+Extension.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import KingfisherSwiftUI
import CoreData
extension SearchViewNavigationController{
}
<file_sep>/Villa2/View/settingsMenu/SettingsMainView.swift
//
// SettingsMainView.swift
// Villa2
//
// Created by <NAME> on 4/10/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct SettingsMainView: View {
var body: some View {
VStack{
HStack{
Image(systemName: "person")
.foregroundColor(.gray)
.imageScale(.large)
Text("Profile")
.foregroundColor(.gray)
.font(.headline)
}
}
}
}
struct SettingsMainView_Previews: PreviewProvider {
static var previews: some View {
SettingsMainView()
}
}
<file_sep>/Villa2/View/Modifiers/CenterNoInsetModifier.swift
//
// CenterNoInsetModifier.swift
// Villa2
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import CoreData
struct CenterNoInsetModifier: ViewModifier {
func body(content: Content) -> some View {
content
.frame(alignment: .center)
.listRowInsets(EdgeInsets(top: 20, leading: 0, bottom: 20, trailing: 20))
}
}
<file_sep>/Villa2/bin/TabViewController.swift
////
//// TabView.swift
//// Villa2
////
//// Created by <NAME> on 3/14/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//
//
//
//
//
//
//
//struct TabViewController: View {
// @Environment(\.colorScheme) var colorScheme: ColorScheme
// @Environment(\.window) var window: UIWindow?
// @EnvironmentObject var user: CurrentUser
// @EnvironmentObject var presentation: PresentationStatus
// @EnvironmentObject var productList:ProductList
// @EnvironmentObject var rootGeometry:RootGeometry
//
// @EnvironmentObject var tabStatus: TabStatus
//
// var mocklist:[String] = ["hey", "ho", "hello"]
//
// var body: some View {
// TabView (selection: self.$tabStatus.tabChoice){
//// Tab1ViewNavigationController()
//// .environment(\.window, window)
//// .environmentObject(productList)
//// .environmentObject(rootGeometry)
//// .environmentObject(user)
//// .environmentObject(presentation)
//// .environmentObject(tabStatus)
//
// Text("mock tab 1")
// .tabItem {
// Image(systemName: "tray.2.fill")
// Text("All")
// }.tag(TabChoice.tab1)
//
//// Tab1MainView()
//// .environmentObject(productList)
//// .environmentObject(rootGeometry)
//// .tabItem {
//// Image(systemName: "2.circle")
//// Text("Second")
//// }.tag(TabChoice.tab2)
//
//
// VStack{
// Text("hello")
// Text("hello2")
// List {
// ForEach(1..<100, id: \.self) { productID in
// Text("hello \(productID)")
// }
// }
// }
// .tabItem {
// Image(systemName: "2.circle")
// Text("Second")
// }.tag(TabChoice.tab2)
//
//
//
// Text("Second View")
// .tabItem {
// Image(systemName: "3.circle")
// Text("Third")
// }.tag(TabChoice.tab3)
//
// CartView()
// .environmentObject(self.productList)
// .environmentObject(self.rootGeometry)
// .tabItem {
// if productList.cart.count == 0 {
// Image(systemName: "cart")
// Text("cart")
// } else {
// Image(systemName: "cart.fill")
// Text("cart")
// }
// }.tag(TabChoice.cart)
// }
// }
//}
//
//struct TabViewController_Previews: PreviewProvider {
// static var previews: some View {
// Group {
// TabViewController()
// .environmentObject(TabStatus())
// .environmentObject(ProductList(products: SampleProductList.products))
// .environmentObject(RootGeometry(geometry: nil))
// .environmentObject(CurrentUser())
// .environmentObject(PresentationStatus())
//
//
// TabViewController()
// .environmentObject(TabStatus())
// .environmentObject(ProductList(products: SampleProductList.products))
// .environmentObject(RootGeometry(geometry: nil))
// .environmentObject(CurrentUser())
// .environmentObject(PresentationStatus())
// .environment(\.colorScheme, .dark)
// }
// }
//}
<file_sep>/Villa2/View/Tab1HomeView/CartView/CartProductTable.swift
//
// CartProductTable.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct CartProductTable: View {
// @EnvironmentObject var rootGeometry:RootGeometry
var productCores:FetchedResults<ProductCore>
var numberOfProducts:Int{
var totalProducts = 0
for product in productCores{
totalProducts += product.quantityInCart
}
return totalProducts
}
@State var disableAnimation = false
var cartTotal:Float {
var total = 0
for product in self.productCores{
total += Int(product.price) * product.quantityInCart
}
return Float(total)
}
var body: some View {
VStack{
CartViewHeaderCell(cartTotal: self.cartTotal, numberOfProducts: self.numberOfProducts)
ScrollView {
ForEach(productCores, id: \.self) {productCore in
CartProductTableCell(disableAnimation: self.disableAnimation, product: productCore)
}
}
}
}
}
//
//struct CartProductTable_Previews: PreviewProvider {
// let fetchedRequestR
// CartProductTable(productCores: SampleProductCore.context.fetch(<#T##request: NSFetchRequest<NSFetchRequestResult>##NSFetchRequest<NSFetchRequestResult>#>))
// .environment(\.managedObjectContext, SampleProductCore.context)
//
//// .
// }
//}
<file_sep>/Villa2/bin/ProductCell.swift
//
// ProductCell.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//import SwiftUI
//
//struct ProductCell: View {
// @EnvironmentObject var rootGeometry:RootGeometry
// @EnvironmentObject var productList:ProductList
// @State var product:ProductRaw
//
//
// var body: some View {
//
// var quantity = Binding<Int>(get: {
// return SampleProductList.productList.getQuantityInCart(sku: self.product.sku)
//
// },
// set: {
// self.productList.setQuantityInCart(sku: self.product.sku, quantity: $0)
// debugPrint("quantity in cart is set to:", $0)
// debugPrint("test getting product quantity:", self.productList.getQuantityInCart(sku: self.product.sku))
//
// })
//
//
// return HStack(alignment: .top){
//
// VStack(alignment: .center){
// // product image
// Button(action: {
// }){
// ProductImage(product: product)
// }
// .buttonStyle(BorderlessButtonStyle())
//
// Text(product.priceDescription)
//
// Text(product.name)
//
// Button("Add To Cart"){
//
// }
// }
//
// // product description and button
//// ProductDescription(product: $product, quantity: quantity)
//// .environmentObject(self.rootGeometry)
//// .environmentObject(self.productList)
//
// }
//
// }
//
// private func imageWidth()->CGFloat{
// return (self.rootGeometry.geometry?.size.width ?? 300) / 3
// }
//}
//
//
//
//
//
//
//
//#if DEBUG
//struct ProductCell_Previews: PreviewProvider {
// static var previews: some View {
// Group{
// ProductCell(product: SampleProductList.products[0])
// .background(Color(.systemBackground))
// .environment(\.colorScheme, .dark)
// .previewLayout(.sizeThatFits)
//
// ProductCell(product: SampleProductList.products[1])
// .previewLayout(.sizeThatFits)
//
// ProductCell(product: SampleProductList.products[0])
// .previewLayout(.sizeThatFits)
//
// }
// .environmentObject(SampleProductList.productList)
// .environmentObject(RootGeometry(geometry: nil))
// .previewLayout(.sizeThatFits)
// }
//}
//
//#endif
<file_sep>/Villa2/View/Observables/RootGeometry.swift
//
// RootGeometry.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
class RootGeometry:ObservableObject{
@Published var geometry:GeometryProxy?
init(geometry:GeometryProxy?){
self.geometry = geometry
}
}
<file_sep>/Villa2/View/Image/ProductCoreImage.swift
//
// ProductImageCore.swift
// Villa2
//
// Created by <NAME> on 3/28/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import KingfisherSwiftUI
struct ProductCoreImage: View {
@State var overrideWidth:Float?
@State var imageAnimation:Double = 0
@Binding var disableImageAnimation:Bool
var width:CGFloat
var productCore: ProductCore
var body: some View {
ZStack(alignment: .center){
// ProductImageBackground(width: imageWidth())
InnerProductCoreImage(product: productCore, width: imageWidth())
}
.animation(
Animation
.easeInOut(duration: 1)
// .delay(0.2)
)
// .rotation3DEffect(self.disableImageAnimation ? Angle.degrees(0):Angle.degrees(self.imageAnimation), axis: (x: 0, y: 1, z: 0))
// .onAppear{
// if self.disableImageAnimation{
//
// } else {
// withAnimation(.interpolatingSpring(stiffness: 2, damping: 1)){
// self.imageAnimation = 0
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// withAnimation(.interpolatingSpring(stiffness: 2, damping: 1)){
// self.imageAnimation = 180
// }
// }
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// withAnimation(.interpolatingSpring(stiffness: 2, damping: 1)){
// self.imageAnimation = 0
// }
// }
// }
// }
// }
}
private func imageWidth()->CGFloat{
if let overrideWidth = self.overrideWidth {
return CGFloat(overrideWidth)
}
return self.width
}
}
struct InnerProductCoreImage: View {
@Environment(\.managedObjectContext) var moc
@State var image:UIImage = UIImage(named: IMAGE_PLACEHOLDER)!
var product:ProductCore
var width:CGFloat
var body: some View {
// Image(uiImage: self.image)
KFImage(self.product.wrappedUrl)
.placeholder{
// Image("VillaPlaceholder-1")
KFImage(self.product.wrappedUrl)
.placeholder{
KFImage(self.product.wrappedAlternativeUrl)
.placeholder{
ImagePlaceholder.productPlaceholderImage()
}
.resizable()
.renderingMode(.original)
.scaledToFit()
}
.resizable()
.renderingMode(.original)
.scaledToFit()
.frame(width: self.width, height: self.width)
}
.resizable()
.renderingMode(.original)
.scaledToFit()
// .cornerRadius(width/7)
.frame(width: self.width, height: self.width)
.foregroundColor(.purple)
}
}
#if DEBUG
struct ProductCoreImage_Preview: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let productCore = ProductCore(context: context)
productCore.name = "testProduct"
return Group {
ProductCoreImage(disableImageAnimation: .constant(true), width: 50, productCore: productCore)
}
}
}
#endif
<file_sep>/Villa2/View/Observables/TabStatus.swift
//
// TabStatus.swift
// Villa2
//
// Created by <NAME> on 3/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
class TabStatus: ObservableObject{
@Published var tabChoice:TabChoice {
didSet {
UserDefaults.standard.set(self.tabChoice.rawValue, forKey:self.tabStatusKey)
}
}
init(){
let savedTab = UserDefaults.standard.string(forKey: self.tabStatusKey) ?? TabChoice.tab1.rawValue
self.tabChoice = TabChoice(rawValue: savedTab) ?? TabChoice.tab1
}
let tabStatusKey = "tabStatusKey"
}
enum TabChoice:String{
case tab1 = "tab1"
case tab2 = "tab2"
case tab3 = "tab3"
case cart = "cart"
}
<file_sep>/Villa2/View/SettingsView/StoreFinder.swift
//
// StoreSelector.swift
// Villa2
//
// Created by <NAME> on 5/6/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import MapKit
struct StoreSelectorMap: UIViewRepresentable {
class Coordinator: NSObject, MKMapViewDelegate{
var parent: StoreSelectorMap
init(_ parent: StoreSelectorMap){
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
debugPrint(mapView.centerCoordinate)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<StoreSelectorMap>) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
for annotation in VillaLocations.annotations{
mapView.addAnnotation(annotation.annotation)
}
return mapView
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<StoreSelectorMap>) {
}
}
struct StoreFinder: View {
var body: some View{
ZStack{
StoreSelectorMap()
.edgesIgnoringSafeArea(.all)
}
.navigationBarTitle("Store Selector")
}
}
struct StoreFinder_Previews: PreviewProvider {
static var previews: some View {
StoreFinder()
}
}
<file_sep>/Villa2/SigninWithAppleContents/CredentialStorage/SharedWebCredential.swift
import Foundation
enum SharedWebCredentialError: Error {
case SecRequestFailure(CFError)
case MissingCredentials
case ConversionFailure
}
struct SharedWebCredential {
private let domain: CFString
private let safeForTutorialCode: Bool
init(domain: String) {
self.domain = domain as CFString
safeForTutorialCode = !domain.isEmpty
}
func retrieve(account: String? = nil, completion: @escaping (Result<(account: String?, password: String?), SharedWebCredentialError>) -> Void) {
guard safeForTutorialCode else {
print("Please set your domain for SharedWebCredential constructor in UserAndPassword.swift!")
return
}
var acct: CFString? = nil
if let account = account {
acct = account as CFString
}
SecRequestSharedWebCredential(domain, acct) { credentials, error in
if let error = error {
DispatchQueue.main.async {
completion(.failure(.SecRequestFailure(error)))
}
return
}
guard
let credentials = credentials,
CFArrayGetCount(credentials) > 0
else {
DispatchQueue.main.async {
completion(.failure(.MissingCredentials))
}
return
}
let unsafeCredential = CFArrayGetValueAtIndex(credentials, 0)
let credential: CFDictionary = unsafeBitCast(unsafeCredential, to: CFDictionary.self)
guard let dict = credential as? Dictionary<String, String> else {
DispatchQueue.main.async {
completion(.failure(.ConversionFailure))
}
return
}
let username = dict[kSecAttrAccount as String]
let password = dict[kSecSharedPassword as String]
DispatchQueue.main.async {
completion(.success((username, password)))
}
}
}
private func update(account: String, password: String?, completion: @escaping (Result<Bool, SharedWebCredentialError>) -> Void) {
guard safeForTutorialCode else {
print("Please set your domain for SharedWebCredential constructor in UserAndPassword.swift!")
return
}
var pwd: CFString? = nil
if let password = password {
pwd = password as CFString
}
SecAddSharedWebCredential(domain, account as CFString, pwd) { error in
DispatchQueue.main.async {
if let error = error {
completion(.failure(.SecRequestFailure(error)))
} else {
completion(.success(true))
}
}
}
}
func store(account: String, password: String, completion: @escaping (Result<Bool, SharedWebCredentialError>) -> Void) {
update(account: account, password: <PASSWORD>, completion: completion)
}
func delete(account: String, completion: @escaping (Result<Bool, SharedWebCredentialError>) -> Void) {
update(account: account, password: nil, completion: completion)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewController/TopBar/ButtonStyle/SearchTopViewIconButtonStyle.swift
//
// SearchTopViewIconButtonStyle.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import KingfisherSwiftUI
struct TopIconsButtonStyle: ButtonStyle {
var activated:Bool
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding()
.foregroundColor(.white)
.background(configuration.isPressed ? Color.red : self.activated ? Color.red: Color(.sRGB, white: 0, opacity: 0.01) )
.frame(height: 100)
.cornerRadius(50.0)
}
}
<file_sep>/Villa2/bin/ProductsInCart.swift
////
//// ProductsInCart.swift
//// villaEcommerce
////
//// Created by <NAME> on 1/14/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import Foundation
//import UIKit
//
//class ProductsInCart{
//
// static var productList:[ProductStorage] = []
// static func totalPrice()->Float{
// var total:Float = 0
// for product in ProductsInCart.productList {
// total += product.totalPrice
// }
// return total
// }
//
// static func addNewProductToCart(productToAdd:ProductRaw, quantity:Int){
// let newProductStorage = ProductStorage(product: productToAdd, quantity: quantity)
// self.productList.append(newProductStorage)
// }
//
// static func removeFromCart(sku:String, quantity:Int){
// if let index = self.productList.firstIndex(where: { (selectedProduct) -> Bool in
// return selectedProduct.product.sku == sku
// }){
// if quantity >= self.productList[index].quantity {
// self.productList.remove(at: index)
// } else {
// self.productList[index].quantity -= quantity
// }
// } else {
// debugPrint("product not in the cart",self.productList)
// }
// }
//
//}
//struct ProductStorage{
// let product:ProductRaw
// var quantity:Int
// var totalPrice : Float {
// get {
// product.price * Float(quantity)
// }
// }
//}
<file_sep>/Villa2/View/Tab1HomeView/HomeViewNavigationController.swift
//
// ContentView.swift
// swiftuiHE
//
// Created by <NAME> on 3/10/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct HomeViewNavigationController: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
@Environment(\.window) var window: UIWindow?
@EnvironmentObject var user: CurrentUser
@EnvironmentObject var presentation: PresentationStatus
@EnvironmentObject var productList:ProductList
@EnvironmentObject var rootGeometry:RootGeometry
@EnvironmentObject var tabStatus:TabStatus
@EnvironmentObject var showProductModal:ShowProductModal //= ShowProductModal()
//Display popups
@State var showMenu = false
@State var showProfile = false
@State var presentProduct = false
@State var showCart = false
@State var showLogin = false
@State var showLocationSelector = true
var body: some View {
return NavigationView {
GeometryReader { g in
ZStack(alignment: .leading) {
self.mainHomeView(g: g)
}
.onAppear(perform: {
debugPrint("location selector is \(self.showLocationSelector)")
})
//navigationBar
// set title
.navigationBarTitle("Villa Market", displayMode: .automatic)
// set items
.navigationBarItems(leading: (
// leading bar items
HomeViewNavigationBarLeadingItems(showMenu: self.$showMenu, showLogin: self.$showLogin)
),trailing: (
// trailing bar item
HomeViewNavigationBarTrailingItems()
)
)
//present login
}
}.sheet(isPresented: self.$showLocationSelector) {
// DeliveryLocation(isDisplayed: self.$showLocationSelector)
StoreSelector(isDisplayed: self.$showLocationSelector)
// LoginView(showLogin:self.$showLogin)
}
}
func mainHomeView(g: GeometryProxy)-> some View {
// HomeViewController(showMenu: self.$showMenu,selectedItem: .constant(0),presentProduct: self.$presentProduct)
// .frame(width: g.size.width, height: g.size.height)
// .offset(x: self.showMenu ? g.size.width/2 : 0)
// .disabled(self.showMenu ? true : false)
HomeView()
}
}
//
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
HomeViewNavigationController()
HomeViewNavigationController()
.environment(\.colorScheme, .dark)
}
.previewDevice(PreviewDevice(rawValue: "iPhone 11 Pro"))
.environmentObject(CurrentUser(isLoggedIn: false, name: "stamp"))
.environmentObject(SampleProductList.productList)
.environmentObject(RootGeometry(geometry: nil))
.environmentObject(PresentationStatus())
.environmentObject(TabStatus())
}
}
#endif
struct Action:Hashable {
let name: String
let pageName: String
let image: Image
func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
<file_sep>/Villa2/SigninWithAppleContents/SignInWithAppleDelegates.swift
import UIKit
import AuthenticationServices
import Contacts
class SignInWithAppleDelegates: NSObject {
private let signInSucceeded: (Bool) -> Void
private weak var window: UIWindow!
init(window: UIWindow?, onSignedIn: @escaping (Bool) -> Void) {
self.window = window
self.signInSucceeded = onSignedIn
}
}
extension SignInWithAppleDelegates: ASAuthorizationControllerDelegate {
private func registerNewAccount(credential: ASAuthorizationAppleIDCredential) {
// 1
let userData = UserData(email: credential.email!,
name: credential.fullName!,
identifier: credential.user)
// 2
let keychain = UserDataKeychain()
do {
try keychain.store(userData)
} catch {
self.signInSucceeded(false)
}
// 3
do {
let success = try WebApi.Register(user: userData,
identityToken: credential.identityToken,
authorizationCode: credential.authorizationCode)
self.signInSucceeded(success)
} catch {
self.signInSucceeded(false)
}
}
private func signInWithExistingAccount(credential: ASAuthorizationAppleIDCredential) {
// You *should* have a fully registered account here. If you get back an error from your server
// that the account doesn't exist, you can look in the keychain for the credentials and rerun setup
// if (WebAPI.Login(credential.user, credential.identityToken, credential.authorizationCode)) {
// ...
// }
debugPrint("user has signed in with existing account",credential.user)
self.signInSucceeded(true)
}
private func signInWithUserAndPassword(credential: ASPasswordCredential) {
// You *should* have a fully registered account here. If you get back an error from your server
// that the account doesn't exist, you can look in the keychain for the credentials and rerun setup
// if (WebAPI.Login(credential.user, credential.password)) {
// ...
// }
debugPrint("user has signed in with user and password",credential.user)
self.signInSucceeded(true)
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
switch authorization.credential {
case let appleIdCredential as ASAuthorizationAppleIDCredential:
if let _ = appleIdCredential.email, let _ = appleIdCredential.fullName {
registerNewAccount(credential: appleIdCredential)
debugPrint("user is registering new account")
} else {
signInWithExistingAccount(credential: appleIdCredential)
debugPrint("user has a keychain account already")
}
break
case let passwordCredential as ASPasswordCredential:
signInWithUserAndPassword(credential: passwordCredential)
debugPrint("user signed in with username and password")
break
default:
break
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
// Handle error.
debugPrint("error apple sign in", error)
}
}
extension SignInWithAppleDelegates: ASAuthorizationControllerPresentationContextProviding {
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.window
}
}
<file_sep>/Villa2/API/MagentoCodables/MagentoCodables.swift
//
// MagentoCodables.swift
// VillaCoreData
//
// Created by <NAME> on 3/22/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import CoreData
struct ProductCodable: Decodable {
let id: Int
let sku: String
let name: String
let attributeSetId: Int
let price: Float
let status: Int
let visibility: Int
let typeId: String
let createdAt: String
let UpdatedAt: String
// let productLinks: [QuantumValue?]
// let tierPrices: [String]
let customAttributes:[CustomProductAttributes]
enum CodingKeys: String, CodingKey {
case id
case sku
case name
case attributeSetId = "attribute_set_id"
case price
case status
case visibility
case typeId = "type_id"
case createdAt = "created_at"
case UpdatedAt = "updated_at"
// case productLinks = "product_links"
// case tierPrices = "tier_prices"
case customAttributes = "custom_attributes"
}
var toProductRaw:ProductRaw{
let categoryIds = customAttributes.first { (customProductAttributes) -> Bool in
return customProductAttributes.attributeCode == "category_ids"
}?.value.listValue
let metaKeywords = customAttributes.first { (customProductAttributes) -> Bool in
return customProductAttributes.attributeCode == "meta_keyword"
}?.value.stringValue
let specialPrice = customAttributes.first { (customProductAttributes) -> Bool in
return customProductAttributes.attributeCode == "special_price"
}?.value.stringValue?.floatValue
let imageUrl = customAttributes.first { (customProductAttributes) -> Bool in
return customProductAttributes.attributeCode == "meta_keyword"
}?.value.stringValue
let description = customAttributes.first { (customProductAttributes) -> Bool in
return customProductAttributes.attributeCode == "short_description"
}?.value.stringValue
return ProductRaw(name: name, image: #imageLiteral(resourceName: "AllLogo"), price: price, sku: sku, category: nil, categoryIds: categoryIds, description: description, isFavourite: false, isRecommended: false, isInHistory: false, imageURL: imageUrl, rankingScore: 0.00, metaKeywords: metaKeywords, specialPrice: specialPrice)
}
func toProductCore(context:NSManagedObjectContext,firstRun:Bool)->ProductCore{
// debugPrint("price is:", self.price)
if firstRun {
return createNewProductCore(context: context)
}else{
if let product = checkIfProductExist(context: context, sku: self.sku){
updateProductCore(productCore: product)
return product
} else {
return createNewProductCore(context: context)
}
}
}
func createNewProductCore(context:NSManagedObjectContext)->ProductCore{
let productCore = ProductCore(context: context)
mergeProductCore(productCore: productCore)
if let url = self.customAttributes.first(where: { (ca) -> Bool in
return ca.attributeCode == "image"
})?.value.stringValue {
productCore.addImage(url: url)
} else {
ErrorCount.addRequestError(topic: "imageUrl new product", number: 1)
}
return productCore
}
func updateProductCore(productCore: ProductCore){
self.mergeProductCore(productCore: productCore)
}
func getCustomStringAttributes(attName:String)->String?{
if let stringValue = self.customAttributes.first(where: { (ca) -> Bool in
return ca.attributeCode == attName
})?.value.stringValue {
return stringValue
} else {
//record error in Errorcount
ErrorCount.addRequestError(topic: attName, number: 1)
return nil
}
}
func getCustomListAttributes(attName:String)->[String]?{
if let listValue = self.customAttributes.first(where: { (ca) -> Bool in
return ca.attributeCode == attName
})?.value.listValue {
// debugPrint(listValue)
return listValue
} else {
//record error in Errorcount
ErrorCount.addRequestError(topic: attName, number: 1)
// ErrorCount.requestErrorCount.updateValue(ErrorCount.requestErrorCount[attName,default: 0] + 1, forKey: attName)
return nil
}
}
func mergeProductCore(productCore: ProductCore){
productCore.name = self.name
productCore.sku = self.sku
productCore.price = Int16(ceil(self.price) > Float(Int16.max) ? Float(0) : ceil(self.price))
//update url
if let url = getCustomStringAttributes(attName: "image"){
productCore.addImage(url: url)
}
if let description = getCustomStringAttributes(attName: "short_description"){
productCore.productDescription = description
}
if let metaKeywords = getCustomStringAttributes(attName: "meta_keyword"){
productCore.metaKeywords = metaKeywords
}
if let longDescription = getCustomStringAttributes(attName: "description"){
productCore.longDescription = longDescription
}
if let productCatId = getCustomListAttributes(attName: "category_ids"){
productCore.categoryIds = productCatId
let catLen = productCatId.count
for catId in 0..<catLen {
switch catId {
case 0:
productCore.cat1 = productCatId[catId]
case 1:
productCore.cat2 = productCatId[catId]
case 2:
productCore.cat3 = productCatId[catId]
case 3:
productCore.cat4 = productCatId[catId]
default:
break
}
}
}
}
}
struct CustomProductAttributes:Decodable{
let attributeCode: String
let value: QuantumValue
enum CodingKeys: String, CodingKey {
case attributeCode = "attribute_code"
case value
}
}
struct ProductsCodable: Decodable {
let item:[ProductCodable]
enum CodingKeys: String, CodingKey {
case item = "items"
}
}
enum QuantumValue: Decodable {
case int(Int), string(String), array([String]), dictionary([String:String])
init(from decoder: Decoder) throws {
if let int = try? decoder.singleValueContainer().decode(Int.self) {
self = .int(int)
return
}
if let string = try? decoder.singleValueContainer().decode(String.self) {
self = .string(string)
return
}
if let array = try? decoder.singleValueContainer().decode([String].self){
self = .array(array)
return
}
if let dictionary = try? decoder.singleValueContainer().decode([String:String].self){
self = .dictionary(dictionary)
return
}
throw QuantumError.missingValue
}
enum QuantumError:Error {
case missingValue
}
var intValue : Int? {
guard case .int(let num) = self else { return nil }
return num
}
var stringValue : String? {
guard case .string(let string) = self else { return nil }
return string
}
var listValue : [String]? {
guard case .array(let array) = self else { return nil }
return array
}
}
struct MagentoError: Codable {
let errorMessage: String
// let parameters: MagentoErrorParameters
enum CodingKeys: String, CodingKey {
case errorMessage = "message"
// case parameters = "parameters"
}
}
extension MagentoError: LocalizedError {
var errorDescription: String? {
return errorMessage
}
}
<file_sep>/Villa2/View/wallet/WalletMainView.swift
//
// WalletMainView.swift
// Villa2
//
// Created by <NAME> on 5/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct WalletMainView: View {
var body: some View {
NavigationView{
GeometryReader{ g in
VStack(alignment: .center){
VStack(alignment: .center){
HStack{
Text("Name")
Text("Surname")
}
HStack{
Text("VPlus No.")
Text("VXIX2048")
}
}
// Balance and points
HStack{
HStack{
Image(uiImage: UIImage(named: "money")!.imageWithColor(tintColor: .gray))
.modifier(IconsModifier())
.padding()
VStack{
Text("123")
Text("Balance")
}
}
.frame(width: g.size.width/2)
HStack{
Image(uiImage: UIImage(named: "point")!.imageWithColor(tintColor: .gray))
.modifier(IconsModifier())
.colorMultiply(.white)
.padding()
VStack{
Text("1284")
Text("Points")
}
}
.frame(width: g.size.width/2)
}
.frame(width: g.size.width)
.padding(.vertical)
// scan and topup
HStack{
Button(action: {
//
}, label: {
HStack{
Image("scan")
// .renderingMode(.original)
.modifier(IconsModifier())
Text("Scan")
}
})
.buttonStyle(BorderlessButtonStyle())
.frame(width: g.size.width/2)
Button(action: {
//
}, label: {
HStack{
Image("topup")
// .renderingMode(.original)
.modifier(IconsModifier())
Text("Top Up")
}
})
.buttonStyle(BorderlessButtonStyle())
.frame(width: g.size.width/2)
}
.padding(.vertical)
VStack{
Image("villaCard")
.resizable()
.scaledToFit()
.frame(width: g.size.width)
ZStack{
// Color.white
Image(uiImage: UIImage(named: "barcode")!.withBackground(color: .white))
// Image("barcode")
.resizable()
.scaledToFit()
.cornerRadius(5)
}
Text("IX0392")
.frame(width: g.size.width/2 )
}
Spacer()
}
}
.navigationBarTitle("Villa Wallet")
}
}
}
struct WalletMainView_Previews: PreviewProvider {
static var previews: some View {
WalletMainView()
}
}
<file_sep>/Villa2/View/Observables/ShowProductModal.swift
//
// ShowProductModal.swift
// Villa2
//
// Created by <NAME> on 3/29/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
class ShowProductModal:ObservableObject{
@Published var product:ProductCore?
@Published var isDisplayed:Bool = false
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchBar/SearchBar.swift
//
// SearchBar.swift
// Villa2
//
// Created by <NAME> on 3/28/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct SearchBar: View {
@Binding var text:String
@Binding var showCat:Bool
@Binding var sidebar:Bool
@Binding var disableImageAnimation:Bool
@Binding var resultLimit:Int
@State var showMagnifying:Bool = true
@Binding var isSearching:Bool
var body: some View {
HStack{
Image(systemName: "magnifyingglass")
.opacity(self.showMagnifying ? 1:0)
.frame(maxWidth: self.showMagnifying ? 40:1)
.padding(.leading)
.animation(.easeInOut)
.onTapGesture {
self.showCat.toggle()
}
TextField("Search", text: $text,onEditingChanged: { editing in
if editing {
self.showCat = true
self.sidebar = false
self.disableImageAnimation = true
self.showMagnifying = false
self.resultLimit = 20
self.isSearching = true
} else {
self.showMagnifying = true
self.resultLimit = 100
self.disableImageAnimation = true
self.isSearching = false
}
}, onCommit: {
self.showCat = true
// self.sidebar = true
self.disableImageAnimation = false
})
.modifier(ClearButton(text: self.$text))
.textFieldStyle(PlainTextFieldStyle())
.padding(.horizontal)
.padding(.vertical, 3.0)
.overlay(Capsule().stroke(Color.blue.opacity(0.5), lineWidth: 5))
// .frame( height: 30, alignment: .center)
// .overlay(RoundedRectangle(cornerRadius: 30, style: .continuous).stroke(Color.blue.opacity(0.2),lineWidth: 5))
// .background(Color.gray)
.padding(.trailing)
}.padding(.top)
}
}
struct ClearButton: ViewModifier
{
@Binding var text: String
public func body(content: Content) -> some View
{
HStack()
{
content
if !text.isEmpty
{
Button(action:
{
self.text = ""
})
{
Image(systemName: "delete.left")
.foregroundColor(Color(UIColor.opaqueSeparator))
}
// .disabled(false)
// .buttonStyle(BorderlessButtonStyle())
.padding(.trailing, 8)
}
}
}
}
struct SearchBar_Previews: PreviewProvider {
static var previews: some View {
SearchBar(text: .constant("hello"),showCat: .constant(true), sidebar: .constant(true),disableImageAnimation: .constant(false), resultLimit: .constant(20), isSearching: .constant(false))
}
}
<file_sep>/Villa2/SystemTypeExtension/IntExtension.swift
//
// IntExtension.swift
// Villa2
//
// Created by <NAME> on 4/3/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
extension Int {
var string:String{
String(self)
}
}
extension Int16 {
var string:String{
String(self)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Body/FilterIconsNavigationLinkTable.swift
//
// FilterIconsNavigationLinkTable.swift
// Villa2
//
// Created by <NAME> on 4/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct FilterIconsNavigationLinkTable: View {
@EnvironmentObject var catList:ProductCategoryList
@Environment(\.managedObjectContext) var moc
var mainCat:[ProductCategory] { get {self.catList.products.childrenData[0].childrenData}}
var isOdd:Bool
var body: some View {
ScrollView(.horizontal){
HStack(spacing: 10) {
ForEach(
self.mainCat.filter(
{ (cat) -> Bool in
return cat.isActive
}
).enumeratedArray()[..<10] , id:\.element){ id, cat in
Group {
if id % 2 == (self.isOdd ? 1:0) {
NavigationLink(destination:
SearchViewController(mainCatID: self.getCatId(cat: cat))
.environment(\.managedObjectContext, self.moc)
.environmentObject(self.catList)
) {
VStack{
Image(uiImage: UIImage(named: cat.name) ?? UIImage(named: "Grocery")!)
.resizable()
.scaledToFit()
.frame(width: 60, height: 40)
Text(cat.name)
.font(.system(size: 10))
.allowsTightening(true)
.minimumScaleFactor(0.5)
.lineLimit(2)
.frame(width: 60, height: 30)
}
}
.frame(width: 70, height: 70, alignment: .center)
.buttonStyle(PlainButtonStyle())
}
}
}
}
}
}
func getCatId(cat:ProductCategory)->Int{
return self.mainCat.firstIndex(where: { (foundCat) -> Bool in
return foundCat.name == cat.name
}) ?? -1
}
}
struct FilterIconsNavigationLinkTable_Previews: PreviewProvider {
static var previews: some View {
FilterIconsNavigationLinkTable(isOdd: true)
}
}
<file_sep>/Villa2/bin/HomeViewController.swift
////
//// ContentView.swift
//// Villa2
////
//// Created by <NAME> on 3/13/20.
//// Copyright © 2020 tenxor. All rights reserved.
////
//
//import SwiftUI
//import KingfisherSwiftUI
//struct HomeViewController: View {
// @Binding var showMenu: Bool
// @EnvironmentObject var productList:ProductList
// @Binding var selectedItem:Int
// @Binding var presentProduct:Bool
//
// var body: some View {
// VStack{
// HomeView()
// }
// }
//}
//
//
//
//
//
//#if DEBUG
//struct MainView_Previews: PreviewProvider {
// static var previews: some View {
// Group{
// HomeViewController(showMenu: .constant(true), selectedItem: .constant(0), presentProduct: .constant(false))
// .background(Color(.systemBackground))
//
//
// HomeViewController(showMenu: .constant(true), selectedItem: .constant(0), presentProduct: .constant(false))
// .background(Color(.systemBackground))
//
// .environment(\.colorScheme, .dark)
// }
// .environmentObject(
// SampleProductList.productList
// )
// .environmentObject(
// RootGeometry(geometry: nil)
// )
// }
//
//}
//#endif
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewController/SearchViewController.swift
//
// Tab2View.swift
// Villa2
//
// Created by <NAME> on 3/15/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct SearchViewController: View {
// @EnvironmentObject var user:CurrentUser
@EnvironmentObject var catList:ProductCategoryList
@State var sidebar:Bool = false
@State var currentCat:Int = -1
@State var currentSubCat:Int = 0
@State var filter:String = ""
@State var showCat:Bool = true
@State var disableImageAnimation:Bool = false
@State var resultLimit:Int = 40
@State var isCheckout = false
@State var isSearching = false
@State var searchBar = false
@Environment(\.managedObjectContext) var moc
// @EnvironmentObject var showProductModal:ShowProductModal //= ShowProductModal()
@State var cat1 = ""
@State var cat2 = ""
var subcat:[ProductCategory] {
get {
return self.currentCat == -1 ? self.mainCat[0].childrenData : self.mainCat[self.currentCat].childrenData
}
}
var fetchRequest:FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
fetchRequest.wrappedValue
}
init(){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = 20
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
}
init(mainCatID:Int, sideBar:Bool = true){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = 20
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
self._currentCat = State(initialValue: mainCatID)
self._sidebar = State(initialValue: sideBar)
}
var mainCat:[ProductCategory] { get {self.catList.products.childrenData[0].childrenData}}
var body: some View {
let drag = DragGesture(minimumDistance: 30, coordinateSpace: .global)
.onChanged{
self.dragValue(translation: $0.translation, sidebar: self.$sidebar, showCat: self.$showCat)
}
return GeometryReader{ g in
VStack{
// if self.currentCat != -1 {
// MainCatSearchIcons(mainCat: self.mainCat, currentCat: self.$currentCat, currentSubCat: self.$currentSubCat, sidebar: self.$sidebar, resultLimit: self.$resultLimit )
// // .offset(x: 0, y: -50)
// .animation(.easeInOut(duration: 1))
// }
// show/hide search bar
if self.searchBar{
SearchBar(text: self.$filter, showCat: self.$showCat, sidebar: self.$sidebar,disableImageAnimation: self.$disableImageAnimation, resultLimit: self.$resultLimit, isSearching: self.$isSearching)
.gesture(drag)
}
// if self.showCat{
// MainCatSearchIcons(mainCat: self.mainCat, currentCat: self.$currentCat, currentSubCat: self.$currentSubCat, sidebar: self.$sidebar, resultLimit: self.$resultLimit )
// .gesture(drag)
// }
// Spacer()
// .frame(width: g.size.width, height: 20, alignment: .center)
ZStack(alignment: .leading) {
VStack(spacing: 10){
ZStack{
Color(UIColor.systemBackground)
SearchViewProductTable(
filter: self.filter,
disableImageAnimation: self.$disableImageAnimation,
resultLimit: self.resultLimit,
bindingResultLimit: self.$resultLimit,
sidebar: self.$sidebar,
cat1: self.currentCat >= 0 ? self.mainCat[self.currentCat].id.string : "" ,
cat2: self.currentSubCat == -1 ? "" : (self.currentSubCat < self.subcat.count) && (self.currentCat >= 0) ? self.subcat[self.currentSubCat].id.string : "", isSearching: self.$isSearching,
width: self.productTableWidth(g: g)
)
// .frame(width: self.productTableWidth(g: g) > 100 ? self.productTableWidth(g: g) : 100)
// .environmentObject(self.showProductModal)
}
}
.frame(width: self.sidebar ? self.productTableWidth(g: g) : g.size.width)
// .frame(minWidth: 100, maxWidth: self.productTableWidth(g: g) > 100 ? self.productTableWidth(g: g):100 )
.offset(x: self.sidebar ? (self.sidebarWidth(g: g)) : 0)
SideBarSearchIcons(mainCat: self.mainCat,currentCat: self.currentCat, currentSubCat: self.$currentSubCat, sideBarWidth: self.sidebarWidth(g: g))
.animation(self.disableImageAnimation ? nil:Animation.default)
.offset(x: !self.sidebar ? -self.sidebarWidth(g: g) : 0)
}
.gesture(drag)
.animation(.easeInOut)
//NavigationBar Items
.navigationBarTitle(Text(self.currentCat == -1 ? "All": self.mainCat[self.currentCat].name),displayMode: .large)
.navigationBarItems(leading:
SearchViewNavigationBarLeadingItems(currentCat: self.$currentCat, currentSubCat: self.$currentSubCat, sidebar: self.$sidebar, resultLimit: self.$resultLimit)
, trailing:
SearchViewNavigationBarTrailingItems(searchBar: self.$searchBar)
)
}
}
}
}
struct FormSectionView_Previews: PreviewProvider {
// let productCat:ProductCategoryList = ProductCategoryList(productCategory: SampleCategory.category)
static var previews: some View {
let productCat = ProductCategoryList(productCategory: SampleCategory.category)
return Group {
SearchViewController()
.environment(\.colorScheme, .dark)
SearchViewController()
.environment(\.colorScheme, .light)
}
.environmentObject(productCat)
.environmentObject(ShowProductModal())
.environment(\.managedObjectContext, SampleProductCore.context)
.background(Color(.systemBackground))
.previewLayout(.sizeThatFits)
}
}
<file_sep>/Villa2/CoreData/Categories+CoreDataClass.swift
//
// Categories+CoreDataClass.swift
// Villa2
//
// Created by <NAME> on 3/25/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Categories)
public class Categories: NSManagedObject {
}
<file_sep>/Villa2/View/SettingsView/DeliveryLocation.swift
import SwiftUI
import MapKit
struct DeliveryLocationMap: UIViewRepresentable {
@Binding var centerCoordinate: CLLocationCoordinate2D
@Binding var locationManager:CLLocationManager
@Binding var centerToCurrentLocation:Bool
var annotation: MKPointAnnotation?
// var locationManager = CLLocationManager()
class Coordinator: NSObject, MKMapViewDelegate, CLLocationManagerDelegate{
var parent: DeliveryLocationMap
init(_ parent: DeliveryLocationMap){
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
parent.centerCoordinate = mapView.centerCoordinate
let centerAnnotation = MKPointAnnotation()
centerAnnotation.coordinate = mapView.centerCoordinate
parent.annotation = centerAnnotation
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<DeliveryLocationMap>) -> MKMapView {
let mapView = MKMapView()
mapView.showsScale = true
mapView.showsUserLocation = true
mapView.showsCompass = true
mapView.showsBuildings = true
var currentLocation = CLLocation(latitude: 13.7563, longitude: 100.5018)
locationManager.delegate = context.coordinator
locationManager.requestWhenInUseAuthorization()
locationManager.distanceFilter = 1000
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.startUpdatingLocation()
if (CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways)
{
currentLocation = locationManager.location ?? currentLocation
}
if CLLocationManager.headingAvailable()
{
locationManager.headingFilter = 5
locationManager.startUpdatingHeading()
}
let region = MKCoordinateRegion( center: currentLocation.coordinate, latitudinalMeters: CLLocationDistance(exactly: 5000)!, longitudinalMeters: CLLocationDistance(exactly: 5000)!)
mapView.setRegion(mapView.regionThatFits(region), animated: true)
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<DeliveryLocationMap>) {
if annotation?.coordinate.latitude != uiView.annotations.first?.coordinate.latitude {
for oldAnnotation in uiView.annotations{
uiView.removeAnnotation(oldAnnotation)
}
if let annotation = annotation{
uiView.addAnnotation(annotation)
}
}
if self.centerToCurrentLocation {
debugPrint("UIMK try to set new center")
uiView.setCenter(self.locationManager.location?.coordinate ?? uiView.centerCoordinate , animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.centerToCurrentLocation = false
}
}
}
}
struct DeliveryLocation: View {
@State private var centerCoordinate:CLLocationCoordinate2D
@State private var location:MKPointAnnotation?
@State private var locationManger:CLLocationManager
@State var centerToCurrentLocation:Bool
@Binding var isDisplayed:Bool
init(isDisplayed: Binding<Bool>){
self._centerCoordinate = State(initialValue: CLLocationCoordinate2D())
self._location = State(initialValue: nil)
self._locationManger = State(initialValue: CLLocationManager())
self._centerToCurrentLocation = State(initialValue: false)
self._isDisplayed = isDisplayed
}
var body: some View{
ZStack{
ZStack{
DeliveryLocationMap(centerCoordinate: self.$centerCoordinate, locationManager: self.$locationManger, centerToCurrentLocation: self.$centerToCurrentLocation, annotation: self.location)
Image(uiImage: UIImage(systemName: "xmark",withConfiguration: UIImage.SymbolConfiguration(weight: .semibold))!.withTintColor(.gray, renderingMode: .alwaysTemplate))
.opacity(0.5)
}
.frame(alignment:.center)
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
self.centerToCurrentLocation = true
debugPrint("set center to current location")
}) {
Image(systemName: "location")
}
.padding()
.background(Color.black.opacity(0.75))
.foregroundColor(.white)
.font(.title)
.clipShape(Circle())
.padding(.trailing)
Button(action: {
let newLocation = MKPointAnnotation()
newLocation.coordinate = self.centerCoordinate
self.location = newLocation
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.isDisplayed = false
}
}) {
Image(systemName: "checkmark")
}
.padding()
.background(Color.black.opacity(0.75))
.foregroundColor(.white)
.font(.title)
.clipShape(Circle())
.padding(.trailing)
}
}
}
.navigationBarTitle("Delivery Location")
}
}
struct DeliveryLocation_Previews: PreviewProvider {
static var previews: some View {
DeliveryLocation(isDisplayed: .constant(true))
}
}
<file_sep>/Villa2/API/MagentoCodables/Category.swift
//
// Category.swift
// Villa2
//
// Created by <NAME> on 3/24/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
class SampleCategory{
static var category = ProductCategory(id: 1, parentId: 1, name: "mock", isActive: true, position: 1, level: 1, productCount: 1, childrenData: [ProductCategory(id: 1, parentId: 1, name: "mock", isActive: true, position: 1, level: 1, productCount: 1, childrenData: [ProductCategory(id: 1, parentId: 1, name: "mock", isActive: true, position: 1, level: 1, productCount: 1, childrenData: [])])])
}
class SubCategoryList{
}
///// product cat
public struct ProductCategory: Codable, Hashable{
let id: Int
let parentId: Int
let name: String
let isActive: Bool
let position: Int
let level: Int
let productCount: Int
let childrenData:[ProductCategory]
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
enum CodingKeys: String, CodingKey{
case id
case parentId = "parent_id"
case name
case isActive = "is_active"
case position
case level
case productCount = "product_count"
case childrenData = "children_data"
}
}
public struct ProductCatLinearizedCodable: Codable, Hashable{
let id: Int
let parentId: Int
let name: String
let position: Int
let level: Int
let children: String
let includeInMenu: Bool
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
enum CodingKeys: String, CodingKey{
case id
case parentId = "parent_id"
case name
case position
case level
case children
case includeInMenu = "include_in_menu"
}
}
public struct ProductCatLinearizedCodableContainer: Codable{
let items: [ProductCatLinearizedCodable]
}
class ProductCategoryList: ObservableObject{
@Published var products: ProductCategory
init(productCategory:ProductCategory) {
self.products = productCategory
}
}
<file_sep>/Villa2/View/Image/ZoomedImageView.swift
//
// ZoomedImageView.swift
// Villa2
//
// Created by <NAME> on 4/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import KingfisherSwiftUI
struct ZoomedImageView: View {
var product:ProductCore
// @State private var zoomValue:CGFloat = 1
@GestureState private var zoomValue:CGFloat = 1
@State var currentZoomValue:CGFloat = 1
// @GestureState var magnifyBy = CGFloat(1.0)
// @State private var dragAmount = CGSize.zero
@State private var currentPosition: CGSize = .zero
@State private var newPosition: CGSize = .zero
@State private var enabled = false
var body: some View {
GeometryReader{g in
VStack{
// ModalViewIndicator()
KFImage(self.product.wrappedUrl)
.placeholder{
KFImage(self.product.wrappedAlternativeUrl)
.placeholder{
ImagePlaceholder.productPlaceholderImage()
}
.resizable()
.scaledToFit()
}
.scaleEffect(CGFloat(self.currentZoomValue))
.offset(self.currentPosition)
.animation(Animation.default.delay( 0.01))
.gesture(
DragGesture()
.onChanged {
let translation = $0.translation
// self.dragAmount = translation
self.currentPosition = CGSize(width: translation.width + self.newPosition.width, height: translation.height + self.newPosition.height)
}
.onEnded { value in
self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
self.newPosition = self.currentPosition
// self.dragAmount = .zero
// self.enabled.toggle()
}
.simultaneously(with:
MagnificationGesture()
.onChanged({ (newZoom) in
self.currentZoomValue = newZoom
})
.updating(self.$zoomValue, body: { (currenState, gestureState, transaction) in
gestureState = currenState
})
.onEnded({ (magnificationValue) in
debugPrint(magnificationValue)
debugPrint(self.zoomValue)
self.currentZoomValue = magnificationValue
})
)
)
Spacer()
Slider(value: self.$currentZoomValue,in: 0.5...3.0)
.padding()
}
.onAppear{
debugPrint(self.product)
}
// .pinchToZoom()
}
}
}
struct ZoomedImageView_Previews: PreviewProvider {
static var previews: some View {
ZoomedImageView(product: SampleProductCore.productCore)
}
}
<file_sep>/Villa2/View/Tab1HomeView/Tab2SearchView/SearchViewController/SideBar/SearchSideFilterTableView.swift
//
// SearchViewSideBarSearchIcon.swift
// Villa2
//
// Created by <NAME> on 4/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import KingfisherSwiftUI
struct SideBarSearchIcons: View{
var mainCat:[ProductCategory]
var currentCat: Int
@Binding var currentSubCat: Int
var sideBarWidth: CGFloat
var subcat:[ProductCategory] {
get {
return self.currentCat == -1 ? self.mainCat[0].childrenData : self.mainCat[self.currentCat].childrenData
}
}
var body: some View {
HStack{
ScrollView{
VStack(spacing: 10){
// all search icon
Group {
Button(action: {
self.currentSubCat = -1
}){
Text("All Products")
.font(.system(size: 15))
.truncationMode(.tail)
.allowsTightening(true)
.minimumScaleFactor(0.2)
.padding(.horizontal, 5)
.padding(.vertical)
.frame(width: self.sideBarWidth)
}
.buttonStyle(SideIconsButtonStyle(activated: -1 == self.currentSubCat,width: self.sideBarWidth))
}
//other search icons
ForEach(0..<self.subcat.count, id: \.self){subCatId in
Group {
Button(action: {
self.currentSubCat = subCatId
}){
if self.subcat[subCatId].isActive{
Text(self.subcat[subCatId].name)
.font(.system(size: 15))
.truncationMode(.tail)
.allowsTightening(true)
.minimumScaleFactor(0.2)
.padding(.horizontal, 5)
.padding(.vertical)
.frame(width: self.sideBarWidth)
}
}
.buttonStyle(SideIconsButtonStyle(activated: subCatId == self.currentSubCat,width: self.sideBarWidth))
}
}
}
}
.frame(width: self.sideBarWidth, alignment: .leading)
.transition(.move(edge: .leading))
Spacer()
}
}
}
<file_sep>/Villa2/View/Modifiers/TextModifier/ListTextDetailViewModifier.swift
//
// ListTextDetailViewModifier.swift
// Villa2
//
// Created by <NAME> on 4/7/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
import CoreData
struct ListTextDetailViewModifier: ViewModifier {
func body(content: Content) -> some View {
content
.font(.subheadline)
.lineLimit(2)
.frame(alignment: .leading)
}
}
<file_sep>/Villa2/View/Tab1HomeView/NavigationBar/HomeViewNavigationBarLeadingItems.swift
//
// NavigationBarLeadingItems.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
struct HomeViewNavigationBarLeadingItems: View {
@EnvironmentObject var user:CurrentUser
@Binding var showMenu:Bool
@Binding var showLogin:Bool
var body: some View {
HStack{
Text("\(DefaultStore.currentStore?.rawValue ?? "") store")
//
//
// NavigationLink(destination: SearchViewController(mainCatID: -1)) {
// Image("searchIcon")
// .renderingMode(.original)
// .resizable()
// .scaledToFit()
//
// }
// .frame(width: 40, height: 40, alignment: .leading)
// Menu Button
// Button(action: {
// withAnimation {
// self.showMenu.toggle()
// }
// }) {
// Image(systemName: "line.horizontal.3")
// .imageScale(.large)
// }
//
//
Button(action: {
self.showLogin.toggle()
}){
if self.user.isLoggedIn{
Text("\(self.user.name ?? "")")
} else {
Text("login")
}
}
.disabled(user.isLoggedIn)
}
}
}
struct NavigationBarLeadingItems_Previews: PreviewProvider {
static var previews: some View {
HomeViewNavigationBarLeadingItems(showMenu:.constant(false), showLogin: .constant(false))
.environmentObject(CurrentUser(isLoggedIn: true, name: "mock name"))
}
}
<file_sep>/Villa2/View/Tab1HomeView/CartView/CartView.swift
//
// CartView.swift
// Villa2
//
// Created by <NAME> on 3/13/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
import CoreData
struct CartView: View {
// @EnvironmentObject var productList:ProductList
// @EnvironmentObject var rootGeometry:RootGeometry
// @EnvironmentObject var user:CurrentUser
@State var payment = false
var fetchRequest: FetchRequest<ProductCore>
var productCores: FetchedResults<ProductCore>{
self.fetchRequest.wrappedValue
}
@State var address:String = "some address"
init(){
let request: NSFetchRequest<ProductCore> = ProductCore.fetchRequest()
request.fetchLimit = 100
let predicate = NSPredicate(format: "isInCart == TRUE")
request.predicate = predicate
request.sortDescriptors = []
self.fetchRequest = FetchRequest<ProductCore>(fetchRequest: request)
}
var body: some View {
VStack{
ZStack{
Color(UIColor.systemBackground)
CartProductTable( productCores: self.productCores)
}
HStack{
Text("your address is : ")
TextField("address", text: self.$address)
.lineLimit(3)
}
}.navigationBarTitle(
Text("Checkout")
, displayMode: .large)
.navigationBarItems(leading: Text("edit"), trailing: Button(action: {self.payment.toggle()}){Text("pay")})
.sheet(isPresented: $payment){
PaymentView()
}
.onTapGesture {
UIApplication.shared.endEditing()
}
}
}
struct PaymentView: View {
var body: some View {
GeometryReader{ geometry in
NavigationView {
Form {
Section(header: Text("Credit Card").font(.title)) {
VStack(alignment: .center){
Image("visaLogo")
.renderingMode(.original)
.resizable()
.frame(width: self.idealWidth(geometry: geometry) , height: self.idealWidth(geometry: geometry)/2.8)
.cornerRadius(self.idealWidth(geometry: geometry)/20)
.padding()
}
}
.frame(width: self.idealWidth(geometry: geometry),alignment: Alignment.center)
Section(header: Text("Villa Wallet").font(.title)) {
VStack(alignment: .center){
Image("villaLogo")
.renderingMode(.original)
.resizable()
.frame(width: self.idealWidth(geometry: geometry) , height: self.idealWidth(geometry: geometry)/2.8)
.cornerRadius(self.idealWidth(geometry: geometry)/20)
.padding()
}
}
.frame(width: self.idealWidth(geometry: geometry),alignment: Alignment.center)
}
.navigationBarTitle("Payment", displayMode: .large)
}
}
}
func idealWidth(geometry:GeometryProxy)-> CGFloat{
return CGFloat(geometry.size.width - 30)
}
}
struct CartView_Previews: PreviewProvider {
static var previews: some View {
Group {
CartView()
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(RootGeometry(geometry: nil))
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewLayout(.device)
CartView()
.environmentObject(ProductList(products: SampleProductList.products))
.environmentObject(RootGeometry(geometry: nil))
.background(Color(.systemBackground))
.environment(\.colorScheme, .light)
.previewLayout(.device)
PaymentView()
PaymentView()
.environment(\.colorScheme, .dark)
}
.environment(\.managedObjectContext, SampleProductCore.context)
.environmentObject(SampleCurrentUser.user)
}
}
<file_sep>/Villa2/View/tabViewElements/UITabBarControllerWrapper.swift
//
// UITabBarControllerWrapper.swift
// tabBarControllerDemo
//
// Created by <NAME> on 3/14/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import Foundation
import SwiftUI
// 1
struct UITabBarControllerWrapper: UIViewControllerRepresentable {
var viewControllers: [UIViewController]
// 2
func makeUIViewController(context: UIViewControllerRepresentableContext<UITabBarControllerWrapper>) -> UITabBarController {
let tabBar = UITabBarController()
// Configure Tab Bar here, if needed
return tabBar
}
// 3
func updateUIViewController(_ uiViewController: UITabBarController, context: UIViewControllerRepresentableContext<UITabBarControllerWrapper>) {
uiViewController.setViewControllers(self.viewControllers, animated: false)
}
// 4
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject {
var parent: UITabBarControllerWrapper
init(_ controller: UITabBarControllerWrapper) {
self.parent = controller
}
}
}
<file_sep>/Villa2/View/settingsMenu/ProfileView/ProfileMenu.swift
//
// ProfileMenu.swift
// Villa2
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 tenxor. All rights reserved.
//
import SwiftUI
class UserProfile: Hashable {
static func == (lhs: UserProfile, rhs: UserProfile) -> Bool {
return lhs.hashValue > rhs.hashValue
}
var userId:String = "abcd1234"
var SampleProfileData = [
"name":"nic".capitalizingFirstLetter(),
"memberId":"1234",
"birthday": "1 feb 2020",
"membership": "gold",
"points": "123"
]
var image = UIImage(named: "Nic")
func hash(into hasher: inout Hasher) {
hasher.combine(self.userId)
}
}
struct ProfileMenu: View {
var userProfile:UserProfile = UserProfile()
var body: some View {
let keys = userProfile.SampleProfileData.map{$0.key}
let values = userProfile.SampleProfileData.map {$0.value}
return GeometryReader{ g in
List {
Image(uiImage: self.userProfile.image ?? UIImage(named: "VillaPlaceholder")!)
.scaledToFill()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white , lineWidth: 10).shadow(radius: 2).opacity(0.6))
.shadow(radius: 2)
.padding()
.frame(width: g.size.width, height: g.size.width, alignment: .center)
.listRowInsets(EdgeInsets(top: -20, leading: 0, bottom: -20, trailing: -20))
ForEach(keys.indices) {index in
HStack {
Text(keys[index].capitalizingFirstLetter()).font(.headline)
.frame(width: 150, alignment: .leading)
Text("\(values[index])").font(.subheadline)
.frame(alignment: .leading)
}
}
}
}
}
}
struct ProfileMenu_Previews: PreviewProvider {
static var previews: some View {
ProfileMenu()
}
}
<file_sep>/Villa2/CoreData/ProductCore+CoreDataProperties.swift
//
// ProductCore+CoreDataProperties.swift
// Villa2
//
// Created by <NAME> on 4/2/20.
// Copyright © 2020 tenxor. All rights reserved.
//
//
import Foundation
import CoreData
extension ProductCore {
@nonobjc public class func fetchRequest() -> NSFetchRequest<ProductCore> {
return NSFetchRequest<ProductCore>(entityName: "ProductCore")
}
@NSManaged public var categoryIds: [String]?
@NSManaged public var imageData: Data?
@NSManaged public var imageUrl: String?
@NSManaged public var isFavourite: Bool
@NSManaged public var isInCart: Bool
@NSManaged public var isInHistory: Bool
@NSManaged public var isRecommended: Bool
@NSManaged public var longDescription: String?
@NSManaged public var metaKeywords: String?
@NSManaged public var name: String?
@NSManaged public var numberInCart: Int16
@NSManaged public var price: Int16
@NSManaged public var productDescription: String?
@NSManaged public var rankingScore: Float
@NSManaged public var sku: String?
@NSManaged public var cat1: String?
@NSManaged public var cat2: String?
@NSManaged public var cat3: String?
@NSManaged public var cat4: String?
}
|
ebe420719b38f195e97ba29c179a7acfa940f5b2
|
[
"Swift"
] | 98 |
Swift
|
thanakijwanavit/Villa2
|
c9f43fdd473d32dba3d1a3ad83f1bece76ff2571
|
4290b06934a8b540911527e2ffafaf11c8948244
|
refs/heads/master
|
<repo_name>Sujoy1/Blinds-Eye<file_sep>/BlindsEye/README.md
# BlindsEye
An IoT based real-time surrounding identification and object detection
<file_sep>/BlindsEye/FYP/load_all_object_names.py
#Load all object names which we have to be detected
def load_all_object_names():
classes=[]
with open("coco.names","r") as f:
classes=f.read().splitlines()
return classes
<file_sep>/BlindsEye/FYP/get_ipaddress.py
import socket
def get_ipaddress():
#Getting the hostname
hostname = socket.gethostname()
#Getting the IP address
ip_address = socket.gethostbyname(hostname)
return ip_address
<file_sep>/BlindsEye/FYP/get_location.py
import geocoder
g = geocoder.ip('me')
print(g.lat)
print(g.lng)
<file_sep>/BlindsEye/FYP/get_data_from_cloud.py
import pymongo
from pymongo import MongoClient
from connect_to_cloud import *
collection = connect_to_cloud()
results = collection.find({})
for x in results:
print(x)<file_sep>/BlindsEye/FYP/create_bounding_boxes.py
import cv2
#Font of parameters
font=cv2.FONT_HERSHEY_PLAIN
def create_bounding_boxes(i, img, boxes, classes, class_ids, confidences, colors):
x,y,w,h=boxes[i]
label=str(classes[class_ids[i]])
confidence=str(round(confidences[i],2))
color=colors[i]
#Creating bounding boxes
cv2.rectangle(img,(x,y),(x+w, y+h),color,2)
#Adding label & confidence over bounding boxes
cv2.putText(img, label + " " + confidence, (x, y+20), font, 2, (255,255,255), 2)
return label, confidence
<file_sep>/README.md
# Blind-s-Eye
Blind's-Eye is a IOT based real time surrounding identification software which helps visually impaired people with neccessary instructions . This has been implemented with YOLO v3 and openCV in python . This is my final year project.
<file_sep>/BlindsEye/FYP/connect_to_cloud.py
import pymongo
from pymongo import MongoClient
def connect_to_cloud():
#Connecting to Mongodb cloud
cluster=MongoClient("mongodb+srv://SujoySeal:<EMAIL>/myFirstDatabase?retryWrites=true&w=majority")
#Assigning database
db=cluster["FYP-Database"]
#Assigning collection
collection=db["Identified-Objects"]
return collection
<file_sep>/BlindsEye/FYP/upload_to_cloud.py
def upload_to_cloud(collection, ip_address, timestamp, label, confidence, address):
#Uploading paramenters to the Mongodb cloud
post = { "ip_address" : ip_address, "timestamp" : timestamp, "label" : label, "confidence" : confidence, "address" : address}
collection.insert_one(post)
<file_sep>/BlindsEye/FYP/BlindsEye_vid.py
#Credits: https://youtu.be/1LCb1PVqzeY
import cv2
from geopy.geocoders import Nominatim
from get_address import *
from upload_to_cloud import *
from get_datetime import *
from get_ipaddress import *
from create_bounding_boxes import *
from text_to_speech import *
from extract_info import *
from connect_to_cloud import *
from load_all_object_names import *
#Connecting to Mongodb cloud
collection=connect_to_cloud()
#Load YOLO Algorithm
net=cv2.dnn.readNet("yolov3.weights","yolov3.cfg")
#To load all objects that have to be detected
classes=load_all_object_names()
#Loading the Video
cap=cv2.VideoCapture(0) #openCV considers "0" as webcam
#Colors of bounding boxes
colors=np.random.uniform(0, 255, size=(len(classes), 3))
while True:
#Extract info from raw image frame
img, height, width, layerOutputs = extract_info_from_image(cap, net)
boxes=[] #bounding boxes
confidences=[] #confidences
class_ids=[] #predicted classes
#Extract all informations from identified objects
extract_info_from_layers(layerOutputs, boxes, confidences, class_ids, height, width)
#Removes redundant boxes and keeping only boxes with high scores
indexes=cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
#Pass all paramaters to show on the output video
if len(indexes)>0:
for i in indexes.flatten():
#Creating bounding boxes
label, confidence = create_bounding_boxes(i, img, boxes, classes, class_ids, confidences, colors)
#Convert identified objects into speech format and play
text_to_speech(label)
#Get timestamp
timestamp=get_datetime()
#Get the address info
address=get_address()
#Get IP Address
ip_address=get_ipaddress()
#Uploading identified objects to the cloud
upload_to_cloud(collection, ip_address, timestamp, label, confidence, address['display_name'])
cv2.imshow("Output",img)
key=cv2.waitKey(1)
#Press esc key to stop the program
if key==27:
break
#Release camera
cap.release()
#Close all output windows
cv2.destroyAllWindows()
<file_sep>/BlindsEye/FYP/get_address.py
#Credits : https://www.thepythoncode.com/article/get-geolocation-in-python
from geopy.geocoders import Nominatim
import time
import geocoder
#Instantiate a new Nominatim client
app = Nominatim(user_agent="BlindsEye")
def get_address(language="en"):
#Get your coordinates
g=geocoder.ip('me')
latitude=g.lat
longitude=g.lng
#Build coordinates string to pass to reverse() function
coordinates = f"{latitude}, {longitude}"
try:
return app.reverse(coordinates, language=language).raw
except:
return get_address_by_location(latitude, longitude)
<file_sep>/BlindsEye/FYP/text_to_speech.py
import os
from gtts import gTTS
def text_to_speech(label):
#Converting text to speech
myobj = gTTS(text=label, lang='en', slow=False)
#Saving the converted audio file into the same directory
myobj.save("Outputs/output.mp3")
#Play the converted file
os.system("start Outputs/output.mp3")
<file_sep>/BlindsEye/FYP/extract_info.py
import cv2
import numpy as np
def extract_info_from_image(cap, net):
#Capture each frames of the video file
_, img=cap.read()
#Capturing its height and width used to scale back to original file
height,width,_=img.shape
#Extracting features to detect objects
blob=cv2.dnn.blobFromImage(img,1/255,(416,416),(0,0,0),swapRB=True,crop=False)
#Inverting blue with red
#bgr->rgb
#We need to pass the img_blob to the algorithm
net.setInput(blob)
output_layers_names=net.getUnconnectedOutLayersNames()
layerOutputs=net.forward(output_layers_names)
return img, height, width, layerOutputs
def extract_info_from_layers(layerOutputs, boxes, confidences, class_ids, height, width):
#Extract all informations form the layers output
for output in layerOutputs:
#Extract information from each of the identified objects
for detection in output:
#Should contain 4 bounding boxes, or 85 parameters
scores=detection[5:] #First 4 parameters are locations(x, y, h, w) and 5th element is confidence
#Get index having maximum scores
class_id=np.argmax(scores)
confidence=scores[class_id]
#If confidence is strong enough, get locations of those bounding boxes
if confidence>0.5:
center_x=int(detection[0]*width)
center_y=int(detection[1]*height)
w=int(detection[2]*width)
h=int(detection[3]*height)
x=int(center_x-w/2)
y=int(center_y-h/2)
boxes.append([x, y, w, h])
confidences.append((float(confidence)))
class_ids.append(class_id)
<file_sep>/BlindsEye/FYP/get_datetime.py
from datetime import datetime
def get_datetime():
#Get current time
now = datetime.now()
timestamp = now.strftime("%Y/%m/%d %H:%M:%S")
return timestamp
|
04cd8c069d6cc1dc67ca4cc6de5840cd79c1b97a
|
[
"Markdown",
"Python"
] | 14 |
Markdown
|
Sujoy1/Blinds-Eye
|
70b3c35d0b286012286f2d6d22cc95d69ae3622d
|
db9cb7c6abc63540fb8014a17478669114497f70
|
refs/heads/master
|
<repo_name>epicboi-deepubhai/Jackpot-game<file_sep>/Jackpot.py
import random
c = ['@', '?', '#', '$', '!', '1', '2', '3', '4', '5', '00', 'x', ':', '"', '>', '<', '/']
score = 10
ctr = 10
while ctr>0:
ctr -=1
score -= 1
p=input('continue?(y/n)')
l, m, n = random.choice(c), random.choice(c), random.choice(c)
if score == 0:
print('you poor')
break
elif p.lower() == 'y':
print(' |||| ', l, '|||', m, '|||', n, ' |||| ')
if l == '$':
if m == '$':
if n == '$':
print('|||Mega Jackpot!! |||')
score += 1000
else:
print('better luck next time')
elif l == '$':
score += 10
if l == m:
if l == n:
print('jackpot')
score += 100
else:
print('cool')
score+=30
elif l == n:
print('So close :(')
elif n == '!':
score += 8
if n == m:
if n == l:
print('jackpot')
else:
print('nice!')
score += 50
elif n == l:
print('So close :(')
elif m == '#':
score += 6
if m == l:
if m == n:
print('jackpot')
else:
print('cool')
score += 30
elif m == n:
print('nice')
score += 50
elif l == m:
if l == n:
print('jackpot')
score += 100
else:
print('cool')
score += 30
elif m == n:
print('nice!')
score += 50
elif n == l:
print('So close :(')
else:
print('better luck next times')
elif p == 'n':
break
else:
print('Please input a valid option')
score += 1
print(score)
|
76bff3078a1a70022b53818b148cc2f93e1a675e
|
[
"Python"
] | 1 |
Python
|
epicboi-deepubhai/Jackpot-game
|
f2d88a552701c093af97086ebdefa9878a690cfd
|
e0769bde8e38a9e5af8b6be251c78da36c2ed1e2
|
refs/heads/master
|
<repo_name>shijiedong/dome<file_sep>/shane/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from . import models
# Create your views here.
def create_task(request):
#return HttpResponse("<h1>Create Task</h1>")
return render( request, "create_task.html")
def task_router(request):
print "task_router"
task_name = request.POST.get('task_name', 'null')
task_id = request.POST.get('task_id', 0)
print task_name
print task_id
task = models.T1_Task.objects.create(strName=task_name, nTaskID=task_id )
print "taskid:%d" % task.id
if( 1001 == task_id ):
pass
#return render( request, "financial.html", { 'taskid' : task.id })
elif( 1002 == task_id):
pass
#return render( request, "financial.html", { 'taskid' : task.id })
elif( 1003 == task_id ):
pass
#return render( request, "financial.html", { 'taskid' : task.id })
return render( request, "financial.html", { 'taskid' : task.id })
def task_1001(request,task_id):
strname = request.POST.get('name', 'null')
strtype = request.POST.get('type', 'nill')
print strname
print strtype
models.T2_MoneyApplyFor.objects.create( strName=strname, strType=strtype )
return render( request, "financial.html")
def task_1002(request,task_id):
strname = request.POST.get('name', 'null')
strtype = request.POST.get('type', 'nill')
print strname
print strtype
models.T2_TestTask.objects.create(strName=strname, strType=strtype )
return render( request, "financial.html")
<file_sep>/shane/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
"""
T1_Task:
"""
class T1_Task(models.Model):
strName = models.CharField(max_length=20) # 任务名称
nTaskID = models.IntegerField(default = 0) # 当前任务ID
nStatu = models.IntegerField(default = 2) # 当前任务状态,
create_at = models.DateTimeField(auto_now_add=True) # 创建时间
update_at = models.DateTimeField(auto_now=True) # 更新时间
def __unicode__(self):
return self.strName
class T1_Poot(models.Model):
nT1_TaskID = models.IntegerField() # 流程ID
nTaskID = models.IntegerField() # 任务ID
create_at = models.DateTimeField(auto_now_add=True) # 创建时间
class T2_MoneyApplyFor(models.Model): # 任务ID 1001
nTaskID = models.IntegerField() # 当前任务ID
nStatu = models.IntegerField( default = 1 ) # 当前任务状态
nMoney = models.IntegerField( default = 0 ) # 金额
strNode = models.CharField( max_length = 200 ) # 备注
create_at = models.DateTimeField(auto_now_add=True) # 创建时间
update_at = models.DateTimeField(auto_now=True) # 更新时间
def __unicode__(self):
return self.strNode
class T2_TestTask(models.Model): # 任务ID 1002
nTaskID = models.IntegerField() # 当前任务ID
nStatus = models.IntegerField( default = 1 ) # 当前任务状态
nMoney = models.IntegerField( default = 0 ) # 金额
strNode = models.CharField( max_length = 200 ) # 备注
create_at = models.DateTimeField(auto_now_add=True) # 创建时间
update_at = models.DateTimeField(auto_now=True) # 更新时间
def __unicode__(self):
return self.strNode
<file_sep>/dome/urls.py
"""dome URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
import shane.views as dome_task
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^task/', dome_task.create_task),
url(r'^rout/', dome_task.task_router),
url(r'^add1001/', dome_task.task_1001),
url(r'^add1002/', dome_task.task_1002),
]
|
313f65650d53ebf98a00cbe0cc8364e4f6cc53ba
|
[
"Python"
] | 3 |
Python
|
shijiedong/dome
|
6e107eb5dba04b3a67852d05143a760bd22b4bf6
|
bad7ef430b42b8eb5ded6fead6841bd5db13a937
|
refs/heads/master
|
<repo_name>Git984265486/HuanJianMVP<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJVehicleList.kt
package com.org.huanjianmvp.Activity
import android.view.View
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.AJVehicleListContrast
import com.org.huanjianmvp.Presenter.AJVehicleListPresenter
import com.org.huanjianmvp.R
/**
* 【安检车辆列表】
* **/
class AJVehicleList : BaseFragment<AJVehicleListPresenter,AJVehicleListContrast.ViewAndPresenter>() {
override fun getContract(): AJVehicleListContrast.ViewAndPresenter {
return object : AJVehicleListContrast.ViewAndPresenter{
}
}
override fun createPresenter(): AJVehicleListPresenter {
return AJVehicleListPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_vehicle_list
}
override fun initViewUI() {
}
override fun initListener() {
}
override fun onClick(view: View?) {
}
override fun destroy() {
}
override fun initDatas() {
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJBaseInfo.kt
package com.org.huanjianmvp.Activity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.org.huanjianmvp.Adapter.AJBaseInfoAdapter
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.AJBaseInfoContrast
import com.org.huanjianmvp.Presenter.AJBaseInfoPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.aj_base_info.*
/**
* 安检基本信息 页面
* */
class AJBaseInfo : BaseFragment<AJBaseInfoPresenter,AJBaseInfoContrast.ViewAndPresenter>() {
var adapter: AJBaseInfoAdapter? = null
override fun getContract(): AJBaseInfoContrast.ViewAndPresenter {
return object : AJBaseInfoContrast.ViewAndPresenter{
}
}
override fun createPresenter(): AJBaseInfoPresenter {
return AJBaseInfoPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_base_info
}
override fun initViewUI() {
var list = ArrayList<String>()
for (i in StaticValues.AJBaseInfoText.indices){
list.add(StaticValues.AJBaseInfoText[i])
}
adapter = AJBaseInfoAdapter(list)
AJBaseInfoView.layoutManager = LinearLayoutManager(this.context)
AJBaseInfoView.adapter = adapter
}
override fun initListener() {
}
override fun onClick(p0: View?) {
}
override fun destroy() {
}
override fun initDatas() {
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/MenuSetting.kt
package com.org.huanjianmvp.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.MenuSettingContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.MenuSettingPresenter
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.base_setting.*
import java.util.*
class MenuSetting : BaseActivity<MenuSettingPresenter,MenuSettingContrast.ViewAndPresenter>() {
var map = HashMap<String,String>()
override fun getContract(): MenuSettingContrast.ViewAndPresenter {
return object : MenuSettingContrast.ViewAndPresenter{
override fun requestSave(map: Map<String, String>, preferences: SharedPreferences) {
mPresenter.contract.requestSave(map,preferences)
}
override fun requestInitData(preferences: SharedPreferences) {
mPresenter.contract.requestInitData(preferences)
}
override fun responseInitData(map: Map<String, String>) {
if (map.get("radioWJ") == "1"){
radioWJ_Select.isChecked = true
}else{
radioWJ_Default.isChecked = true
}
if (map.get("radioDP") == "1"){
radioDP_Select.isChecked = true
}else{
radioDP_Default.isChecked = true
}
if (map.get("radioXHPZ") == "1"){
radioXHPZ_Select.isChecked = true
}else{
radioXHPZ_Default.isChecked = true
}
if (map.get("radioDTDP") == "1"){
radioDTDP_Select.isChecked = true
}else{
radioDTDP_Default.isChecked = true
}
if (map.get("radioSCFS") == "1"){
radioSCFS_Select.isChecked = true
}else{
radioSCFS_Default.isChecked = true
}
if (map.get("radioSCMS") == "1"){
radioSCMS_Select.isChecked = true
}else{
radioSCMS_Default.isChecked = true
}
if (map.get("radioSJTK") == "1"){
radioSJTK_Select.isChecked = true
}else{
radioSJTK_Default.isChecked = true
}
if (map.get("radioZPZD") == "1"){
radioZPZD_Select.isChecked = true
}else{
radioZPZD_Default.isChecked = true
}
}
}
}
override fun createPresenter(): MenuSettingPresenter {
return MenuSettingPresenter()
}
override fun getViewID(): Int {
return R.layout.base_setting
}
override fun initViewUI() {
application.addActivity(this@MenuSetting)
}
override fun initListener() {
saveBaseSetting.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view?.id){
R.id.saveBaseSetting->{
var preferences = getSharedPreferences("MenuSetting",0)
if (radioWJ_Select.isChecked){ //外检通道号
map.put("radioWJ","1")
}else{
map.put("radioWJ","0")
}
if (radioDP_Select.isChecked){ //地盘通道号
map.put("radioDP","1")
}else{
map.put("radioDP","0")
}
if (radioXHPZ_Select.isChecked){ //循环拍照
map.put("radioXHPZ","1")
}else{
map.put("radioXHPZ","0")
}
if (radioDTDP_Select.isChecked){ //动态地盘
map.put("radioDTDP","1")
}else{
map.put("radioDTDP","0")
}
if (radioSCFS_Select.isChecked){ //数据上传方式
map.put("radioSCFS","1")
}else{
map.put("radioSCFS","0")
}
if (radioSCMS_Select.isChecked){ //照片上传模式
map.put("radioSCMS","1")
}else{
map.put("radioSCMS","0")
}
if (radioSJTK_Select.isChecked){ //时间调控
map.put("radioSJTK","1")
}else{
map.put("radioSJTK","0")
}
if (radioZPZD_Select.isChecked){ //驻坡制动
map.put("radioZPZD","1")
}else{
map.put("radioZPZD","0")
}
contract.requestSave(map,preferences)
var intentFunction = Intent(this@MenuSetting,Function::class.java)
var bundle = Bundle()
bundle.putSerializable("data",intent.getSerializableExtra("data") as UserData)
intentFunction.putExtras(bundle)
startActivity(intentFunction)
this.finish()
}
}
}
override fun destroy() {
}
override fun initDatas() {
var preferences = getSharedPreferences("MenuSetting",0)
contract.requestInitData(preferences)
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/Function.kt
package com.org.huanjianmvp.Activity
import android.content.Intent
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.FunctionContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.FunctionActivityPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.FileUtils
import com.org.huanjianmvp.Utils.SQLiteFunction
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.function.*
/**
* 功能页面
* **/
class Function : BaseActivity<FunctionActivityPresenter,FunctionContrast.ViewAndPresenter>() {
var user : UserData? = null
var bundle: Bundle? = null
override fun getContract(): FunctionContrast.ViewAndPresenter {
return object : FunctionContrast.ViewAndPresenter{
}
}
override fun createPresenter(): FunctionActivityPresenter {
return FunctionActivityPresenter()
}
override fun getViewID(): Int {
return R.layout.function
}
override fun initViewUI() {
application.addActivity(this@Function)
user = intent.getSerializableExtra("data") as UserData
funCarNumType.text = user?.sex
funSerialNumber.text = user?.userName
funCarType.text = user?.age
funCarNumber.text = user?.userName
user?.ShowLog()
Log.e("功能页面打印数据","【完毕】")
}
override fun initListener() {
save.setOnClickListener(this)
test.setOnClickListener(this)
testBtn1.setOnClickListener(this)
testBtn2.setOnClickListener(this)
testBtn3.setOnClickListener(this)
testBtn4.setOnClickListener(this)
drawerMenu.setNavigationItemSelectedListener ({item->
when(item.itemId){
R.id.uploadStatus->{
Log.e("侧滑菜单","照片上传状态")
var uploadStatus = Intent(this@Function,MenuSetting::class.java)
var bundle = Bundle()
bundle.putSerializable("data",user)
uploadStatus.putExtras(bundle)
startActivity(uploadStatus)
}
R.id.baseSetting->{
Log.e("侧滑菜单","基本参数设置")
var intentSetting = Intent(this@Function,MenuSetting::class.java)
var bundle = Bundle()
bundle.putSerializable("data",user)
intentSetting.putExtras(bundle)
startActivity(intentSetting)
}
R.id.updatePassword->{
Log.e("侧滑菜单","密码更改")
var updatePassword = Intent(this@Function,MenuSetting::class.java)
var bundle = Bundle()
bundle.putSerializable("data",user)
updatePassword.putExtras(bundle)
startActivity(updatePassword)
}
}
false
})
}
override fun onClick(view: View?) {
when(view!!.id){
R.id.save ->{
var intent = Intent(this@Function,InspectionAndPhotograph::class.java)
//bundle!!.putSerializable("data",user)
intent.putExtras(bundle)
startActivity(intent)
}
R.id.test->{
var lite = SQLiteFunction(this@Function,StaticValues.SQLiteName,null,StaticValues.SQLiteVersion)
lite.create() //创建表格
//var bitmap = BitmapFactory.decodeResource(resources,R.drawable.icon,null)
//lite.insertData("admin","0",bitmap) //插入数据到SQLite数据库
//lite.LogData()
var bitmap = lite.queryData("admin") //通过name字段查找返回bitmap
//lite.updateData("1","admin" , bitmap) //通过name字段更新status
//Log.e("bitmap的长度",bitmap.width.toString())
test.background = FileUtils.bitmapToDrawable(bitmap)
}
R.id.testBtn1->{
var AJCheck = Intent(this@Function,AJCheckAndPhotoAndBaseInfo::class.java)
AJCheck.putExtras(bundle)
startActivity(AJCheck)
}
R.id.testBtn2->{
var AJPhotoIntent = Intent(this@Function,AJVehicleListAndInitLoginAndRecheckLogin::class.java)
AJPhotoIntent.putExtras(bundle)
startActivity(AJPhotoIntent)
}
R.id.testBtn3->{
var chassisIntent = Intent(this@Function , Chassis::class.java)
startActivity(chassisIntent)
}
R.id.testBtn4->{
}
}
}
override fun destroy() {
[email protected]()
}
override fun initDatas() {
bundle = Bundle()
bundle!!.putSerializable("data",user)
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
[email protected]()
return super.onKeyDown(keyCode, event)
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJVehicleListAndInitLoginAndRecheckLogin.kt
package com.org.huanjianmvp.Activity
import android.graphics.Color
import android.support.v4.app.Fragment
import android.view.View
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.AJVehicleListInitLoginRecheckLoginContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.AJVehicleListInitLoginRecheckLoginPresenter
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.aj_vehiclelist__initlogin_rechecklogin.*
/**
* 安检的 【车辆列表、初检登录、复检登录】 导航页
* **/
class AJVehicleListAndInitLoginAndRecheckLogin : BaseActivity<AJVehicleListInitLoginRecheckLoginPresenter,
AJVehicleListInitLoginRecheckLoginContrast.ViewAndPresenter>() {
var user : UserData? = null
private var tabText = arrayOf("车辆列表", "初检登录", "复检登录")
private var fragments = arrayListOf<Fragment>()
override fun getContract(): AJVehicleListInitLoginRecheckLoginContrast.ViewAndPresenter {
return object : AJVehicleListInitLoginRecheckLoginContrast.ViewAndPresenter{
}
}
override fun createPresenter(): AJVehicleListInitLoginRecheckLoginPresenter {
return AJVehicleListInitLoginRecheckLoginPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_vehiclelist__initlogin_rechecklogin
}
override fun initViewUI() {
application.addActivity(this@AJVehicleListAndInitLoginAndRecheckLogin) //添加页面到统一管理中
fragments.add(AJVehicleList())
fragments.add(AJInitLogin())
fragments.add(AJRecheckLogin())
AJLoginNavigationBar.defaultSetting()
AJLoginNavigationBar.titleItems(tabText) //tab文字集合
AJLoginNavigationBar.fragmentList(fragments) //Fragment集合
AJLoginNavigationBar.tabTextSize(18) //tab文字大小
AJLoginNavigationBar.navigationHeight(40) //导航栏高度
AJLoginNavigationBar.normalTextColor(Color.parseColor("#ffffff")) //字体未选中的颜色
AJLoginNavigationBar.selectTextColor(Color.parseColor("#FF0000")) //字体选中的颜色
AJLoginNavigationBar.navigationBackground(Color.parseColor("#5bc0de")) //导航栏背景色 3F9AE2
AJLoginNavigationBar.fragmentManager(supportFragmentManager)
AJLoginNavigationBar.build()
}
override fun initListener() {
}
override fun onClick(view: View?) {
}
override fun destroy() {
}
override fun initDatas() {
user = intent.getSerializableExtra("data") as UserData //获取传递过来的对象数据
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/InspectAdapter.kt
package com.org.huanjianmvp.Adapter
import android.graphics.Color
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StringUtils
import kotlinx.android.synthetic.main.inspect_item.view.*
import java.util.HashMap
/**
* 【外检检验项适配器】
* Created by Administrator on 2020/8/25.
*/
class InspectAdapter(list: ArrayList<inspectCheck>) : RecyclerView.Adapter<InspectAdapter.inspectHolder>() {
var listData = ArrayList<inspectCheck>() //TextView初始赋值数据
var spinnerMap = HashMap<String , String>() //每次改变在监听中更新数据
init {
listData = list
for (i in listData.indices){ // i 从 0 开始
var mayKey = StringUtils.inspectMapKey(listData[i].title)
spinnerMap.put(mayKey,"1")
Log.e("【初始中的值】",spinnerMap.get(mayKey)+"\t\t【map的key值】\t\t"+mayKey+"\t\ti的值为:"+i)
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): inspectHolder {
var view = LayoutInflater.from(parent?.context).inflate(R.layout.inspect_item,parent,false)
var holder = inspectHolder(view)
return holder
}
override fun getItemCount(): Int {
return listData.size
}
override fun onBindViewHolder(holder: inspectHolder?, position: Int) {
//holder?.textView?.text = (position+1).toString()+ "." + listData[position]
holder?.textView?.text = (position + 1).toString() + "." + listData[position].title //设置标题内容
if (listData[position].isCheck){
holder?.textResult?.text = "是"
//holder?.textResult?.setTextColor(Color.GREEN)
}else{
holder?.textResult?.text = "否"
//holder?.textResult?.setTextColor(Color.RED)
}
holder?.textResult?.setOnClickListener {
var mapKey = StringUtils.inspectMapKey(listData[position].title)
Log.e("position的值为", position.toString() +"\tmap的键值为:\t" + mapKey)
/**【将每一个spinner的选中值都放到map中储存起来、改变的时候更新map中的数据】**/
if (listData[position].isCheck){
holder?.textResult?.text = "否"
//holder?.textResult?.setTextColor(Color.RED)
listData[position].isCheck = false
spinnerMap.put(mapKey ,"0")
}else{
holder?.textResult?.text = "是"
//holder?.textResult?.setTextColor(Color.GREEN)
listData[position].isCheck = true
spinnerMap.put(mapKey ,"1")
}
}
}
class inspectHolder(view : View) : RecyclerView.ViewHolder(view){
var textView = view.inspect_Text
var textResult = view.textResult
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/ListDatasActivityPresenter.kt
package com.org.huanjianmvp.Presenter
import android.content.Context
import android.support.v7.widget.RecyclerView
import cn.pedant.SweetAlert.SweetAlertDialog
import com.org.huanjianmvp.Activity.ListDatas
import com.org.huanjianmvp.Adapter.ListDatasAdapter
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.ListDatasContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Model.ListDatasActivityModel
/**
* Created by Administrator on 2020/8/19.
*/
class ListDatasActivityPresenter: BaseActivityPresenter<ListDatas, ListDatasActivityModel, ListDatasContrast.ViewAndPresenter>() {
override fun getContract(): ListDatasContrast.ViewAndPresenter {
return object : ListDatasContrast.ViewAndPresenter{
override fun requestExit(alert: SweetAlertDialog) {
mModel.contract.exitAction(alert)
}
override fun responseExit(isExit: Boolean?) {
weakView.get()?.contract?.responseExit(isExit)
}
override fun requestData() {
mModel.contract.dataSource()
}
override fun responseData(list: List<UserData>) {
weakView.get()?.contract?.responseData(list)
}
override fun requestRefresh(list: List<UserData>, rv: RecyclerView, context: Context, clas: Class<*>) {
mModel.contract.refreshData(list,rv,context,clas)
}
override fun responseRefresh(adapter: ListDatasAdapter) {
weakView.get()?.contract?.responseRefresh(adapter)
}
override fun requestFind(string: String) {
mModel.contract.dataFind(string)
}
override fun responseFind(list: List<UserData>) {
weakView.get()?.contract?.responseFind(list)
}
}
}
override fun createModel(): ListDatasActivityModel {
return ListDatasActivityModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/SettingModel.kt
package com.org.huanjianmvp.Model
import android.content.SharedPreferences
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.SettingContrast
import com.org.huanjianmvp.Presenter.SettingPresenter
/**
* Created by Administrator on 2020/8/28.
*/
class SettingModel(mPresenter:SettingPresenter?): BaseActivityModel<SettingPresenter,SettingContrast.Model>(mPresenter) {
override fun getContract(): SettingContrast.Model {
return object : SettingContrast.Model{
/**【保存数据】**/
override fun saveAction(map: Map<String, String> , preferences: SharedPreferences) {
var editor = preferences.edit()
editor.putString("IP", map.get("strIP").toString())
editor.putString("FTP",map.get("strFTP").toString())
editor.putString("JGBH",map.get("Number").toString())
editor.putString("SXDDIP",map.get("Dispatch").toString())
editor.putString("JCXDH",map.get("CheckNum").toString())
if (map.get("upType").equals("存本地")){
editor.putInt("TPSC",0)
}else{
editor.putInt("TPSC",1)
}
editor.commit()
}
/**【获取保存的数据】**/
override fun initDataAction(preferences: SharedPreferences) {
var map = HashMap<String,String>()
map.put("strIP",preferences.getString("IP", "")) //IP地址
map.put("strFTP",preferences.getString("FTP", "")) //FTP地址
map.put("Number",preferences.getString("JGBH", "")) //检测站编号
map.put("Dispatch",preferences.getString("SXDDIP", "")) //上线调度地址
map.put("CheckNum",preferences.getString("JCXDH", "")) //检验机构检测线代号
map.put("upType",preferences.getInt("TPSC",0).toString()+"") //上传方式
presenter.contract.responseInitData(map)
}
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/ChassisContrast.kt
package com.org.huanjianmvp.Contrast
/**
* 底盘契约类
* Created by Administrator on 2020/9/22.
*/
interface ChassisContrast {
interface Model{}
interface ViewAndPresenter{}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJBaseInfoPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJBaseInfo
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.AJBaseInfoContrast
import com.org.huanjianmvp.Model.AJBaseInfoModel
/**
* Created by Administrator on 2020/9/4.
*/
class AJBaseInfoPresenter : BaseFragmentPresenter<AJBaseInfo,AJBaseInfoModel,AJBaseInfoContrast.ViewAndPresenter>(){
override fun getContract(): AJBaseInfoContrast.ViewAndPresenter {
return object : AJBaseInfoContrast.ViewAndPresenter{
}
}
override fun createModel(): AJBaseInfoModel {
return AJBaseInfoModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJVehicleListInitLoginRecheckLoginPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJVehicleListAndInitLoginAndRecheckLogin
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.AJVehicleListInitLoginRecheckLoginContrast
import com.org.huanjianmvp.Model.AJVehicleListInitLoginRecheckLoginModel
/**
* Created by Administrator on 2020/9/16.
*/
class AJVehicleListInitLoginRecheckLoginPresenter: BaseActivityPresenter<AJVehicleListAndInitLoginAndRecheckLogin,AJVehicleListInitLoginRecheckLoginModel,
AJVehicleListInitLoginRecheckLoginContrast.ViewAndPresenter>() {
override fun getContract(): AJVehicleListInitLoginRecheckLoginContrast.ViewAndPresenter {
return object : AJVehicleListInitLoginRecheckLoginContrast.ViewAndPresenter{
}
}
override fun createModel(): AJVehicleListInitLoginRecheckLoginModel {
return AJVehicleListInitLoginRecheckLoginModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/PhotographFragmentModel.kt
package com.org.huanjianmvp.Model
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.StrictMode
import android.provider.MediaStore
import android.util.Log
import com.org.huanjianmvp.Activity.ImageShow
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.PhotographContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.PhotographFragmentPresenter
import com.org.huanjianmvp.Utils.FileUtils
import com.org.huanjianmvp.Utils.SQLiteFunction
import com.org.huanjianmvp.Utils.StaticValues
import java.io.File
import java.io.FileInputStream
/**
* Created by Administrator on 2020/8/24.
*/
class PhotographFragmentModel(mPresenter: PhotographFragmentPresenter?):
BaseFragmentModel<PhotographFragmentPresenter,PhotographContrast.Model>(mPresenter) {
override fun getContract(): PhotographContrast.Model {
return object : PhotographContrast.Model{
override fun actionPhotoData(fileName : String , context: Context) {
var inputStream: FileInputStream? = null
try {
inputStream = FileInputStream(FileUtils.createFileFolder() + fileName)
var bitmap = BitmapFactory.decodeStream(inputStream) //获取指定目录下保存的位图
/**【数据保存到数据库中】**/
var lite = SQLiteFunction(context, StaticValues.SQLiteName,null, StaticValues.SQLiteVersion)
lite.insertData(fileName,"0",bitmap) //保存图片名字、上传状态、位图到SQLite中
var waterMark = FileUtils.bitmapWaterMark(bitmap) //给位图添加水印
FileUtils.overWriteFile(waterMark , FileUtils.createFileFolder()+fileName) //水印位图覆盖原来的图片
}catch ( ex : Exception){
ex.printStackTrace()
presenter.weakView.get()!!.responseError(ex.message , ex)
}finally {
inputStream?.close()
}
}
/**【图片长按处理】**/
override fun actionOnLongClick(context: Context, user: UserData) {
var intentPhoto = Intent("android.media.action.IMAGE_CAPTURE")
var fileName = user.age + "_" + user.userName + ".jpg" //文件名字【流水号 + 照片名】
Log.e("图片名字","\t\t" + fileName)
var file = File(FileUtils.createFileFolder() + fileName)//新建一个文件
var uri = Uri.fromFile(file) as Uri //将File文件转换成Uri以启动相机程序
intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT , uri) //指定图片输出地址
presenter.contract.responseOnLongClick(intentPhoto) //返回Intent
}
/**【图片点击处理】**/
override fun actionOnClick(context: Context, user: UserData) {
var fileName = user.age + "_" + user.userName + ".jpg" //文件名字【流水号 + 照片名】
if (FileUtils.fileIsExists(fileName)) { //判断目录下是否存在文件
var intent = Intent(context , ImageShow::class.java)
intent.putExtra("fileName",fileName) //传递文件名字
context.startActivity(intent)
}
}
/**【获取数据】**/
override fun actionGetData(user : UserData) {
/**
* android.os.FileUriExposedException: file:///storage/emulated/0/ilive/images/photophoto.jpeg
* exposed beyond app through ClipData.Item.getUri()
* 下面三行解决此处问题
* **/
var builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
builder.detectFileUriExposure()
var arrayList =ArrayList<UserData>()
//模拟数据
var user1 = UserData()
user1.age = user!!.userName
user1.userName = "车辆VIN照"
var user2 = UserData()
user2.age = user!!.userName
user2.userName = "车辆排气照"
var user3 = UserData()
user3.age = user!!.userName
user3.userName = "燃油蒸发控制系统照"
var user4 = UserData()
user4.age = user!!.userName
user4.userName = "张三"
arrayList.add(user1)
arrayList.add(user2)
arrayList.add(user3)
arrayList.add(user4)
var arrayListSpinner = ArrayList<String>()
arrayListSpinner.add("车辆VIN照")
arrayListSpinner.add("车辆排气照")
arrayListSpinner.add("燃油蒸发控制系统照")
arrayListSpinner.add("污染控制装置照")
presenter.contract.responseData(arrayList , arrayListSpinner)
}
/**【图片添加处理】**/
override fun actionAddImage(arrayLists: ArrayList<UserData>, strSelect: String) {
var isHave = false
var user = UserData()
for (i in arrayLists.indices) {
if (strSelect == arrayLists[i].userName) {
isHave = true
break
}
}
if (!isHave){
user.age = arrayLists[0].age
user.userName = strSelect
arrayLists.add(user)
presenter.contract.responseAddImg(isHave,arrayLists)
}
}
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJCheckAndPhotoAndBaseInfo.kt
package com.org.huanjianmvp.Activity
import android.graphics.Color
import android.support.v4.app.Fragment
import android.view.KeyEvent
import android.view.View
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.AJCheckPhotoBaseContrast
import com.org.huanjianmvp.Presenter.AJCheckPhotoBasePresenter
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.aj_check__photo__baseinfo.*
/**
* 安检的 【外检检验、外检拍照、基本信息】 导航页
* **/
class AJCheckAndPhotoAndBaseInfo : BaseActivity<AJCheckPhotoBasePresenter,AJCheckPhotoBaseContrast.ViewAndPresenter>() {
private var tabText = arrayOf("外检检验", "外检拍照", "基本信息")
private var fragments = arrayListOf<Fragment>()
override fun getContract(): AJCheckPhotoBaseContrast.ViewAndPresenter {
return object : AJCheckPhotoBaseContrast.ViewAndPresenter{
}
}
override fun createPresenter(): AJCheckPhotoBasePresenter {
return AJCheckPhotoBasePresenter()
}
override fun getViewID(): Int {
return R.layout.aj_check__photo__baseinfo
}
override fun initViewUI() {
application.addActivity(this@AJCheckAndPhotoAndBaseInfo) //添加页面到统一管理中
fragments.add(AJCheck())
fragments.add(AJPhoto())
fragments.add(AJBaseInfo())
AJnavigationBar.defaultSetting()
AJnavigationBar.titleItems(tabText) //tab文字集合
AJnavigationBar.fragmentList(fragments) //Fragment集合
AJnavigationBar.tabTextSize(18) //tab文字大小
AJnavigationBar.navigationHeight(40) //导航栏高度
AJnavigationBar.normalTextColor(Color.parseColor("#ffffff")) //字体未选中的颜色
AJnavigationBar.selectTextColor(Color.parseColor("#FF0000")) //字体选中的颜色
AJnavigationBar.navigationBackground(Color.parseColor("#5bc0de")) //导航栏背景色
AJnavigationBar.fragmentManager(supportFragmentManager)
AJnavigationBar.build()
}
override fun initListener() {
}
override fun onClick(p0: View?) {
}
override fun destroy() {
[email protected]()
}
override fun initDatas() {
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
[email protected]()
return super.onKeyDown(keyCode, event)
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJPhoto.kt
package com.org.huanjianmvp.Activity
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.org.huanjianmvp.Adapter.AJPhotoAdapter
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.AJCheckContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.AJPhotoPresenter
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.aj_photo.*
/**
* 安检拍照 页面
* */
class AJPhoto : BaseFragment<AJPhotoPresenter,AJCheckContrast.ViewAndPresenter>() {
var user : UserData? = null //传递过来的对象数据
var strSelect: String? = null
var spinnerVal = arrayOf("车辆VIN照", "车辆排气照","燃油蒸发控制系统照","污染控制装置照")
override fun getContract(): AJCheckContrast.ViewAndPresenter {
return object : AJCheckContrast.ViewAndPresenter{
override fun requestData() {
}
override fun responseData(list: List<String>) {
}
}
}
override fun createPresenter(): AJPhotoPresenter {
return AJPhotoPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_photo
}
override fun initViewUI() {
ajCarNumber.text = user!!.userName
ajType.text = user!!.age
ajSerialNumber.text = user!!.sex
ajCarType.text = user!!.userName
var spinnerAdapter = ArrayAdapter<String>(activity,R.layout.spinner_textview,spinnerVal)
ajSpinnerImg.adapter = spinnerAdapter
ajRecyclerView.layoutManager = GridLayoutManager(activity, 2)
var arrayList =ArrayList<UserData>()
//模拟数据
var user1 = UserData()
user1.age = user!!.userName
user1.userName = "车辆VIN照"
var user2 = UserData()
user2.age = user!!.userName
user2.userName = "车辆排气照"
var user3 = UserData()
user3.age = user!!.userName
user3.userName = "燃油蒸发控制系统照"
var user4 = UserData()
user4.age = user!!.userName
user4.userName = "张三"
arrayList.add(user1)
arrayList.add(user2)
arrayList.add(user3)
arrayList.add(user4)
var photoAdapter = AJPhotoAdapter(arrayList , ajRecyclerView , activity)
ajRecyclerView.adapter = photoAdapter
}
override fun initListener() {
ajBtnAdd.setOnClickListener(this)
ajSpinnerImg.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
strSelect = spinnerVal[i]
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
}
override fun onClick(view: View?) {
when(view!!.id){
R.id.ajBtnAdd->{
Log.e("添加的照片" , strSelect)
}
}
}
override fun destroy() {
}
override fun initDatas() {
user = activity.intent.getSerializableExtra("data") as UserData //获取传递过来的对象数据
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/AJPhotoAdapter.kt
package com.org.huanjianmvp.Adapter
import android.content.Context
import android.graphics.BitmapFactory
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.FileUtils
import com.org.huanjianmvp.Utils.SQLiteFunction
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.take_photo_item.view.*
/**
* 安检拍照适配器
* Created by Administrator on 2020/9/22.
*/
class AJPhotoAdapter(list: List<UserData>, recyView: RecyclerView, context: Context) : RecyclerView.Adapter<AJPhotoAdapter.photoShow>(),
View.OnClickListener,View.OnLongClickListener{
private var photoClickListener: PhotoClickListener? = null //声明一下点击接口
private var photoLongClickListener: PhotoLongClickListener? = null //声明一下长按接口
private var recyclerView: RecyclerView? = null
private var dataList : List<UserData>? = null
private var mContext : Context? = null
init {
this.recyclerView = recyView
this.dataList = list
this.mContext = context
}
/**【图片点击监听】**/
fun setOnPhotoClickListener(photoClickListener: PhotoClickListener) {
this.photoClickListener = photoClickListener
}
/**【图片长按监听】**/
fun setOnPhotoLongClickListener(photoLongClickListener: PhotoLongClickListener){
this.photoLongClickListener = photoLongClickListener
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): AJPhotoAdapter.photoShow {
var view = LayoutInflater.from(parent?.context).inflate(R.layout.take_photo_item,parent,false)
view.setOnClickListener(this) //设置点击监听器
view.setOnLongClickListener(this) //设置长按监听器
var holder = AJPhotoAdapter.photoShow(view)
return holder
}
override fun onBindViewHolder(holder: AJPhotoAdapter.photoShow?, position: Int) {
var fileName = dataList!![position].age + "_" + dataList!![position].userName + ".jpg" //图片名字
var lite = SQLiteFunction(mContext, StaticValues.SQLiteName,null, StaticValues.SQLiteVersion)
/**【图片说明】**/
holder!!.textView.text = dataList!![position].userName
/**【图片展示】**/
if (FileUtils.fileIsExists(fileName)){ //判断文件是否存在、true:存在 false:不存在
var filePath = FileUtils.createFileFolder() + fileName //获取目录下的图片
var imgBitmap = BitmapFactory.decodeFile(filePath,null)
Log.e("展示图片来源","\t\t手机文件夹\t\t" + position.toString())
holder!!.imageView.setImageBitmap(imgBitmap)
}else{
var bitmap = lite.queryData(fileName)
Log.e("展示图片来源","\t\tSQLite数据库\t\t" + position.toString())
holder!!.imageView.setImageBitmap(bitmap)
}
/**【图片状态】**/
if(lite.queryUploadStatus(fileName) == "1"){
holder!!.uploadText.text = "已上传"
}else{
holder!!.uploadText.text = "未上传"
}
}
override fun getItemCount(): Int {
return dataList!!.size
}
/**【定义一个内部类,展示的数据由内部类决定】 */
class photoShow(view: View) : RecyclerView.ViewHolder(view){
var imageView: ImageView = view.takePhotoImg //图片
var textView: TextView = view.takePhotoText //图片说明
var uploadText : TextView = view.uploadText //图片上传状态
}
/**【点击事件】**/
override fun onClick(view: View?) {
//根据RecyclerView获得当前View的位置
var position: Int= recyclerView?.getChildAdapterPosition(view)!!
//程序执行到此,会去执行具体实现的onItemClick()方法
if (photoClickListener != null) {
photoClickListener?.onPhotoClick(recyclerView,view,position,dataList!![position])
}
}
/**【长按事件】**/
override fun onLongClick(view: View?): Boolean {
//根据RecyclerView获得当前View的位置
var position: Int= recyclerView?.getChildAdapterPosition(view)!!
//程序执行到此,会去执行具体实现的photoLongClickListener()方法
if (photoLongClickListener!=null){
photoLongClickListener?.onPhotoLongClick(recyclerView,view,position,dataList!![position])
}
return false
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/FunctionActivityModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.FunctionContrast
import com.org.huanjianmvp.Presenter.FunctionActivityPresenter
/**
* Created by Administrator on 2020/8/21.
*/
open class FunctionActivityModel(mPresenter: FunctionActivityPresenter?) : BaseActivityModel<FunctionActivityPresenter, FunctionContrast.Model>(mPresenter) {
override fun getContract(): FunctionContrast.Model {
return object : FunctionContrast.Model {
}
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/ImageShowContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/9/11.
*/
interface ImageShowContrast {
interface Model{}
interface ViewAndPresenter{}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Login.java
package com.org.huanjianmvp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.org.huanjianmvp.Activity.ListDatas;
import com.org.huanjianmvp.Activity.Setting;
import com.org.huanjianmvp.Base.BaseActivity;
import com.org.huanjianmvp.Contrast.LoginContrast;
import com.org.huanjianmvp.Domain.validateCode;
import com.org.huanjianmvp.Internet.ObserverManager;
import com.org.huanjianmvp.Internet.RetrofitManager;
import com.org.huanjianmvp.Presenter.LoginActivityPresenter;
import com.org.huanjianmvp.Utils.AlertDialogUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import io.reactivex.Observable;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* 仅负责展示处理,不涉及逻辑以及数据处理
*
* **/
public class Login extends BaseActivity<LoginActivityPresenter,LoginContrast.ViewAndPresenter> {
private String username , password;
private MaterialEditText userName , passWord;
private BootstrapButton btnLogin , btnExit , btnSetting;
private AlertDialogUtils dialogUtils;
private SweetAlertDialog alert;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private TextView appVersionText;
private AlertDialog dialog;
/**【实现契约接口中的方法】**/
@Override
public LoginContrast.ViewAndPresenter getContract() {
return new LoginContrast.ViewAndPresenter() {
/**【发起登录请求】**/
@Override
public void requestLogin(String userName, String passWord , Context context) {
mPresenter.getContract().requestLogin(userName,passWord , context);
}
/**【响应请求结果】**/
@Override
public void responseResult(String msg) {
if (msg != null){
if (msg.equals("登录成功")){
Intent intent = new Intent(Login.this, ListDatas.class);
startActivity(intent);
Login.this.finish();
}else{
dialogUtils.AlertTitle(msg,"warning");
}
}
}
@Override
public void requestExit(SweetAlertDialog alert) {
mPresenter.getContract().requestExit(alert);
}
@Override
public void responseExit(Boolean isExit) {
if (isExit){
Login.this.finish();
}
}
@Override
public void requestVersion(Context context) {
mPresenter.getContract().requestVersion(context);
}
@Override
public void responseVersion(Map<String,String> map) {
//dialogUtils.AlertTitle(map.get("deviceID"),"success");
appVersionText.setText(map.get("versionName"));
}
@Override
public void requestPermission(Context context) {
mPresenter.getContract().requestPermission(Login.this);
}
@Override
public void requestToken() {
mPresenter.getContract().requestToken();
}
};
}
/**【创建实例化一个Presenter】**/
@Override
public LoginActivityPresenter createPresenter() {
return new LoginActivityPresenter();
}
/**【拿到、引用布局文件】**/
@Override
public int getViewID() {
return R.layout.activity_login;
}
/**【初始化UI组件】**/
@Override
public void initViewUI() {
application.addActivity(Login.this);
appVersionText = findViewById(R.id.appVersionText);
userName = findViewById(R.id.EditTextUserName);
passWord = findViewById(R.id.EditTextPassWord);
btnLogin = findViewById(R.id.login);
btnExit = findViewById(R.id.exit);
btnSetting = findViewById(R.id.setting);
dialogUtils = new AlertDialogUtils(this);
alert = dialogUtils.getAlertDialog("warning");
alert.setCancelable(false);
preferences = getSharedPreferences("userName",0);
editor = preferences.edit();
}
/**【初始化监听事件】**/
@Override
public void initListener() {
btnLogin.setOnClickListener(this);
btnExit.setOnClickListener(this);
btnSetting.setOnClickListener(this);
}
/**【销毁时执行方法】**/
@Override
public void destroy() {
if (dialogUtils != null){
dialogUtils.dismissDialog();
}
if (alert != null){
alert.dismiss();
}
dialogUtils = null;
alert = null;
}
/**【初始化数据】**/
@Override
public void initDatas() {
//System.Net.ServicePointManager.ServerCertificateValidationCallback;/* = delegate { return true; };*/
userName.setText(preferences.getString("userName",""));
getContract().requestPermission(Login.this);
getContract().requestVersion(Login.this);
}
/**【报错处理】**/
@Override
public void responseError(Object o, Throwable throwable) {
dialogUtils.AlertTitle(throwable.getMessage(),"error");
}
/**【点击执行事件】**/
@Override
public void onClick(View view) {
username = userName.getText().toString().trim();
password = <PASSWORD>.getText().toString().trim();
switch (view.getId()){
case R.id.login:
editor.putString("userName",username);
editor.commit();
/**【交由契约类处理,契约类交给P层,P层交给M层】**/
getContract().requestLogin(username,password , this);
break;
case R.id.exit:
//getContract().requestToken(); //请求刷新token
//getContract().requestExit(alert); //请求退出软件
//Intent intent2 = new Intent(Login.this, AJVehicleListAndInitLoginAndRecheckLogin.class);
//startActivity(intent2);
dialog = AlertDialogUtils.AlertLoading(Login.this);
Observable<validateCode> observable = RetrofitManager.getRetrofitManager().getApiService().requestCode();
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ObserverManager<validateCode>() {
@Override
public void onSuccess(validateCode validateCode) {
validateCode.dataLog();
if ( validateCode.getCode() == 200 ){
//dialog.dismiss();
}
}
@Override
public void onFail(Throwable throwable) {
Log.e("Throwable",throwable.toString());
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dialog.dismiss();
t.cancel();
}
}, 5000);
}
@Override
public void onFinish() {
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dialog.dismiss();
t.cancel();
}
}, 5000);
Log.e("请求验证码结果","完成");
}
@Override
public void onDisposable(Disposable disposable) {
dialog.show();
}
});
break;
case R.id.setting:
Intent intent = new Intent(Login.this, Setting.class);
startActivity(intent);
break;
}
}
/**【重写返回键】**/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
getContract().requestExit(alert);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/ImageShowPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.ImageShow
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.ImageShowContrast
import com.org.huanjianmvp.Model.ImageShowModel
/**
* Created by Administrator on 2020/9/11.
*/
class ImageShowPresenter: BaseActivityPresenter<ImageShow,ImageShowModel,ImageShowContrast.ViewAndPresenter>() {
override fun getContract(): ImageShowContrast.ViewAndPresenter {
return object : ImageShowContrast.ViewAndPresenter{
}
}
override fun createModel(): ImageShowModel {
return ImageShowModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/SettingPresenter.kt
package com.org.huanjianmvp.Presenter
import android.content.SharedPreferences
import com.org.huanjianmvp.Activity.Setting
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.SettingContrast
import com.org.huanjianmvp.Model.SettingModel
/**
* Created by Administrator on 2020/8/28.
*/
class SettingPresenter: BaseActivityPresenter<Setting,SettingModel,SettingContrast.ViewAndPresenter>() {
override fun getContract(): SettingContrast.ViewAndPresenter {
return object : SettingContrast.ViewAndPresenter{
override fun requestSave(map: Map<String, String> , preferences: SharedPreferences) {
mModel.contract.saveAction(map,preferences)
}
override fun requestInitData(preferences: SharedPreferences) {
mModel.contract.initDataAction(preferences)
}
override fun responseInitData(map: Map<String, String>) {
weakView.get()?.contract?.responseInitData(map)
}
}
}
override fun createModel(): SettingModel {
return SettingModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJVehicleListInitLoginRecheckLoginModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.AJVehicleListInitLoginRecheckLoginContrast
import com.org.huanjianmvp.Presenter.AJVehicleListInitLoginRecheckLoginPresenter
/**
* Created by Administrator on 2020/9/16.
*/
class AJVehicleListInitLoginRecheckLoginModel(mPresenter: AJVehicleListInitLoginRecheckLoginPresenter): BaseActivityModel<AJVehicleListInitLoginRecheckLoginPresenter,
AJVehicleListInitLoginRecheckLoginContrast.Model>(mPresenter) {
override fun getContract(): AJVehicleListInitLoginRecheckLoginContrast.Model {
return object : AJVehicleListInitLoginRecheckLoginContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/PhotographContrast.kt
package com.org.huanjianmvp.Contrast
import android.content.Context
import android.content.Intent
import com.org.huanjianmvp.Domain.UserData
/**
* Created by Administrator on 2020/8/24.
*/
interface PhotographContrast {
interface Model{
/**【添加图片处理】**/
fun actionAddImage(arrayList: ArrayList<UserData> , strSelect : String)
/**【获取数据处理】**/
fun actionGetData(user : UserData)
/**【点击事件处理】**/
fun actionOnClick(context: Context , user: UserData)
/**【长按事件处理】**/
fun actionOnLongClick(context: Context , user: UserData)
/**【拍照返回数据处理】**/
fun actionPhotoData(fileName : String , context: Context)
}
interface ViewAndPresenter{
/**【请求获取数据事件】**/
fun requestData(user : UserData)
/**【响应获取数据事件】**/
fun responseData(arrayList: ArrayList<UserData> , arraySpinnerStr: ArrayList<String>)
/**【请求添加图片】**/
fun requestAddImg(arrayList: ArrayList<UserData> , strSelect : String)
/**【响应添加图片】**/
fun responseAddImg(boolean: Boolean , arrayLists: ArrayList<UserData>)
/**【请求图片点击事件】**/
fun requestOnClick(context: Context , user: UserData)
/**【请求图片长按事件】**/
fun requestOnLongClick(context: Context , user: UserData)
/**【响应图片长按事件】**/
fun responseOnLongClick(intent: Intent)
/**【请求拍照返回数据处理】**/
fun requestPhotoData(fileName : String , context: Context)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJVehicleListPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJVehicleList
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.AJVehicleListContrast
import com.org.huanjianmvp.Model.AJVehicleListModel
/**
* Created by Administrator on 2020/9/16.
*/
class AJVehicleListPresenter: BaseFragmentPresenter<AJVehicleList , AJVehicleListModel ,AJVehicleListContrast.ViewAndPresenter>() {
override fun getContract(): AJVehicleListContrast.ViewAndPresenter {
return object : AJVehicleListContrast.ViewAndPresenter{
}
}
override fun createModel(): AJVehicleListModel {
return AJVehicleListModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/Photograph.kt
package com.org.huanjianmvp.Activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.org.huanjianmvp.Adapter.PhotoAdapter
import com.org.huanjianmvp.Adapter.PhotoClickListener
import com.org.huanjianmvp.Adapter.PhotoLongClickListener
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.PhotographContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.PhotographFragmentPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.SQLiteFunction
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.photograph.*
/**
* 外检拍照页面
**/
class Photograph : BaseFragment<PhotographFragmentPresenter,PhotographContrast.ViewAndPresenter>() {
var user : UserData? = null //传递过来的对象数据
var arrayList = ArrayList<UserData>()
var spinnerVal = arrayOf("车辆VIN照", "车辆排气照","燃油蒸发控制系统照","污染控制装置照")
var arraySpinner = ArrayList<String>() //spinner下拉添加的图片
var strSelect : String = "" //选择要添加的图片
var photoAdapter : PhotoAdapter? = null //recyclerView适配器
var fileName : String = "" //文件名字【流水号 + 照片名】
override fun getContract(): PhotographContrast.ViewAndPresenter {
return object : PhotographContrast.ViewAndPresenter{
override fun requestPhotoData(fileName : String , context: Context) {
mPresenter.contract.requestPhotoData(fileName , context)
}
override fun responseOnLongClick(intent: Intent) {
startActivityForResult(intent,103) //启动相机
}
override fun requestOnLongClick(context: Context, user: UserData) {
mPresenter.contract.requestOnLongClick(context,user)
}
override fun requestOnClick(context: Context, user: UserData) {
mPresenter.contract.requestOnClick(activity,user)
}
override fun requestData(user : UserData) {
mPresenter.contract.requestData(user)
}
override fun responseData(arrayLists: ArrayList<UserData> , arraySpinnerStr: ArrayList<String>) {
arrayList = arrayLists
arraySpinner = arraySpinnerStr
}
override fun requestAddImg(arrayList: ArrayList<UserData>, strSelect: String) {
mPresenter.contract.requestAddImg(arrayList,strSelect)
}
override fun responseAddImg(boolean: Boolean , arrayLists: ArrayList<UserData>) {
if (!boolean){
arrayList = arrayLists
photoAdapter = PhotoAdapter(arrayList,recycler_View,activity)
/**【绑定点击事件】**/
photoAdapter?.setOnPhotoClickListener(PhotoClickListener { parent, view, position, data ->
contract.requestOnClick(activity , data) //点击事件处理绑定
fileName = data!!.age + "_" + data!!.userName + ".jpg" //文件名字、原始文件,未添加文字水印【流水号 + 照片名】
})
/**【绑定长按事件】**/
photoAdapter?.setOnPhotoLongClickListener(PhotoLongClickListener{parent, view, position, data ->
contract.requestOnLongClick(activity,data) //长按事件处理绑定
fileName = data!!.age + "_" + data!!.userName + ".jpg" //文件名字、原始文件,未添加文字水印【流水号 + 照片名】
})
recycler_View.adapter = photoAdapter
}
}
}
}
override fun createPresenter(): PhotographFragmentPresenter {
return PhotographFragmentPresenter()
}
override fun getViewID(): Int {
return R.layout.photograph
}
override fun initViewUI() {
/**【绑定适配器】**/
recycler_View.adapter = photoAdapter
recycler_View.layoutManager = GridLayoutManager(activity, 2)
var adapter = ArrayAdapter<String>(activity,R.layout.spinner_textview,spinnerVal)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerImg.adapter = adapter
funCarNumber.text = user?.userName //车牌号码
funCarType.text = user?.age //品牌型号
funSerialNumber.text = user?.userName //检验流水号
funCarNumType.text = user?.sex //号牌种类
}
override fun initListener() {
btnAdd.setOnClickListener(this)
/**【绑定spinner选择事件】**/
spinnerImg.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
strSelect = spinnerVal[i]
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
/**【绑定图片点击事件】**/
photoAdapter?.setOnPhotoClickListener(PhotoClickListener { parent, view, position, data ->
contract.requestOnClick(activity , data) //点击事件处理绑定
fileName = data!!.age + "_" + data!!.userName + ".jpg" //文件名字、原始文件,未添加文字水印【流水号 + 照片名】
//Log.e("图片点击事件名字","\t\t" + fileName)
})
/**【绑定图片长按事件】**/
photoAdapter?.setOnPhotoLongClickListener(PhotoLongClickListener{parent, view, position, data ->
contract.requestOnLongClick(activity,data) //长按事件处理绑定
fileName = data!!.age + "_" + data!!.userName + ".jpg" //文件名字、原始文件,未添加文字水印【流水号 + 照片名】
//Log.e("图片长按事件名字","\t\t" + fileName)
})
}
override fun onClick(view: View?) {
when(view?.id){
R.id.btnAdd ->{
contract.requestAddImg( arrayList , strSelect )
}
}
}
override fun destroy() {
activity.finish()
}
override fun initDatas() {
user = activity.intent.getSerializableExtra("data") as UserData //获取传递过来的对象数据
user?.ShowLog()
Log.e("外检拍照页面打印数据","【完毕】")
contract.requestData(user!!) //请求初始数据
/**【初始化适配器】**/
photoAdapter = PhotoAdapter(arrayList , recycler_View , activity)
}
/**【数据重新初始化、刷新数据】**/
override fun onResume() {
super.onResume()
photoAdapter = PhotoAdapter(arrayList,recycler_View,activity) //重新初始化适配器,刷新数据
recycler_View.adapter = photoAdapter
initListener() //初始化监听
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
/**【回调函数】**/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK){
when(requestCode){
103 ->{
contract.requestPhotoData(fileName , activity) //拍照返回数据处理
var lite = SQLiteFunction(activity,StaticValues.SQLiteName,null,StaticValues.SQLiteVersion)
lite.updateStatus(fileName , "1") //更新数据库中图片上传状态
lite.LogData()
recycler_View.adapter = photoAdapter //重新加载数据
}
}
}
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Internet/ObserverManager.java
package com.org.huanjianmvp.Internet;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
* Observer封装、可在各个方法中做一些封装或数据处理
* 由子类来实现抽象方法
* Created by Administrator on 2020/8/20.
*/
public abstract class ObserverManager<T> implements Observer<T> {
@Override
public void onSubscribe(Disposable d) {
onDisposable(d);
}
@Override
public void onNext(T t) {
onSuccess(t);
}
@Override
public void onComplete() {
onFinish();
}
@Override
public void onError(Throwable e) {
onFail(e);
}
public abstract void onSuccess(T t); //调用成功
public abstract void onFail(Throwable throwable); //调用失败或者报错
public abstract void onFinish(); //调用完成
public abstract void onDisposable(Disposable disposable); //调用前准备工作
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/FunctionContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/8/21.
*/
interface FunctionContrast {
interface Model
interface ViewAndPresenter
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJRecheckLoginModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.AJRecheckLoginContrast
import com.org.huanjianmvp.Presenter.AJRecheckLoginPresenter
/**
* Created by Administrator on 2020/9/17.
*/
class AJRecheckLoginModel(mPresenter: AJRecheckLoginPresenter): BaseFragmentModel<AJRecheckLoginPresenter,AJRecheckLoginContrast.Model>(mPresenter) {
override fun getContract(): AJRecheckLoginContrast.Model {
return object : AJRecheckLoginContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/AJRecheckLoginAdapter.kt
package com.org.huanjianmvp.Adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.R
/**
* 安检中复检登陆的适配器
* Created by Administrator on 2020/9/18.
*/
class AJRecheckLoginAdapter(listData: ArrayList<inspectCheck> , context: Context) : RecyclerView.Adapter<AJRecheckLoginAdapter.holderView>() {
var list = ArrayList<inspectCheck>()
var holder: holderView? = null
var mContext: Context? = null
var listRecheck : ArrayList<String> = ArrayList() //每次改变在监听中更新数据
init {
this.list = listData
this.mContext = context
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): holderView {
var view: View = LayoutInflater.from(parent!!.context).inflate(R.layout.aj_recheck_login_item,parent,false)
holder = holderView(view)
return holder as holderView
}
override fun onBindViewHolder(holder: holderView?, position: Int) {
holder!!.textView.text = list[position].title
if (list[position].isCheck){
holder.checkBox.setBackgroundDrawable(mContext!!.resources.getDrawable(R.drawable.checkbox_null))
}else{
holder.checkBox.setBackgroundDrawable(mContext!!.resources.getDrawable(R.drawable.checkbox))
}
holder.checkBox.setOnClickListener {
if (list[position].isCheck){
holder.checkBox.setBackgroundDrawable(mContext!!.resources.getDrawable(R.drawable.checkbox))
list[position].isCheck = false
addListValue(list[position].title) //添加数据到ArrayList中
}else{
holder.checkBox.setBackgroundDrawable(mContext!!.resources.getDrawable(R.drawable.checkbox_null))
list[position].isCheck = true
removeListData(list[position].title) //移除ArrayList中的数据
}
}
}
override fun getItemCount(): Int {
return list.size
}
/**【添加数据到map中】**/
fun addListValue(value: String): String{
var arrayList = value.split("-")
listRecheck.add(arrayList[0])
//listArrayListContent(listRecheck)
return arrayList[0]
}
/**【移除map中的数据】**/
fun removeListData(value: String){
var arrayList = value.split("-")
listRecheck.remove(arrayList[0])
//listArrayListContent(listRecheck)
}
/**【遍历ArrayList中的内容】**/
fun listArrayListContent(list: ArrayList<String>){
for (i in list.indices){
Log.e("【ArrayList中的内容】" , list[i] + "\t...")
}
}
/**【展示内容】**/
class holderView(view: View): RecyclerView.ViewHolder(view){
var checkBox: TextView = view.findViewById(R.id.recheckLoginImg)
var textView: TextView = view.findViewById(R.id.recheckLoginText)
}
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions' //应用替代findViewById插件
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.org.huanjianmvp"
minSdkVersion 20//15
targetSdkVersion 26
versionCode 1
versionName "2.1.7" /*【版本号】*/
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
androidTestCompile('com.android.support:support-annotations:26.1.0') {
force = true
}
//compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:design:26.1.0' //侧滑菜单
compile 'com.beardedhen:androidbootstrap:2.3.2' //开源UI组件
compile 'com.github.f0ris.sweetalert:library:1.5.1' //弹框
compile 'io.reactivex.rxjava2:rxjava:2.2.19' //RxJava2依赖
compile 'io.reactivex.rxjava2:rxandroid:2.1.1' //RxAndroid依赖,切换线程
compile 'com.squareup.retrofit2:converter-gson:2.3.0' // 必要依赖,解析json字符所用
compile 'com.squareup.okhttp3:okhttp:3.1.2' // 网络请求必要依赖
compile 'com.squareup.retrofit2:adapter-rxjava2:2.5.0' // rxjava2和retrofit2的适配器
compile 'in.srain.cube:ultra-ptr:1.0.11' //下拉刷新
compile 'com.rengwuxian.materialedittext:library:2.1.4' //输入框
implementation 'com.android.support:recyclerview-v7:24.2.1' //recyclerview
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.github.Vincent7Wong:EasyNavigation:1.5.0' //底部导航
compile 'com.gavin.com.library:stickyDecoration:1.5.2' //recyclerView的头部
compile 'com.bm.photoview:library:1.4.1' //图片
compile 'com.github.zzz40500:android-shapeLoadingView:1.0.3.2' //内容加载展示(图形)
}
repositories {
mavenCentral() //弹框要求
}
apply plugin: 'kotlin-android'<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJVehicleListModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.AJVehicleListContrast
import com.org.huanjianmvp.Presenter.AJVehicleListPresenter
/**
* Created by Administrator on 2020/9/16.
*/
class AJVehicleListModel(mPresenter: AJVehicleListPresenter) : BaseFragmentModel<AJVehicleListPresenter,AJVehicleListContrast.Model>(mPresenter) {
override fun getContract(): AJVehicleListContrast.Model {
return object : AJVehicleListContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/Chassis.kt
package com.org.huanjianmvp.Activity
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.org.huanjianmvp.Adapter.AJCheckAdapter
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.ChassisContrast
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.Presenter.ChassisPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.chassis.*
class Chassis : BaseActivity<ChassisPresenter , ChassisContrast.ViewAndPresenter>() {
var chassisAdapter: AJCheckAdapter? = null
override fun getContract(): ChassisContrast.ViewAndPresenter {
return object : ChassisContrast.ViewAndPresenter{
}
}
override fun createPresenter(): ChassisPresenter {
return ChassisPresenter()
}
override fun getViewID(): Int {
return R.layout.chassis
}
override fun initViewUI() {
chassisEnd.isEnabled = false //提交按钮不可点击
chassisRecycler.layoutManager = LinearLayoutManager(this@Chassis)
var dataList = ArrayList<inspectCheck>() //适配器
for (i in StaticValues.chassisDynamics.indices) {
var check = inspectCheck()
check.title = StaticValues.chassisDynamics[i]
check.result = "合格"
check.isCheck = true
dataList.add(check)
}
chassisAdapter = AJCheckAdapter(dataList)
chassisRecycler.adapter = chassisAdapter
}
override fun initListener() {
chassisBegin.setOnClickListener(this)
chassisEnd.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view?.id){
R.id.chassisBegin->{
chassisEnd.isEnabled = true //提交按钮可点击
}
R.id.chassisEnd->{
Log.e("map中数据总数","\t\t" + chassisAdapter?.spinnerMap!!.size.toString())
}
}
}
override fun destroy() {
}
override fun initDatas() {
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJBaseInfoModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.AJBaseInfoContrast
import com.org.huanjianmvp.Presenter.AJBaseInfoPresenter
/**
* Created by Administrator on 2020/9/4.
*/
class AJBaseInfoModel(mPresenter: AJBaseInfoPresenter?) : BaseFragmentModel<AJBaseInfoPresenter,AJBaseInfoContrast.Model>(mPresenter) {
override fun getContract(): AJBaseInfoContrast.Model {
return object : AJBaseInfoContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/InspectionFragmentModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.InspectionContrast
import com.org.huanjianmvp.Presenter.InspectionPresenter
/**
* Created by Administrator on 2020/8/24.
*/
class InspectionFragmentModel(mPresenter: InspectionPresenter?): BaseFragmentModel<InspectionPresenter, InspectionContrast.Model>(mPresenter) {
override fun getContract(): InspectionContrast.Model {
return object : InspectionContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJRecheckLoginPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJRecheckLogin
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.AJRecheckLoginContrast
import com.org.huanjianmvp.Model.AJRecheckLoginModel
/**
* Created by Administrator on 2020/9/17.
*/
class AJRecheckLoginPresenter: BaseFragmentPresenter<AJRecheckLogin,AJRecheckLoginModel,AJRecheckLoginContrast.ViewAndPresenter>() {
override fun getContract(): AJRecheckLoginContrast.ViewAndPresenter {
return object : AJRecheckLoginContrast.ViewAndPresenter{
}
}
override fun createModel(): AJRecheckLoginModel {
return AJRecheckLoginModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJRecheckLogin.kt
package com.org.huanjianmvp.Activity
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.org.huanjianmvp.Adapter.AJBaseInfoAdapter
import com.org.huanjianmvp.Adapter.AJRecheckLoginAdapter
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.AJRecheckLoginContrast
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.Presenter.AJRecheckLoginPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import com.org.huanjianmvp.Utils.StringUtils
import kotlinx.android.synthetic.main.aj_recheck_login.*
/**
* 安检的【复检登录】页
* **/
class AJRecheckLogin : BaseFragment<AJRecheckLoginPresenter,AJRecheckLoginContrast.ViewAndPresenter>() {
var carProvince: String? = null
var selectType: String? = null
var isForceCheck: String? = null
var pdaAdapter: AJRecheckLoginAdapter? = null //PDA检测适配器
var instrumentAdapter: AJRecheckLoginAdapter? = null //仪器检测适配器
override fun getContract(): AJRecheckLoginContrast.ViewAndPresenter {
return object : AJRecheckLoginContrast.ViewAndPresenter{
}
}
override fun createPresenter(): AJRecheckLoginPresenter {
return AJRecheckLoginPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_recheck_login
}
override fun initViewUI() {
var carProvince = ArrayAdapter<String>(this.context,R.layout.spinner_textview, StringUtils.strToArrayList(StaticValues.provinceName))
recheckLoginCarProvince.adapter = carProvince
var carTypeAdapter = ArrayAdapter<String>(this.context,R.layout.spinner_textview, StringUtils.strToArrayList(StaticValues.carType))
recheckLoginCarType.adapter = carTypeAdapter
forceCheckN.isChecked = true //单选默认 否
recheckPDAContent.layoutManager = LinearLayoutManager(this.context)
recheckPDAContent.adapter = pdaAdapter
recheckInstrument.layoutManager = LinearLayoutManager(this.context)
recheckInstrument.adapter = instrumentAdapter
}
override fun initListener() {
recheckLoginFind.setOnClickListener(this)
recheckLoginBtn.setOnClickListener(this)
/**【绑定spinner选择事件】**/
recheckLoginCarProvince.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
carProvince = StaticValues.provinceName[i]
Log.e("省份缩写",carProvince + "\t\t选择的position:\t\t" + i)
}
override fun onNothingSelected(adapterView: AdapterView<*>) {}
}
/**【绑定spinner选择事件】**/
recheckLoginCarType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
selectType = StaticValues.carType[i]
Log.e("车辆类型",selectType + "\t\t选择的position:\t\t" + i)
}
override fun onNothingSelected(adapterView: AdapterView<*>) {}
}
/**【单选事件】**/
forceCheck.setOnCheckedChangeListener { radioGroup, position ->
when(position){
forceCheckN.id ->{
isForceCheck = "NO"
}
forceCheckY.id->{
isForceCheck = "YES"
}
}
}
}
override fun onClick(view: View?) {
when(view?.id){
R.id.recheckLoginFind->{
Log.e("是否强制路试",isForceCheck + "..")
}
R.id.recheckLoginBtn->{
var pdaArray = pdaAdapter!!.listRecheck //PDA检测内容
var instrumentArray = instrumentAdapter!!.listRecheck //仪器检测内容
var finalArray = ArrayList<String>() //最终提交的内容
/**【合并二者的内容】**/
for (i in pdaArray.indices){
if (!finalArray.contains(pdaArray[i])){ //如果 finalArray 中不包含 pdaArray[i]
finalArray.add(pdaArray[i])
}
}
for (i in instrumentArray.indices){
if (!finalArray.contains(instrumentArray[i])){ //如果 finalArray 中不包含 pdaArray[i]
finalArray.add(instrumentArray[i])
}
}
pdaAdapter!!.listArrayListContent(finalArray)
Log.e("总共有数据" , finalArray.size.toString() + "条")
}
}
}
override fun destroy() {
}
override fun initDatas() {
/**【单选默认值】**/
if (forceCheckN.isChecked){
isForceCheck = "NO"
}else{
isForceCheck = "YES"
}
/**【适配器初始化】**/
var listPDA = ArrayList<inspectCheck>()
for (i in StaticValues.PADCheck.indices){
var inspectPDA = inspectCheck()
inspectPDA.title = StaticValues.PADCheck[i]
inspectPDA.isCheck = true
listPDA.add(inspectPDA)
}
pdaAdapter = AJRecheckLoginAdapter(listPDA ,activity)
var listInstrument = ArrayList<inspectCheck>()
for (i in StaticValues.instrumentCheck.indices){
var inspectInstrument = inspectCheck()
inspectInstrument.title = StaticValues.instrumentCheck[i]
inspectInstrument.isCheck = true
listInstrument.add(inspectInstrument)
}
instrumentAdapter = AJRecheckLoginAdapter(listInstrument , activity)
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJCheckModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.AJCheckContrast
import com.org.huanjianmvp.Presenter.AJCheckPresenter
/**
*
* Created by Administrator on 2020/9/4.
*/
class AJCheckModel(mPresenter: AJCheckPresenter) : BaseFragmentModel<AJCheckPresenter,AJCheckContrast.Model>(mPresenter) {
override fun getContract(): AJCheckContrast.Model {
return object : AJCheckContrast.Model{
override fun actionData() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/InspectionPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.Inspection
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.InspectionContrast
import com.org.huanjianmvp.Model.InspectionFragmentModel
/**
* Created by Administrator on 2020/8/24.
*/
class InspectionPresenter : BaseFragmentPresenter<Inspection,InspectionFragmentModel,InspectionContrast.ViewAndPresenter>(){
override fun getContract(): InspectionContrast.ViewAndPresenter {
return object : InspectionContrast.ViewAndPresenter{
}
}
override fun createModel(): InspectionFragmentModel {
return InspectionFragmentModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/PhotographFragmentPresenter.kt
package com.org.huanjianmvp.Presenter
import android.content.Context
import android.content.Intent
import com.org.huanjianmvp.Activity.Photograph
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.PhotographContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Model.PhotographFragmentModel
/**
* Created by Administrator on 2020/8/24.
*/
class PhotographFragmentPresenter : BaseFragmentPresenter<Photograph,PhotographFragmentModel,PhotographContrast.ViewAndPresenter>(){
override fun getContract(): PhotographContrast.ViewAndPresenter {
return object : PhotographContrast.ViewAndPresenter{
override fun requestPhotoData(fileName : String , context: Context) {
mModel.contract.actionPhotoData(fileName , context)
}
override fun responseOnLongClick(intent: Intent) {
weakView.get()!!.contract.responseOnLongClick(intent)
}
override fun requestOnLongClick(context: Context, user: UserData) {
mModel.contract.actionOnLongClick(context,user)
}
override fun requestOnClick(context: Context, user: UserData) {
mModel.contract.actionOnClick(context,user)
}
override fun requestData(user : UserData) {
mModel.contract.actionGetData(user)
}
override fun responseData(arrayList: ArrayList<UserData> , arraySpinnerStr: ArrayList<String>) {
weakView.get()!!.contract.responseData(arrayList , arraySpinnerStr)
}
override fun requestAddImg(arrayList: ArrayList<UserData>, strSelect: String) {
mModel.contract.actionAddImage(arrayList,strSelect)
}
override fun responseAddImg(boolean: Boolean , arrayLists: ArrayList<UserData>) {
weakView.get()!!.contract.responseAddImg(boolean , arrayLists)
}
}
}
override fun createModel(): PhotographFragmentModel {
return PhotographFragmentModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/ListDatas.kt
package com.org.huanjianmvp.Activity
import `in`.srain.cube.views.ptr.PtrDefaultHandler
import `in`.srain.cube.views.ptr.PtrFrameLayout
import `in`.srain.cube.views.ptr.PtrHandler
import `in`.srain.cube.views.ptr.header.MaterialHeader
import `in`.srain.cube.views.ptr.util.PtrLocalDisplay
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.KeyEvent
import android.view.View
import cn.pedant.SweetAlert.SweetAlertDialog
import com.org.huanjianmvp.Adapter.ListDatasAdapter
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.ListDatasContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.ListDatasActivityPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.AlertDialogUtils
import kotlinx.android.synthetic.main.list_datas.*
/**
* 登录后数据展示页面
* **/
class ListDatas : BaseActivity<ListDatasActivityPresenter, ListDatasContrast.ViewAndPresenter>() {
var arrayList = arrayListOf<UserData>()
var dialogUtils = AlertDialogUtils(this)
/**【实现契约类中的接口】**/
override fun getContract(): ListDatasContrast.ViewAndPresenter {
return object : ListDatasContrast.ViewAndPresenter{
override fun requestExit(alert: SweetAlertDialog) {
mPresenter.contract.requestExit(alert)
}
override fun responseExit(isExit: Boolean?) {
if (isExit==true){
[email protected]()
}
}
/**【请求数据】**/
override fun requestData() {
mPresenter.contract.requestData()
}
/**【响应请求数据】**/
override fun responseData(list: List<UserData>) {
arrayList = list as ArrayList<UserData>
contract.requestRefresh(arrayList,recycler_View,this@ListDatas, Function::class.java)
}
/**【请求刷新数据】**/
override fun requestRefresh(list: List<UserData>, rv: RecyclerView, context: Context, clas: Class<*>) {
mPresenter.contract.requestRefresh(list,rv,context,clas)
}
/**【响应刷新、重载数据】**/
override fun responseRefresh(adapter: ListDatasAdapter) {
recycler_View.adapter = adapter
}
/**【查找请求】**/
override fun requestFind(string: String) {
mPresenter.contract.requestFind(string)
}
/**【响应查找结果】**/
override fun responseFind(list: List<UserData>) {
arrayList = list as ArrayList<UserData>
contract.requestRefresh(arrayList,recycler_View,this@ListDatas, Function::class.java)
}
}
}
/**【实例化P层】**/
override fun createPresenter(): ListDatasActivityPresenter {
return ListDatasActivityPresenter()
}
/**【加载布局文件】**/
override fun getViewID(): Int {
return R.layout.list_datas
}
/**【初始化UI组件】**/
override fun initViewUI() {
application.addActivity(this@ListDatas)
/**【下拉刷新】**/
val header = MaterialHeader(this)
header.setPadding(0, PtrLocalDisplay.dp2px(15f), 0, 0)
mPtrFrame.headerView = header
mPtrFrame.addPtrUIHandler(header)
/**【绑定下拉操作事务】**/
mPtrFrame.setPtrHandler(object : PtrHandler{
/**【加载数据时触发,可在这里做线程获取数据等操作】**/
override fun onRefreshBegin(frame: PtrFrameLayout?) {
editTextFind.text = null //刷新后输入框设为null
contract.requestData() //请求数据
mPtrFrame.refreshComplete() //刷新完成
}
/**【检查是否可以执行下来刷新,比如列表为空或者列表第一项在最上面时】**/
override fun checkCanDoRefresh(frame: PtrFrameLayout?, content: View?, header: View?): Boolean {
return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header)
}
})
/**【列出数据】**/
var layoutManager = LinearLayoutManager(this)
recycler_View.layoutManager = layoutManager
}
/**【点击监听】**/
override fun initListener() {
btnFind.setOnClickListener(this)
}
/**【Button点击实现事件】**/
override fun onClick(v: View?) {
when(v?.id){
R.id.btnFind ->{
var inputStr = editTextFind.text.toString().trim()
if (!inputStr.equals("")){
contract.requestFind(inputStr)
}else{
dialogUtils.AlertTitle("查找的内容不能为空!","warning")
}
}
}
}
/**【销毁时执行】**/
override fun destroy() {
if (dialogUtils!=null){
dialogUtils.dismissDialog()
}
this.finish()
}
/**【数据初始化】**/
override fun initDatas() {
contract.requestData()
}
/**【错误处理】**/
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
Log.e("eee","responseError")
}
/**【重写返回键】 */
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
contract.requestExit(dialogUtils.getAlertDialog("warning"))
return true
}
return super.onKeyDown(keyCode, event)
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Base/BaseFragment.java
package com.org.huanjianmvp.Base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* 继承自Fragment的基类
* Created by Administrator on 2020/8/24.
*/
public abstract class BaseFragment<P extends BaseFragmentPresenter , CONTRACT>
extends Fragment implements View.OnClickListener{
public P mPresenter;
public abstract CONTRACT getContract(); //方法接口,实现接口中的方法
public abstract P createPresenter(); //实例化P层
public abstract int getViewID(); //拿到布局视图
public abstract void initViewUI(); //初始化组件
public abstract void initListener(); //初始化监听
public abstract void destroy(); //销毁时执行方法
public abstract void initDatas(); //初始化数据
//处理相应错误信息
public abstract<ERROR extends Object> void responseError(ERROR error , Throwable throwable);
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
this.mPresenter = createPresenter(); //实例化P层
mPresenter.attach(this); //绑定
return inflater.inflate(getViewID(),null);
//return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initDatas(); //初始化数据
initViewUI(); //初始化UI组件
initListener(); //初始化监听
}
@Override
public void onDestroyView() {
destroy(); //销毁时触发
mPresenter.detach(); //解绑
super.onDestroyView();
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Utils/StringUtils.java
package com.org.huanjianmvp.Utils;
import java.util.ArrayList;
/**
* Created by Administrator on 2020/9/9.
*/
public class StringUtils {
/**【 返回【外检】中储存到 map 中的 key 的值 】**/
public static String inspectMapKey(String itemName){
String mapKey = null;
if (itemName.equals("车辆机械状况是否良好")){
mapKey = "jxzksflh";
return mapKey;
}else if (itemName.equals("排气污染控制装置是否齐全,正常")){
mapKey = "<KEY>";
return mapKey;
}else if (itemName.equals("车辆是否存在烧机油或者严重冒黑烟现象")){
mapKey = "sfmhy";
return mapKey;
}else if (itemName.equals("(汽油车)燃油蒸发控制系统是否正常")){
mapKey = "ryzfxt";
return mapKey;
}else if (itemName.equals("车上仪表工作是否正常")){
mapKey = "csybgz";
return mapKey;
}else if (itemName.equals("有无可能影响安全或引起测试偏差的机械故障")){
mapKey = "<KEY>";
return mapKey;
}else if (itemName.equals("车辆进、排气系统是否有任何泄露")){
mapKey = "<KEY>";
return mapKey;
}else if (itemName.equals("车辆的发动机、变速箱和冷却系统等有无明显的液体泄漏")){
mapKey = "<KEY>";
return mapKey;
}else if (itemName.equals("是否带OBD系统")){
mapKey = "sfyobd";
return mapKey;
}else if (itemName.equals("轮胎气压是否正常")){
mapKey = "ltqysfzc";
return mapKey;
}else if (itemName.equals("轮胎是否干燥、清洁")){
mapKey = "ltsfgzqj";
return mapKey;
}else if (itemName.equals("是否关闭车上空调、暖风等附属设备")){
mapKey = "<KEY>";
return mapKey;
}else if (itemName.equals("是否已经中断车辆上可能影响测试正常进行的功能,如ARS、ESP、EPC牵引力控制或自动制动系统等")){
mapKey = "<KEY>";
return mapKey;
}else if (itemName.equals("车辆油箱和油品是否异常")){
mapKey = "clyxhyp";
return mapKey;
}else if (itemName.equals("是否适合工况法检测")){
mapKey = "gkfjy";
return mapKey;
}else if (itemName.equals("(汽油车)曲轴箱通风系统是否正常")){
mapKey = "qzxtfxt";
return mapKey;
}else if (itemName.equals("(柴油车)发动机燃油系统是否采用电控泵")){
mapKey = "fdjryxt";
return mapKey;
}else if (itemName.equals("机动车环保信息随车清单是否一致")){
mapKey = "scqdsfyz";
return mapKey;
}
return mapKey;
}
/**【String[] 转 ArrayList<String>类型】**/
public static ArrayList<String> strToArrayList(String [] data){
ArrayList<String> list = null;
if (data != null){
list = new ArrayList<>();
for (int i = 0 ; i < data.length ; i ++){
list.add(data[i]);
}
}
return list;
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/InspectionContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/8/24.
*/
interface InspectionContrast {
interface Model
interface ViewAndPresenter
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/PhotoAdapter.kt
package com.org.huanjianmvp.Adapter
import android.content.Context
import android.graphics.BitmapFactory
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.FileUtils
import com.org.huanjianmvp.Utils.SQLiteFunction
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.take_photo_item.view.*
/**
* 外观拍照适配器、点击监听、长按监听
* Created by Administrator on 2020/8/24.
*/
class PhotoAdapter(list: List<UserData> , recyclerView: RecyclerView , context: Context) : RecyclerView.Adapter<PhotoAdapter.viewHolder>(),
View.OnClickListener,View.OnLongClickListener{
private var mContext : Context? = null
private var listData = ArrayList<UserData>() //对象数据
private var rv: RecyclerView? = null
private var photoClickListener: PhotoClickListener? = null //声明一下点击接口
private var photoLongClickListener: PhotoLongClickListener? = null //声明一下长按接口
/**【图片点击监听】**/
fun setOnPhotoClickListener(photoClickListener: PhotoClickListener) {
this.photoClickListener = photoClickListener
}
/**【图片长按监听】**/
fun setOnPhotoLongClickListener(photoLongClickListener: PhotoLongClickListener){
this.photoLongClickListener = photoLongClickListener
}
//初始化模块,与第一构造函数同时执行
init {
listData = list as ArrayList<UserData>
rv = recyclerView
mContext = context
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): viewHolder {
var view = LayoutInflater.from(parent?.context).inflate(R.layout.take_photo_item,parent,false)
view.setOnClickListener(this) //设置点击监听器
view.setOnLongClickListener(this) //设置长按监听器
var holder = viewHolder(view)
return holder
}
/**【子项总数量】**/
override fun getItemCount(): Int {
return listData.size
}
/**【子项赋值】**/
override fun onBindViewHolder(holder: viewHolder?, position: Int) {
var fileName = listData[position].age + "_" + listData[position].userName + ".jpg" //图片名字
var lite = SQLiteFunction(mContext,StaticValues.SQLiteName,null,StaticValues.SQLiteVersion)
/**【图片说明】**/
holder!!.textView.text = listData[position].userName
/**【图片展示】**/
if (FileUtils.fileIsExists(fileName)){ //判断文件是否存在、true:存在 false:不存在
var filePath = FileUtils.createFileFolder() + fileName //获取目录下的图片
var imgBitmap = BitmapFactory.decodeFile(filePath,null)
Log.e("展示图片来源","\t\t手机文件夹\t\t" + position.toString())
holder!!.imageView.setImageBitmap(imgBitmap)
}else{
var bitmap = lite.queryData(fileName)
Log.e("展示图片来源","\t\tSQLite数据库\t\t" + position.toString())
holder!!.imageView.setImageBitmap(bitmap)
}
/**【图片状态】**/
if(lite.queryUploadStatus(fileName) == "1"){
holder!!.uploadText.text = "已上传"
}else{
holder!!.uploadText.text = "未上传"
}
}
/**【定义一个内部类,展示的数据由内部类决定】 */
class viewHolder(view: View) : RecyclerView.ViewHolder(view) {
var imageView: ImageView = view.takePhotoImg //图片
var textView: TextView = view.takePhotoText //图片说明
var uploadText : TextView = view.uploadText //图片上传状态
}
/**【点击事件】**/
override fun onClick(view: View?) {
//根据RecyclerView获得当前View的位置
var position: Int= rv?.getChildAdapterPosition(view)!!
//程序执行到此,会去执行具体实现的onItemClick()方法
if (photoClickListener != null) {
photoClickListener?.onPhotoClick(rv,view,position,listData[position])
}
}
/**【长按事件】**/
override fun onLongClick(view: View?): Boolean {
//根据RecyclerView获得当前View的位置
var position: Int= rv?.getChildAdapterPosition(view)!!
//程序执行到此,会去执行具体实现的photoLongClickListener()方法
if (photoLongClickListener!=null){
photoLongClickListener?.onPhotoLongClick(rv,view,position,listData[position])
}
return false
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/MenuSettingModel.kt
package com.org.huanjianmvp.Model
import android.content.SharedPreferences
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.MenuSettingContrast
import com.org.huanjianmvp.Presenter.MenuSettingPresenter
/**
* Created by Administrator on 2020/8/31.
*/
class MenuSettingModel(mPresenter : MenuSettingPresenter?) : BaseActivityModel<MenuSettingPresenter,MenuSettingContrast.Model>(mPresenter) {
override fun getContract(): MenuSettingContrast.Model {
return object : MenuSettingContrast.Model{
override fun saveAction(map: Map<String, String>, preferences: SharedPreferences) {
var editor = preferences.edit()
editor.putString("radioWJ",map.get("radioWJ")) //外检通道号
editor.putString("radioDP",map.get("radioDP")) //底盘通道号
editor.putString("radioXHPZ",map.get("radioXHPZ")) //循环拍照
editor.putString("radioDTDP",map.get("radioDTDP")) //动态地盘
editor.putString("radioSCFS",map.get("radioSCFS")) //数据上传方式
editor.putString("radioSCMS",map.get("radioSCMS")) //照片上传模式
editor.putString("radioSJTK",map.get("radioSJTK")) //时间调控
editor.putString("radioZPZD",map.get("radioZPZD")) //驻坡制动
editor.commit()
}
override fun initDataAction(preferences: SharedPreferences) {
var map = HashMap<String,String>()
map.put("radioWJ",preferences.getString("radioWJ","0")) //外检通道号
map.put("radioDP",preferences.getString("radioDP","0")) //底盘通道号
map.put("radioXHPZ",preferences.getString("radioXHPZ","0")) //循环拍照
map.put("radioDTDP",preferences.getString("radioDTDP","0")) //动态地盘
map.put("radioSCFS",preferences.getString("radioSCFS","0")) //数据上传方式
map.put("radioSCMS",preferences.getString("radioSCMS","0")) //照片上传模式
map.put("radioSJTK",preferences.getString("radioSJTK","0")) //时间调控
map.put("radioZPZD",preferences.getString("radioZPZD","0")) //驻坡制动
presenter.contract.responseInitData(map)
}
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJCheckPhotoBaseModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.AJCheckPhotoBaseContrast
import com.org.huanjianmvp.Presenter.AJCheckPhotoBasePresenter
/**
* Created by Administrator on 2020/9/4.
*/
class AJCheckPhotoBaseModel(mPresenter: AJCheckPhotoBasePresenter?)
:BaseActivityModel<AJCheckPhotoBasePresenter,AJCheckPhotoBaseContrast.Model>(mPresenter) {
override fun getContract(): AJCheckPhotoBaseContrast.Model {
return object : AJCheckPhotoBaseContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/Inspection.kt
package com.org.huanjianmvp.Activity
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.org.huanjianmvp.Adapter.InspectAdapter
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.InspectionContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.Presenter.InspectionPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import com.org.huanjianmvp.Utils.StringUtils
import kotlinx.android.synthetic.main.inspection.*
/**
* 外检检验项页面处理
* **/
class Inspection : BaseFragment<InspectionPresenter,InspectionContrast.ViewAndPresenter>() {
var user : UserData? = null
var mapData = HashMap<String,String>()
override fun getContract(): InspectionContrast.ViewAndPresenter {
return object : InspectionContrast.ViewAndPresenter{
}
}
override fun createPresenter(): InspectionPresenter {
return InspectionPresenter()
}
override fun getViewID(): Int {
return R.layout.inspection
}
override fun initViewUI() {
var list = ArrayList<inspectCheck>()
for (i in StaticValues.InspectionValues.indices) {
var check = inspectCheck()
check.title = StaticValues.InspectionValues[i]
check.result = "是"
check.isCheck = true
list.add(check)
}
var adapter = InspectAdapter(list)
inspectRecycler.layoutManager = LinearLayoutManager(this.context)
inspectRecycler.adapter = adapter
mapData = adapter.spinnerMap //获取适配器InspectAdapter中的数据
}
override fun initListener() {
inspectCommit.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view?.id){
R.id.inspectCommit ->{
for (i in 0..(mapData.size - 1)){
Log.e("【提交结果数据】",mapData?.get(StringUtils.inspectMapKey(StaticValues.InspectionValues[i])) +"\t\t【i的值】\t\t"+ i.toString())
}
}
}
}
override fun destroy() {
activity.finish()
}
override fun initDatas() {
user = activity.intent.getSerializableExtra("data") as UserData
user?.ShowLog()
Log.e("外检检验项页面打印数据","【完毕】")
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJInitLoginPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJInitLogin
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.AJInitLoginContrast
import com.org.huanjianmvp.Model.AJInitLoginModel
/**
* Created by Administrator on 2020/9/17.
*/
class AJInitLoginPresenter : BaseFragmentPresenter<AJInitLogin , AJInitLoginModel , AJInitLoginContrast.ViewAndPresenter>() {
override fun getContract(): AJInitLoginContrast.ViewAndPresenter {
return object : AJInitLoginContrast.ViewAndPresenter{
}
}
override fun createModel(): AJInitLoginModel {
return AJInitLoginModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/ListDatasContrast.kt
package com.org.huanjianmvp.Contrast
import android.content.Context
import android.support.v7.widget.RecyclerView
import cn.pedant.SweetAlert.SweetAlertDialog
import com.org.huanjianmvp.Adapter.ListDatasAdapter
import com.org.huanjianmvp.Domain.UserData
/**
* Created by Administrator on 2020/8/19.
*/
interface ListDatasContrast {
interface Model{
//数据查找
fun dataFind(string: String)
//重新加载数据
fun refreshData(list: List<UserData> , rv: RecyclerView , context: Context , clas: Class<*>)
//获取数据源
fun dataSource()
//退出处理
fun exitAction(alert: SweetAlertDialog)
}
interface ViewAndPresenter{
/**【-----------View层的方法-----------】**/
//请求获取数据
fun requestData()
//请求查找数据
fun requestFind(string: String)
//请求刷新重载数据
fun requestRefresh(list: List<UserData> , rv: RecyclerView , context: Context , clas: Class<*>)
//请求退出
fun requestExit(alert: SweetAlertDialog)
/**【-----------Presenter层的方法-----------】**/
//响应请求数据
fun responseData(list: List<UserData>)
//响应查找数据
fun responseFind(list: List<UserData>)
//响应刷新重载数据
fun responseRefresh(adapter: ListDatasAdapter)
//响应请求退出
fun responseExit(isExit: Boolean?)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/InspectionAndPhotograph.kt
package com.org.huanjianmvp.Activity
import android.graphics.Color
import android.support.v4.app.Fragment
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.InspectAndPhotoContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.InspectAndPhotoPresenter
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.inspection_and_photograph.*
/**
* 【外检检验】 和 【外检拍照】 导航页
**/
class InspectionAndPhotograph : BaseActivity<InspectAndPhotoPresenter,InspectAndPhotoContrast.ViewAndModel>() {
var user : UserData? = null
private var tabText = arrayOf("外检检验", "外检拍照")
private var fragments = arrayListOf<Fragment>()
override fun getContract(): InspectAndPhotoContrast.ViewAndModel {
return object : InspectAndPhotoContrast.ViewAndModel{
}
}
override fun createPresenter(): InspectAndPhotoPresenter {
return InspectAndPhotoPresenter()
}
override fun getViewID(): Int {
return R.layout.inspection_and_photograph
}
override fun initViewUI() {
application.addActivity(this@InspectionAndPhotograph)
fragments.add(Inspection())
fragments.add(Photograph())
navigationBar.defaultSetting()
navigationBar.titleItems(tabText) //tab文字集合
navigationBar.fragmentList(fragments) //Fragment集合
navigationBar.tabTextSize(18) //tab文字大小
navigationBar.navigationHeight(40) //导航栏高度
navigationBar.normalTextColor(Color.parseColor("#ffffff")) //字体未选中的颜色
navigationBar.selectTextColor(Color.parseColor("#FF0000")) //字体选中的颜色
navigationBar.navigationBackground(Color.parseColor("#5bc0de")) //导航栏背景色
navigationBar.fragmentManager(supportFragmentManager)
navigationBar.build()
}
override fun initListener() {
}
override fun onClick(view: View?) {
}
override fun destroy() {
[email protected]()
}
override fun initDatas() {
user = intent.getSerializableExtra("data") as UserData
user?.ShowLog()
Log.e("外检检验拍照页面打印数据","【完毕】")
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
[email protected]()
return super.onKeyDown(keyCode, event)
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/ListDatasAdapter.java
package com.org.huanjianmvp.Adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import com.org.huanjianmvp.Domain.UserData;
import com.org.huanjianmvp.R;
import java.util.ArrayList;
import java.util.List;
/**
* 展示数据信息,登录进来后进行展示,数据展示页面适配器
* Created by Administrator on 2020/8/19.
*/
public class ListDatasAdapter extends RecyclerView.Adapter<ListDatasAdapter.viewHolder> implements View.OnClickListener{
private List<UserData> dataList = new ArrayList<>();
private RecyclerView rv;
private ItemClickListener onItemClickListener; //声明一下这个接口
//提供setter方法
public void setOnItemClickListener(ItemClickListener onItemClickListener){
this.onItemClickListener = onItemClickListener;
}
/**【定义一个内部类,展示的数据由内部类决定】**/
static class viewHolder extends RecyclerView.ViewHolder{
private TextView listSerialNumber , listCarNumber , listCarNumType ,listCarID;
public viewHolder(View view) {
super(view);
listSerialNumber = view.findViewById(R.id.listSerialNumber);
listCarNumber = view.findViewById(R.id.listCarNumber);
listCarNumType = view.findViewById(R.id.listCarNumType);
listCarID = view.findViewById(R.id.listCarID);
}
}
/**【构造函数初始化数据】**/
public ListDatasAdapter(List<UserData> list , RecyclerView recyclerView){
dataList = list;
rv = recyclerView;
}
/**【子项布局文件获取】**/
@Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_datas_item,parent,false);
view.setOnClickListener(this); //设置监听器
final viewHolder holder = new viewHolder(view);
return holder;
}
/**【给子项赋值】**/
@Override
public void onBindViewHolder(viewHolder holder, int position) {
UserData users = dataList.get(position);
holder.listSerialNumber.setText(users.getUserName());
holder.listCarNumber.setText(users.getAge());
holder.listCarNumType.setText(users.getSex());
holder.listCarID.setText(users.getUserName());
}
/**【返回子项总数量】**/
@Override
public int getItemCount() {
return dataList.size();
}
@Override
public void onClick(View view) {
//根据RecyclerView获得当前View的位置
int position = rv.getChildAdapterPosition(view);
//程序执行到此,会去执行具体实现的onItemClick()方法
if (onItemClickListener!=null){
onItemClickListener.onItemClick(rv,view,position,dataList.get(position));
}
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/AJInitLoginContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/9/17.
*/
interface AJInitLoginContrast {
interface Model{}
interface ViewAndPresenter{}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJInitLoginModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.AJInitLoginContrast
import com.org.huanjianmvp.Presenter.AJInitLoginPresenter
/**
* Created by Administrator on 2020/9/17.
*/
class AJInitLoginModel(mPresenter: AJInitLoginPresenter): BaseFragmentModel<AJInitLoginPresenter , AJInitLoginContrast.Model>(mPresenter) {
override fun getContract(): AJInitLoginContrast.Model {
return object : AJInitLoginContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/ImageShowModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.ImageShowContrast
import com.org.huanjianmvp.Presenter.ImageShowPresenter
/**
* Created by Administrator on 2020/9/11.
*/
class ImageShowModel(mPresenter: ImageShowPresenter?): BaseActivityModel<ImageShowPresenter,ImageShowContrast.Model>(mPresenter) {
override fun getContract(): ImageShowContrast.Model {
return object : ImageShowContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/InspectAndPhotoActivityModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.InspectAndPhotoContrast
import com.org.huanjianmvp.Presenter.InspectAndPhotoPresenter
/**
* Created by Administrator on 2020/8/24.
*/
class InspectAndPhotoActivityModel(mPresenter: InspectAndPhotoPresenter?): BaseActivityModel<InspectAndPhotoPresenter, InspectAndPhotoContrast.Model>(mPresenter){
override fun getContract(): InspectAndPhotoContrast.Model {
return object : InspectAndPhotoContrast.Model{
}
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/AJPhotoModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseFragmentModel
import com.org.huanjianmvp.Contrast.AJPhotoContrast
import com.org.huanjianmvp.Presenter.AJPhotoPresenter
/**
* Created by Administrator on 2020/9/4.
*/
class AJPhotoModel(mPresenter: AJPhotoPresenter): BaseFragmentModel<AJPhotoPresenter,AJPhotoContrast.Model>(mPresenter) {
override fun getContract(): AJPhotoContrast.Model {
return object : AJPhotoContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/InspectAndPhotoPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.InspectionAndPhotograph
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.InspectAndPhotoContrast
import com.org.huanjianmvp.Model.InspectAndPhotoActivityModel
/**
* Created by Administrator on 2020/8/24.
*/
class InspectAndPhotoPresenter: BaseActivityPresenter<InspectionAndPhotograph,InspectAndPhotoActivityModel,InspectAndPhotoContrast.ViewAndModel>(){
override fun getContract(): InspectAndPhotoContrast.ViewAndModel {
return object : InspectAndPhotoContrast.ViewAndModel{
}
}
override fun createModel(): InspectAndPhotoActivityModel {
return InspectAndPhotoActivityModel(this)
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/InspectAndPhotoContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/8/24.
*/
interface InspectAndPhotoContrast {
interface Model
interface ViewAndModel
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJPhotoPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJPhoto
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.AJCheckContrast
import com.org.huanjianmvp.Contrast.AJPhotoContrast
import com.org.huanjianmvp.Model.AJPhotoModel
/**
* Created by Administrator on 2020/9/4.
*/
class AJPhotoPresenter : BaseFragmentPresenter<AJPhoto,AJPhotoModel,AJPhotoContrast.ViewAndPresenter>() {
override fun getContract(): AJPhotoContrast.ViewAndPresenter {
return object : AJPhotoContrast.ViewAndPresenter {
}
}
override fun createModel(): AJPhotoModel {
return AJPhotoModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/AJCheckAdapter.kt
package com.org.huanjianmvp.Adapter
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.ajcheck_item.view.*
import java.util.HashMap
/**
* 安检外检检验项 适配器
* Created by Administrator on 2020/9/4.
*/
class AJCheckAdapter(listData: ArrayList<inspectCheck>) : RecyclerView.Adapter<AJCheckAdapter.myViewHolder>(){
var spinnerMap = HashMap<String , String>() //每个spinner默认选择数据、每次改变在监听中更新数据
var viewHolder: myViewHolder? = null //子项的布局
var list: ArrayList<inspectCheck>? = null
init {
this.list = listData
for (n in 0..(list!!.size -1)){
spinnerMap!!.put(n.toString(),"1")
Log.e("【初始中的值】",spinnerMap.get(n.toString())+"\t\t【初始的长度】\t\t"+spinnerMap.size.toString()+"\t\tn的值为:"+n)
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): myViewHolder {
var view : View = LayoutInflater.from(parent?.context).inflate(R.layout.ajcheck_item,parent,false)
viewHolder = myViewHolder(view)
return viewHolder as myViewHolder
}
override fun onBindViewHolder(holder: myViewHolder?, position: Int) {
if (list!![position].isCheck){
holder!!.textResult.text = "合格"
//holder!!.textResult.setTextColor(Color.GREEN)
}else{
holder!!.textResult.text = "不合格"
//holder!!.textResult.setTextColor(Color.RED)
}
holder!!.textTitle.text = list!![position].title
/**【设置监听】**/
holder!!.textResult.setOnClickListener {
if (list!![position].isCheck){
holder!!.textResult.text = "不合格"
//holder!!.textResult.setTextColor(Color.RED)
list!![position].isCheck = false
spinnerMap!!.put(position.toString(),"0")
}else{
holder!!.textResult.text = "合格"
//holder!!.textResult.setTextColor(Color.GREEN)
list!![position].isCheck = true
spinnerMap!!.put(position.toString(),"1")
}
}
}
/**【总数】**/
override fun getItemCount(): Int {
return this.list!!.size
}
/**【子项的视图】**/
class myViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var textTitle: TextView = view.check_items
var textResult: TextView = view.checkResult
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJCheckPhotoBasePresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJCheckAndPhotoAndBaseInfo
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.AJCheckPhotoBaseContrast
import com.org.huanjianmvp.Model.AJCheckPhotoBaseModel
/**
* Created by Administrator on 2020/9/4.
*/
class AJCheckPhotoBasePresenter : BaseActivityPresenter<AJCheckAndPhotoAndBaseInfo,AJCheckPhotoBaseModel,AJCheckPhotoBaseContrast.ViewAndPresenter>() {
override fun getContract(): AJCheckPhotoBaseContrast.ViewAndPresenter {
return object : AJCheckPhotoBaseContrast.ViewAndPresenter{
}
}
override fun createModel(): AJCheckPhotoBaseModel {
return AJCheckPhotoBaseModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJInitLogin.kt
package com.org.huanjianmvp.Activity
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.org.huanjianmvp.Adapter.AJBaseInfoAdapter
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.AJInitLoginContrast
import com.org.huanjianmvp.Presenter.AJInitLoginPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import com.org.huanjianmvp.Utils.StringUtils
import kotlinx.android.synthetic.main.aj_init_login.*
/**
* 安检的【初检登录】页
* **/
class AJInitLogin : BaseFragment<AJInitLoginPresenter , AJInitLoginContrast.ViewAndPresenter>() {
var adapter: AJBaseInfoAdapter? = null
var carProvince: String? = null
var carSeleType: String? = null
override fun getContract(): AJInitLoginContrast.ViewAndPresenter {
return object : AJInitLoginContrast.ViewAndPresenter{
}
}
override fun createPresenter(): AJInitLoginPresenter {
return AJInitLoginPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_init_login
}
override fun initViewUI() {
var carProvince = ArrayAdapter<String>(this.context,R.layout.spinner_textview,StringUtils.strToArrayList(StaticValues.provinceName))
carPosition.adapter = carProvince
var carTypeAdapter = ArrayAdapter<String>(this.context,R.layout.spinner_textview,StringUtils.strToArrayList(StaticValues.carType))
carType.adapter = carTypeAdapter
recyclerBaseInfo.layoutManager = LinearLayoutManager(this.context)
recyclerBaseInfo.adapter = adapter
recyclerCheckInfo.layoutManager = LinearLayoutManager(this.context)
recyclerCheckInfo.adapter = adapter
}
override fun initListener() {
carBtnFind.setOnClickListener(this)
initLoginBtn.setOnClickListener(this)
/**【绑定spinner选择事件】**/
carPosition.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
carProvince = StaticValues.provinceName[i]
Log.e("省份缩写",carProvince + "\t\t选择的position:\t\t" + i)
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
/**【绑定spinner选择事件】**/
carType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
carSeleType = StaticValues.carType[i]
Log.e("省份缩写",carProvince + "\t\t选择的position:\t\t" + i)
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
}
override fun onClick(view: View?) {
when(view?.id){
R.id.carBtnFind->{
Log.e("省份缩写",carProvince + "-----" + carSeleType)
}
R.id.initLoginBtn->{
}
}
}
override fun destroy() {
}
override fun initDatas() {
var list = ArrayList<String>()
for (i in StaticValues.AJBaseInfoText.indices){
list.add(StaticValues.AJBaseInfoText[i])
}
adapter = AJBaseInfoAdapter(list)
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/AJCheckPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.AJCheck
import com.org.huanjianmvp.Base.BaseFragmentPresenter
import com.org.huanjianmvp.Contrast.AJCheckContrast
import com.org.huanjianmvp.Model.AJCheckModel
/**
* Created by Administrator on 2020/9/4.
*/
class AJCheckPresenter : BaseFragmentPresenter<AJCheck,AJCheckModel,AJCheckContrast.ViewAndPresenter>() {
override fun getContract(): AJCheckContrast.ViewAndPresenter {
return object : AJCheckContrast.ViewAndPresenter{
override fun requestData() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun responseData(list: List<String>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
}
override fun createModel(): AJCheckModel {
return AJCheckModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/Setting.kt
package com.org.huanjianmvp.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.view.View
import android.widget.ArrayAdapter
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.SettingContrast
import com.org.huanjianmvp.Login
import com.org.huanjianmvp.Presenter.SettingPresenter
import com.org.huanjianmvp.R
import kotlinx.android.synthetic.main.setting.*
/**
* 程序设置参数页面
* **/
class Setting : BaseActivity<SettingPresenter,SettingContrast.ViewAndPresenter>() {
override fun getContract(): SettingContrast.ViewAndPresenter {
return object : SettingContrast.ViewAndPresenter{
override fun requestSave(map: Map<String, String> , preferences: SharedPreferences) {
mPresenter.contract.requestSave(map,preferences)
}
override fun requestInitData(preferences: SharedPreferences) {
mPresenter.contract.requestInitData(preferences)
}
override fun responseInitData(map: Map<String, String>) {
editTextIP.setText(map.get("strIP"))
editTextFTP.setText(map.get("strFTP"))
editTextNumber.setText(map.get("Number"))
editTextDispatch.setText(map.get("Dispatch"))
editTextCheckNum.setText(map.get("CheckNum"))
if (map.get("upType") == "0"){
uploadType.setSelection(0)
}else{
uploadType.setSelection(1)
}
}
}
}
override fun createPresenter(): SettingPresenter {
return SettingPresenter()
}
override fun getViewID(): Int {
return R.layout.setting
}
override fun initViewUI() {
application.addActivity(this@Setting)
var zpscfsdatas = arrayOf("存本地", "实时传")
var adapterthree = ArrayAdapter<String>(this, R.layout.spinner_textview, zpscfsdatas)
adapterthree.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
uploadType.adapter = adapterthree
}
override fun initListener() {
settingSave.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view?.id){
R.id.settingSave ->{
var map = HashMap<String , String>()
var preferences = getSharedPreferences("AppSettings", 0)
map.put("strIP",editTextIP.text.toString())
map.put("strFTP",editTextFTP.text.toString())
map.put("Number",editTextNumber.text.toString())
map.put("Dispatch",editTextDispatch.text.toString())
map.put("CheckNum",editTextCheckNum.text.toString())
map.put("upType",uploadType.selectedItem.toString())
contract.requestSave(map ,preferences)
var intent = Intent(this@Setting, Login::class.java)
startActivity(intent)
this.finish()
}
}
}
override fun destroy() {
[email protected]()
}
override fun initDatas() {
var preferences = getSharedPreferences("AppSettings", 0)
contract.requestInitData(preferences)
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/MenuSettingContrast.kt
package com.org.huanjianmvp.Contrast
import android.content.SharedPreferences
/**
* Created by Administrator on 2020/8/31.
*/
interface MenuSettingContrast {
interface Model{
/**【保存数据】**/
fun saveAction(map : Map<String,String> , preferences: SharedPreferences)
/**【获取初始化数据】**/
fun initDataAction(preferences: SharedPreferences)
}
interface ViewAndPresenter{
/**【请求保存数据】**/
fun requestSave(map : Map<String,String> , preferences: SharedPreferences)
/**【请求初始数据】**/
fun requestInitData(preferences: SharedPreferences)
/**【响应初始数据】**/
fun responseInitData(map : Map<String,String>)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/ChassisModel.kt
package com.org.huanjianmvp.Model
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.ChassisContrast
import com.org.huanjianmvp.Presenter.ChassisPresenter
/**
* Created by Administrator on 2020/9/22.
*/
class ChassisModel(mPresenter: ChassisPresenter): BaseActivityModel<ChassisPresenter , ChassisContrast.Model>(mPresenter) {
override fun getContract(): ChassisContrast.Model {
return object : ChassisContrast.Model{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/AJCheckPhotoBaseContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/9/4.
*/
interface AJCheckPhotoBaseContrast {
interface Model{}
interface ViewAndPresenter{}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Adapter/AJBaseInfoAdapter.kt
package com.org.huanjianmvp.Adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.aj_baseinfo_item.view.*
/**
* 安检基本信息适配器
* Created by Administrator on 2020/9/11.
*/
class AJBaseInfoAdapter(listData: ArrayList<String>) : RecyclerView.Adapter<AJBaseInfoAdapter.viewHolder>(){
var list = ArrayList<String>()
var holder: viewHolder? = null
init {
this.list = listData
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): viewHolder {
var view : View = LayoutInflater.from(parent!!.context).inflate(R.layout.aj_baseinfo_item,parent,false)
holder = viewHolder(view)
return holder as viewHolder
}
override fun onBindViewHolder(holder: viewHolder?, position: Int) {
holder!!.textTitle.text = StaticValues.AJBaseInfoTitle[position]
holder!!.textText.text = list[position]
}
override fun getItemCount(): Int {
return list.size
}
/**【内部类,展示的内容】**/
class viewHolder(view : View): RecyclerView.ViewHolder(view){
var textTitle : TextView = view.baseTitle
var textText : TextView = view.baseText
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Utils/SQLiteFunction.java
package com.org.huanjianmvp.Utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.util.Log;
/**
* 创建SQLite数据库储存图片
* Created by Administrator on 2020/9/3.
*/
public class SQLiteFunction extends SQLiteOpenHelper{
private static final String TABLE_NAME = "TabPhoto"; //表格名称
private static final String TABLE_CREATE = "create table if not exists TabPhoto(" //表格创建语句
+"[id] INTEGER PRIMARY KEY AUTOINCREMENT," //主键自增
+"[name] TEXT," //名字
+"[time] TEXT," //录入时间
+"[photo] BINARY," //照片保存为binary格式
+"[status] TEXT)"; //照片上传状态
public SQLiteFunction(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE); //创建表格
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
//sqLiteDatabase.execSQL("drop table if exists ImageTab");
}
//调用onCreate创建表格
public void create(){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
onCreate(sqLiteDatabase);
}
//插入数据
public void insertData(String name , String status , Bitmap bitmap){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name",name);
values.put("status",status);
values.put("time",TimeUtils.getNowDay());
values.put("photo",FileUtils.bitmapToByte(bitmap)); //将字节数组保存到数据库中
//查找数据库中是否存在字段 [ name = name ] 的数据
Cursor cursor = database.query(TABLE_NAME,null,"name=?",new String[]{ name },null,null,null);
if (cursor.getCount() != 0){
//存在则更新数据
database.update(TABLE_NAME,values,"name=?",new String[]{ name } );
}else{
//不存在则新增数据
database.insert(TABLE_NAME,null,values);
}
}
//查找返回bitmap
public Bitmap queryData(String queryName){
Bitmap bitmap = null;
if (queryName!=null){
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.query(TABLE_NAME,null,"name=?",new String[]{ queryName },null,null,null);
if (cursor.getCount() != 0){
cursor.moveToFirst();
byte[] photo = cursor.getBlob(cursor.getColumnIndex("photo"));
Log.e("SQLite查找bitmap的byte长度","\t\t" + photo.length);
bitmap = FileUtils.byteToBitmap(photo);
}
}
return bitmap;
}
//查找返回照片上传状态 status
public String queryUploadStatus(String queryName){
String uploadStatus = "";
if (queryName!=null){
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.query(TABLE_NAME,null,"name=?",new String[]{ queryName },null,null,null);
if (cursor.getCount() != 0){
cursor.moveToFirst();
uploadStatus = cursor.getString(cursor.getColumnIndex("status"));
Log.e("查找数据库上传状态","\t\t" + uploadStatus);
}
}
return uploadStatus;
}
//通过字段:name 更新字段:time 、 bitmap
public void updateData(String name , Bitmap bitmap){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("time",TimeUtils.getNowDay());
values.put("photo",FileUtils.bitmapToByte(bitmap));
int result = database.update(TABLE_NAME,values,"name=?",new String[]{ name } );
Log.e("Bitmap数据更新结果","\t\t" + result);
}
//通过字段:name 更新字段:time 、 status
public void updateStatus(String name ,String status){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("status",status);
values.put("time",TimeUtils.getNowDay());
int result = database.update(TABLE_NAME,values,"name=?",new String[]{ name } );
Log.e("Status数据更新结果","\t\t" + result);
}
//遍历所有数据、删除3天前的数据
public void delDataForThreeDay() throws Exception {
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.query(TABLE_NAME,new String[]{"name","time"},null,null,null,null,null);
if (cursor.moveToFirst()){
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
String time = cursor.getString(cursor.getColumnIndex("time"));
if (TimeUtils.dayDiff(time) >= 3){ //当前时间和录入时间作比较
int result = database.delete(TABLE_NAME,"name=?",new String[]{ name }); //删除数据
Log.e("数据删除结果\t",result + "...");
}
}while (cursor.moveToNext());
}
}
//后台打印全部数据
public void LogData(){
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.query(TABLE_NAME,null,null,null,null,null,null);
if (cursor.moveToFirst()){
do {
String name = "\t\t数据库中name:\t" + cursor.getString(cursor.getColumnIndex("name"));
String status = "\t\t数据库中status:\t" + cursor.getString(cursor.getColumnIndex("status"));
String time = "\t\t数据库中time:\t" + cursor.getString(cursor.getColumnIndex("time"));
Log.e("数据库中ID",cursor.getInt(0) + "\t" + name + status + time);
//Log.e("数据库中name",cursor.getString(cursor.getColumnIndex("name")));
//Log.e("数据库中status",cursor.getString(cursor.getColumnIndex("status")));
//Log.e("数据库中time",cursor.getString(cursor.getColumnIndex("time")));
}while (cursor.moveToNext());
}
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Base/SuperBase.java
package com.org.huanjianmvp.Base;
/**
* 整个架构的父类、超级父类
* 泛型 CONTRACT 面向的是接口类
* 子类必须实现方法接口getContract(),具体实现哪些看传过来的方法接口中有哪些方法
* Created by Administrator on 2020/8/19.
*/
public abstract class SuperBase<CONTRACT> {
/*【子类要实现的方法,具体实现由传过来的接口中的方法决定】*/
public abstract CONTRACT getContract();
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/MenuSettingPresenter.kt
package com.org.huanjianmvp.Presenter
import android.content.SharedPreferences
import com.org.huanjianmvp.Activity.MenuSetting
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.MenuSettingContrast
import com.org.huanjianmvp.Model.MenuSettingModel
/**
* Created by Administrator on 2020/8/31.
*/
class MenuSettingPresenter : BaseActivityPresenter<MenuSetting,MenuSettingModel,MenuSettingContrast.ViewAndPresenter>(){
override fun createModel(): MenuSettingModel {
return MenuSettingModel(this)
}
override fun getContract(): MenuSettingContrast.ViewAndPresenter {
return object : MenuSettingContrast.ViewAndPresenter{
override fun requestSave(map: Map<String, String>, preferences: SharedPreferences) {
mModel.contract.saveAction(map,preferences)
}
override fun requestInitData(preferences: SharedPreferences) {
mModel.contract.initDataAction(preferences)
}
override fun responseInitData(map: Map<String, String>) {
weakView.get()?.contract?.responseInitData(map)
}
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Model/ListDatasActivityModel.kt
package com.org.huanjianmvp.Model
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.util.Log
import cn.pedant.SweetAlert.SweetAlertDialog
import com.org.huanjianmvp.Adapter.ListDatasAdapter
import com.org.huanjianmvp.Base.BaseActivityModel
import com.org.huanjianmvp.Contrast.ListDatasContrast
import com.org.huanjianmvp.Domain.UserData
import com.org.huanjianmvp.Presenter.ListDatasActivityPresenter
/**
* Created by Administrator on 2020/8/19.
*/
class ListDatasActivityModel(mPresenter: ListDatasActivityPresenter?) : BaseActivityModel<ListDatasActivityPresenter, ListDatasContrast.Model>(mPresenter) {
override fun getContract(): ListDatasContrast.Model {
return object : ListDatasContrast.Model{
/**【请求退出处理】**/
override fun exitAction(alert: SweetAlertDialog) {
alert.setTitle("是否退出当前软件?")
alert.confirmText = "确定"
alert.cancelText = "取消"
alert.setConfirmClickListener {
presenter.contract.responseExit(true)
}
alert.setCancelClickListener {
presenter.contract.responseExit(false)
alert.dismiss()
}
alert.show()
}
/**【数据源、初始数据】**/
override fun dataSource(){
try {
}catch (exception:Exception){
}
var arrayList = arrayListOf<UserData>() //创建一个空数组
//模拟数据
var user1 = UserData()
user1.age = "23"
user1.sex = "男"
user1.userName = "张三"
var user2 = UserData()
user2.age = "30"
user2.sex = "女"
user2.userName = "李四"
var user3 = UserData()
user3.age = "25"
user3.sex = "保密"
user3.userName = "刘柳"
arrayList.add(user1)
arrayList.add(user2)
arrayList.add(user3)
presenter.contract.responseData(arrayList) //响应请求数据
}
/**【下拉刷新数据处理、并绑定每一项的点击事件】**/
override fun refreshData(list: List<UserData>, rv: RecyclerView, context: Context, clas: Class<*>){
var adapter = ListDatasAdapter(list,rv)
adapter.setOnItemClickListener{parent, view, position, data ->
var intent = Intent(context,clas)
var bundle = Bundle()
bundle.putSerializable("data",data)
intent.putExtras(bundle)
context.startActivity(intent)
}
presenter.contract.responseRefresh(adapter) //响应刷新重载数据
}
/**【关键字查找数据】**/
override fun dataFind(string: String) {
Log.e("拿到的查找数据",string)
var returnList = arrayListOf<UserData>() //模仿返回数据
if (string.equals("admin")){
var user1 = UserData()
user1.age = "保"
user1.sex = "保密"
user1.userName = "保密吧"
returnList.add(user1)
}
presenter.contract.responseFind(returnList) //响应查找数据
}
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/ChassisPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.Chassis
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.ChassisContrast
import com.org.huanjianmvp.Model.ChassisModel
/**
* Created by Administrator on 2020/9/22.
*/
class ChassisPresenter : BaseActivityPresenter<Chassis , ChassisModel , ChassisContrast.ViewAndPresenter>() {
override fun getContract(): ChassisContrast.ViewAndPresenter {
return object : ChassisContrast.ViewAndPresenter{
}
}
override fun createModel(): ChassisModel {
return ChassisModel(this)
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/AJCheck.kt
package com.org.huanjianmvp.Activity
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.org.huanjianmvp.Adapter.AJCheckAdapter
import com.org.huanjianmvp.Base.BaseFragment
import com.org.huanjianmvp.Contrast.AJCheckContrast
import com.org.huanjianmvp.Domain.inspectCheck
import com.org.huanjianmvp.Presenter.AJCheckPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.aj_check.*
import android.support.v7.widget.DividerItemDecoration
import com.gavin.com.library.StickyDecoration
import com.gavin.com.library.listener.GroupListener
/**
* 安检外检 页面
* */
class AJCheck : BaseFragment<AJCheckPresenter,AJCheckContrast.ViewAndPresenter>() {
var adapter: AJCheckAdapter? = null
var list : ArrayList<inspectCheck>? = null
override fun getContract(): AJCheckContrast.ViewAndPresenter {
return object : AJCheckContrast.ViewAndPresenter{
override fun requestData() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun responseData(list: List<String>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
}
override fun createPresenter(): AJCheckPresenter {
return AJCheckPresenter()
}
override fun getViewID(): Int {
return R.layout.aj_check
}
override fun initViewUI() {
list = ArrayList()
for (i in StaticValues.AJCheckContens.indices){
var check = inspectCheck()
check.title = StaticValues.AJCheckContens[i]
check.result = "合格"
check.isCheck = true
list!!.add(check)
}
adapter = AJCheckAdapter(list!!)
var groupListener = GroupListener { position ->
gounpName(position)
}
var decoration = StickyDecoration.Builder.init(groupListener)
.setGroupHeight(20).setGroupTextSize(15).setGroupTextColor(Color.parseColor("#373a3c")).build()
/*.setGroupBackground(Color.parseColor("#0275d8"))*///设置背景色
AJCheckItem.layoutManager = LinearLayoutManager(this.context)
AJCheckItem.addItemDecoration(decoration)
AJCheckItem.addItemDecoration(DividerItemDecoration(this.context, DividerItemDecoration.VERTICAL)) //添加Android自带的分割线
AJCheckItem.adapter = adapter
}
fun gounpName(position: Int): String? {
if (position == 0 ){
return "车辆唯一性检查"
}else if (position == 5){
return "车辆特征参数检查"
}else if (position == 7){
return "车辆外观检查"
}else if (position == 13){
return "安全装置检查"
}
return null
}
override fun initListener() {
AJCheckStart.setOnClickListener(this)
AJCheckCommit.setOnClickListener(this)
}
override fun onClick(view: View?) {
when(view!!.id){
/**【检验开始】**/
R.id.AJCheckStart->{
}
/**【提交数据】**/
R.id.AJCheckCommit->{
var map = adapter!!.spinnerMap
for (i in 0..(map.size-1)){
Log.e("提交的结果",map.get(i.toString()))
}
}
}
}
override fun destroy() {
}
override fun initDatas() {
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Presenter/FunctionActivityPresenter.kt
package com.org.huanjianmvp.Presenter
import com.org.huanjianmvp.Activity.Function
import com.org.huanjianmvp.Base.BaseActivityPresenter
import com.org.huanjianmvp.Contrast.FunctionContrast
import com.org.huanjianmvp.Model.FunctionActivityModel
/**
* Created by Administrator on 2020/8/21.
*/
class FunctionActivityPresenter: BaseActivityPresenter<Function, FunctionActivityModel, FunctionContrast.ViewAndPresenter>(){
override fun createModel(): FunctionActivityModel {
return FunctionActivityModel(this)
}
override fun getContract(): FunctionContrast.ViewAndPresenter {
return object : FunctionContrast.ViewAndPresenter{
}
}
}<file_sep>/app/src/main/java/com/org/huanjianmvp/Activity/ImageShow.kt
package com.org.huanjianmvp.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import android.view.View
import com.org.huanjianmvp.Base.BaseActivity
import com.org.huanjianmvp.Contrast.ImageShowContrast
import com.org.huanjianmvp.Presenter.ImageShowPresenter
import com.org.huanjianmvp.R
import com.org.huanjianmvp.Utils.FileUtils
import com.org.huanjianmvp.Utils.SQLiteFunction
import com.org.huanjianmvp.Utils.StaticValues
import kotlinx.android.synthetic.main.image_show.*
/**
* 图片展示页面
* **/
class ImageShow : BaseActivity<ImageShowPresenter,ImageShowContrast.ViewAndPresenter>() {
private var bitmap: Bitmap? = null //原图
private var finalBitmap : Bitmap? = null //最终效果图
private var sqlBitmap : Bitmap? = null //数据库位图更新
private var rotateCount = 1 //位图旋转次数
private var fileName : String? = null //图片名字
override fun getContract(): ImageShowContrast.ViewAndPresenter {
return object : ImageShowContrast.ViewAndPresenter{
}
}
override fun createPresenter(): ImageShowPresenter {
return ImageShowPresenter()
}
override fun getViewID(): Int {
return R.layout.image_show
}
override fun initViewUI() {
application.addActivity(this@ImageShow) //将本页面添加到页面统一管理中
fileName = intent.getStringExtra("fileName") //拿到图片名字
var lite = SQLiteFunction(this@ImageShow,StaticValues.SQLiteName,null,StaticValues.SQLiteVersion)
bitmap = lite.queryData(fileName) //通过文件名字查找数据库中的bitmap
sqlBitmap = bitmap //初始默认数据库bitmap
//bitmap = BitmapFactory.decodeFile(fileName,null) //通过路径获取位图
photoView.enable() //启用图片缩放
photoView.maxScale = 3.0f //图片最大缩放倍数
photoView.setImageBitmap(FileUtils.bitmapWaterMark(bitmap)) //位图展示
//var photoStr = FileUtils.getPhotoData(FileUtils.createFileFolder()+fileName) //图片压缩转成String
//Log.e("图片信息","\t\t" + photoStr)
}
override fun initListener() {
btnDelete.setOnClickListener(this@ImageShow)
btnRotate.setOnClickListener(this@ImageShow)
btnSave.setOnClickListener(this@ImageShow)
}
override fun onClick(view: View?) {
when(view!!.id){
R.id.btnRotate->{
var bitmapRotate = FileUtils.bitmapRotate(bitmap , rotateCount) //位图旋转
sqlBitmap = bitmapRotate //旋转过后的数据库位图
rotateCount ++ //旋转次数,每点击一次:顺时针旋转 90°* 次数
finalBitmap = FileUtils.bitmapWaterMark(bitmapRotate) //给位图添加水印
photoView.setImageBitmap(finalBitmap) //更新展示位图
}
R.id.btnDelete->{
Log.e("删除按钮","删除图片")
[email protected]()
}
R.id.btnSave->{
var lite = SQLiteFunction(this@ImageShow,StaticValues.SQLiteName,null,StaticValues.SQLiteVersion)
lite.updateData(fileName,sqlBitmap) //更新数据库中保存的bitmap
var filePath = FileUtils.createFileFolder() + fileName //文件保存路径及名字
var isSuccess = FileUtils.overWriteFile(finalBitmap , filePath)//要保存的位图:finalBitmap(数据库也要更新)
if (isSuccess){
Log.e("保存按钮","图片覆盖成功!")
}else{
Log.e("保存按钮","图片覆盖失败!")
}
[email protected]()
}
}
}
override fun destroy() {
}
override fun initDatas() {
}
override fun <ERROR : Any?> responseError(error: ERROR, throwable: Throwable?) {
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Base/BaseActivity.java
package com.org.huanjianmvp.Base;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.org.huanjianmvp.BootApplication;
import com.org.huanjianmvp.Login;
import cn.pedant.SweetAlert.SweetAlertDialog;
/**
* 只关注P层,不与V层进行交互
* 继承自AppCompatActivity的基类
* Created by Administrator on 2020/8/19.
*/
public abstract class BaseActivity<P extends BaseActivityPresenter, CONTRACT>
extends AppCompatActivity implements View.OnClickListener{
public P mPresenter;
private Long startTime = System.currentTimeMillis(); //第一次点击时间
private Long clickTime = System.currentTimeMillis(); //每一次点击都重置该时间,判断两次时间间隔
private Intent intent ; //超时跳转页面
private SweetAlertDialog alertDialog; //超时提示框
public BootApplication application; //程序页面管理
public abstract CONTRACT getContract(); //方法接口,实现接口中的方法
public abstract P createPresenter(); //实例化P层
public abstract int getViewID(); //拿到布局视图
public abstract void initViewUI(); //初始化组件
public abstract void initListener(); //初始化监听
public abstract void destroy(); //销毁时执行方法
public abstract void initDatas(); //初始化数据
//处理相应错误信息
public abstract<ERROR extends Object> void responseError(ERROR error , Throwable throwable);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(getViewID()); //引入布局文件
this.mPresenter = createPresenter(); //实例化P层
application = (BootApplication)getApplication();
mPresenter.attach(this); //绑定
initViewUI(); //初始化UI组件
initListener(); //初始化监听
initDatas(); //初始化数据
}
/**
* 【登录长时间无操作】
* 【每点击屏幕就触发该事件】**/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN : //屏幕按下
clickTime = System.currentTimeMillis();
if (clickTime - startTime > 1000 * 60 * 10){ //屏幕十分钟无操作
intent = new Intent(this, Login.class);
if (alertDialog == null){
alertDialog = new SweetAlertDialog(this,SweetAlertDialog.WARNING_TYPE);
}
//Log.e("点击时间",clickTime + "\t\t开始时间\t\t" + startTime + "\t\t相差时间\t\t" + (clickTime - startTime));
alertDialog.setCancelable(false);
alertDialog.setTitleText("登录超时!");
alertDialog.setContentText("程序十分钟无操作,返回重新登录!");
alertDialog.setConfirmText("确定");
alertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
clickTime = System.currentTimeMillis();
startTime = clickTime;
startActivity(intent);
application.destroyActivity();
}
});
alertDialog.show();
return true; //返回值为True事件会传递到自己的onTouchEvent() 返回值为False传递到下一个view的dispatchTouchEvent()
}else {
startTime = clickTime;
//Log.e("时间clickTime",clickTime + "\t\t时间startTime\t\t" + startTime + "\t\t相差时间\t\t" + (clickTime - startTime));
}
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
protected void onDestroy() {
destroy(); //销毁时触发
mPresenter.detach(); //解绑
if (alertDialog!=null){
alertDialog.dismiss();
}
super.onDestroy();
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Domain/validateCode.java
package com.org.huanjianmvp.Domain;
import android.util.Log;
/**
* Created by Administrator on 2020/9/28.
*/
public class validateCode {
private int code;
private String msg;
private int count;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
class data{
public String imageKey;
private String imageCode;
public String getImageKey() {
return imageKey;
}
public void setImageKey(String imageKey) {
this.imageKey = imageKey;
}
public String getImageCode() {
return imageCode;
}
public void setImageCode(String imageCode) {
this.imageCode = imageCode;
}
}
public void dataLog(){
Log.e("code",code + "\t\tmsg:" + msg + "\t\tcount:" + count );
}
}
<file_sep>/app/src/main/java/com/org/huanjianmvp/Contrast/AJCheckContrast.kt
package com.org.huanjianmvp.Contrast
/**
* Created by Administrator on 2020/9/4.
*/
interface AJCheckContrast {
interface Model{
/**【请求数据处理】**/
fun actionData()
}
interface ViewAndPresenter{
/**【请求数据】**/
fun requestData()
/**【相应请求数据】**/
fun responseData(list: List<String>)
}
}
|
3bb598342375963128bc1f719a50bbe7095c3e4f
|
[
"Java",
"Kotlin",
"Gradle"
] | 78 |
Kotlin
|
Git984265486/HuanJianMVP
|
058758ed3bad7e0d6612f49ec827bd6627fc462b
|
bc49f9bc4722047f42e3241a4413f38ebc2dab8e
|
refs/heads/master
|
<file_sep># libutils
A small library of utility methods I use in my C programs
<file_sep>WARNOPTS=-Wall -Wextra
DEBUG += ${DEBUGFLAGS}
INSTALLDIR=libutils
OPTI=
LIBDIR=${HOME}/lib/${INSTALLDIR}
INCDIR=${HOME}/include/${INSTALLDIR}
test: stringlib hashmaplib memorylib linkedlistlib test.c
gcc ${OPTI} ${DEBUG} -o test test.c -I./ -L./ -lstring -lhashmap -lmemory -llinkedlist
String.o: String.c String.h
gcc ${OPTI} ${DEBUG} ${WARNOPTS} -c String.c
stringlib: String.o
ar -rcs libstring.a String.o
Hashmap.o: stringlib Hashmap.c Hashmap.h
gcc ${OPTI} ${DEBUG} ${WARNOPTS} -c Hashmap.c -I./ -L./ -lstring
hashmaplib: Hashmap.o
ar -rcs libhashmap.a Hashmap.o
Memory.o: Memory.c Memory.h
gcc ${OPTI} ${DEBUG} ${WARNOPTS} -c Memory.c
memorylib: Memory.o
ar -rcs libmemory.a Memory.o
LinkedList.o: LinkedList.c LinkedList.h memorylib
gcc ${OPTI} ${DEBUG} ${WARNOPTS} -c LinkedList.c -I./ -L./ -lmemory
linkedlistlib: LinkedList.o
ar -rcs liblinkedlist.a LinkedList.o
utilslib: String.o Hashmap.o Memory.o LinkedList.o
ar -rcs libutils.a String.o Hashmap.o Memory.o LinkedList.o
install: utilslib
mkdir -p ${LIBDIR}
mkdir -p ${INCDIR}
cp -u *.a ${LIBDIR}
cp -u *.h ${INCDIR}
clean:
rm *.o *.a test
<file_sep>/* Hashmap.h */
#ifndef MEVANS_LIBUTILS_HASHMAP
#define MEVANS_LIBUTILS_HASHMAP
#include <stdlib.h>
#include "String.h"
#include "Memory.h"
typedef struct __hashmap_keyvaluepair {
String * key;
void * value;
struct __hashmap_keyvaluepair * next, * previous;
} Hashmap_KeyValuePair;
typedef struct __hashmap {
char * id;
Hashmap_KeyValuePair * firstKeyValuePair, *lastKeyValuePair;
Hashmap_KeyValuePair * currentKeyValuePair;
int size;
} Hashmap;
Hashmap * hashmapCreate();
int hashmapDestroy(Hashmap * hashmap);
int hashmapAdd(String * key, void * value, Hashmap * hashmap);
int hashmapRemove(String * key, Hashmap * hashmap);
void * hashmapGet(String * key, Hashmap * hashmap);
int hashmapSet(String * key, void * value, Hashmap * hashmap);
int hashmapSize(Hashmap * hashmap);
int hashmapHasKey(String * key, Hashmap * hashmap);
Hashmap_KeyValuePair * hashmapGetFirst(Hashmap * hashmap);
Hashmap_KeyValuePair * hashmapGetLast(Hashmap * hashmap);
Hashmap_KeyValuePair * hashmapGetNext(Hashmap * hashmap);
Hashmap_KeyValuePair * hashmapGetPrevious(Hashmap * hashmap);
int hashmapHasNext(Hashmap * hashmap);
int hashmapHasPrevious(Hashmap * hashmap);
// Utility methods, used internally by the methods above.
int __hashmap_is_valid(Hashmap * hashmap);
Hashmap_KeyValuePair * __hashmap_find(String * key, Hashmap * hashmap);
#endif<file_sep>/* Networking library
(C)2019 <NAME> */
#ifndef MEVANSPN_LIBUTILS_NETWORK
#define MEVANSPN_LIBUTILS_NETWORK
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Error.h"
typedef struct __network_addrinfo {
struct addrinfo * addressInfo;
Error error;
} AddressInfo;
typedef int SOCKET_TYPE;
const SOCKET_TYPE TCP = 1;
const SOCKET_TYPE UDP = 0;
typedef struct __network_socket {
int socketDescriptor;
AddressInfo * addressInfo;
Error error;
int isServer, isListening;
} Socket;
typedef struct __network_connection {
struct sockaddr_storage theirAddress;
int socketDescriptor;
Error error;
} SocketConnection;
AddressInfo * networkGetAddressInfo(const char * host, const char * port, SOCKET_TYPE socketType) {
int status;
struct addressinfo hints;
AddressInfo * serverInfo = (AddressInfo *) malloc(sizeof(AddressInfo));
if (socketType != TCP || socketType != UDP) {
setError(&serverInfo->error, 1, "Invalid socket type.\0");
return NULL;
}
if (port == NULL) {
setError(&serverInfo->error, 2, "NULL port value given.\n");
return NULL;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = (socketType == 0) ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_flags = AI_;
if ((status = getaddrinfo(host, port, &hints, &serverInfo->addressInfo)) != 0) {
setError(&serverInfo->error, 3, gai_strerror(status));
return NULL;
}
return serverInfo;
}
void networkFreeAddressInfo(AddressInfo * addressInfo) {
freeaddrinfo(addressInfo->addressInfo);
}
Socket * networkCreateClientSocket(const char * host, const char * port, SOCKET_TYPE socketType) {
Socket * s = (Socket *) malloc(sizeof(Socket));
s->addressInfo = networkGetAddressInfo(host, port, socketType);
if (s->addressInfo != NULL) {
s->socketDescriptor = socket( s->addressInfo->addressInfo->ai_family,
s->addressInfo->addressInfo->ai_socktype,
s->addressInfo->addressInfo->ai_protocol);
s->isServer = s->isListening = 0;
return s;
} else {
free(s);
return NULL;
}
}
Socket * networkCreateServerSocket(const char * host, const char * port, SOCKET_TYPE socketType) {
Socket * s = networkCreateClientSocket(host, port, socketType);
if (s != NULL) {
bind( s->socketDescriptor,
s->addressInfo->addressInfo->ai_addr,
s->addressInfo->addressInfo->ai_addrlen);
s->isServer = 1;
s->isListening = 0;
return s;
} else {
free(s);
return NULL;
}
}
int networkConnect(Socket * socket) {
if (socket != NULL) {
return connect(socket->socketDescriptor,
socket->addressInfo->addressInfo->ai_addr,
socket->addressInfo->addressInfo->ai_addrlen);
} else return -1;
}
int networkListen(Socket * socket) {
if (socket == NULL || !socket->isServer) return -1;
else {
socket->isListening = 1;
return listen(socket->socketDescriptor, 10);
}
}
SocketConnection * networkAcceptConnection(Socket * socket) {
if (socket == NULL || !socket->isListening) return NULL;
SocketConnection * sockConn = (SocketConnection *) malloc(sizeof(SocketConnection));
int ssize = sizeof sockConn->theirAddress;
sockConn->socketDescriptor =
accept(socket->socketDescriptor, (struct sockaddr *) &sockConn->theirAddress, &ssize);
if (sockConn->socketDescriptor == -1) {
free(sockConn);
return NULL;
}
return sockConn;
}
int networkSend(Socket * socket, const char * message, int messageLength) {
return send(socket->socketDescriptor, message, messageLength, 0);
}
#endif<file_sep>/* Memory.h
Memory management library
(C)2019 <NAME> */
#ifndef MEVANSPN_LIBUTILS_MEMORY
#define MEVANSPN_LIBUTILS_MEMORY
#include <stdlib.h>
typedef struct __libutils_memory {
char * id;
char * class;
char * data;
int size;
struct __libutils_memory * nextBlock, * previousBlock;
int (* destructor)(void *);
int (* sizeMethod)(void *);
int freed, destructorSet;
} Memory;
typedef struct __libutils_memory_manager {
char * id;
Memory * firstBlock, *lastCreated;
} MemoryManager;
static MemoryManager * MEM_MAN = NULL;
/* Creates a block of dynamic memory and associates it with the global memory manager.
Returns a pointer to the start of the allocated memory. */
void * memoryCreate(int size);
/* Frees a block of memory. Returns the number of bytes freed (or 0 if there was an
error) */
int memoryFree(void * dataPtr);
/* Sets all byte values in the block of memory pointed to at 'dataPtr' to have the value
'value'. */
int memorySet(void * dataPtr, char value);
/* Sets the contents of the memory block pointed to by 'dataPtr' to contain the string
or data pointed to by 'string'. 'stringLength' gives the length of the source string
(or data). If the block size is larger, the contents of the source is repeated until
the end of the memory block is reached. */
int memorySetString(void * dataPtr, char * string, int stringLength);
/* Indicates if the index ranges given by 'startOffset' and 'endOffset' fall within the
bounds of the memory block starting at 'dataPtr'. The method will return (0) if not
valid and (1) if the offsets are valid (fall within range) */
int memoryCheckRange(void * dataPtr, int startOffset, int endOffset);
/* Resizes a block of memory which starts at 'dataPtr'. 'newSize' gives the new size in
bytes. Note: If the new size if smaller than the original, data that falls outside
the new range will be discarded. */
void * memoryResize(void * dataPtr, const int newSize);
/* Can be called to fill memory using a user-defined method. 'dataPtr' points to the
start of the memory block to fill. 'fillMethod' is a pointer to the method used to
fill the memory. 'data' is a pointer to any ancillary information the method may need
in order to perform the fill operation. 'dataSize' gives the length of the anciallary
data in bytes.
An example memoryFill method is shown below:
void * addName(LinkedList * ll, char * name, int nameLen) {
linkedListAdd(name, ll);
}
Calling the method for example:
memoryFill(linkedList, &addName, "Morgan\0", 7);
Note, this is only an example to show how to define and call a memoryFill method and
is in no way ideal in demonstrating the purpose. */
void * memoryFill(void * dataPtr, void * (* fillMethod)(void *, void *, int), void * data,
int dataSize);
/* Copies the source data from 'data' up to 'maxCharsToCopy' into the memory block
starting at 'dataPtr'. Note, data will be truncated if the end of the memory block
is reached before 'maxCharsToCopy'. */
int memoryCopy(void * dataPtr, const char * data, int maxCharsToCopy);
/* Makes the memory block at 'dataPtr1' an exact copy of the memory block at 'dataPtr2',
including resizing/shrinking the memory area to match. */
int memoryClone(void * dataPtr1, void * dataPtr2);
/* Allows for a custom destructor method to be defined for the memory block. If set, the
destructor method is ALWAYS called before the memory is freed, which is useful where
the program may wish to perform routine house-keeping duties beforehand. */
void memorySetDestructor(void * dataPtr, int (*destructor)(void *));
/* If it exists, dissassociate the current destructor method from the memory block. */
void memoryRemoveDestructor(void *dataPtr);
/* Returns the size of the memory block at 'dataPtr'. The size is always in bytes. Note,
this is the size of the memory requested, not the size of the memory used by the internal
Memory structure. */
int memorySize(void * dataPtr);
/* Will free any memory blocks which have not been directly freed prior to this method
being called. If the memory blocks have associated destructor and memory sizing
methods, these will be used before the memory is freed. */
int memoryGC();
/* Allows a parent program to group allocated memory to a class. This allows for more fine-
tuned garbage collection operations and reporting. Note: class name can be no longer than
255 characters and MUST be zero terminated. */
void memorySetClass(void * dataPtr, const char * className);
/* Allows a parent program to get the memory class name. */
char * memoryGetClass(void * dataPtr);
// The following methods are used internally by the library and should not be called directly.
int __is_valid_memory(Memory * memory);
int __memory_set(void * memoryPointer, char value, int charsToSet);
int __memory_size(void * dataPtr);
#endif
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: LinkedList.h
* Author: morgan
*
* Created on 15 September 2019, 11:03
*/
#ifndef MEVANSPN_LIBUTILS_LINKEDLIST
#define MEVANSPN_LIBUTILS_LINKEDLIST
#include "Memory.h"
typedef struct __libutils_linked_list_element {
void * data;
struct __libutils_linked_list_element * nextElement, * previousElement;
} LinkedListElement;
typedef struct __libutils_linked_list {
LinkedListElement * firstElement, * currentElement;
int size;
} LinkedList;
LinkedList * linkedListCreate();
int linkedListDestroy(LinkedList * list);
int linkedListRemove(LinkedListElement * listElement, LinkedList * list);
int linkedListAdd(void * data, LinkedList * list);
int linkedListInsert(void * data, LinkedListElement * target, LinkedList * list);
LinkedListElement * linkedListGetFirst(LinkedList * list);
LinkedListElement * linkedListGetLast(LinkedList * list);
LinkedListElement * linkedListGetNext(LinkedList * list);
LinkedListElement * linkedListGetPrevious(LinkedList * list);
int linkedListSize(LinkedList * list);
int __linked_list_element_exists(LinkedListElement * element,
LinkedList * list);
int __linked_list_size(LinkedList * ll);
#endif /* LINKEDLIST_H */
<file_sep>/* HashMap.c
A simple HashMap library for use with Hashmap
(C)2019 M.Evans */
#include "Hashmap.h"
/** createHashMap - creates an empty hashmap data structure. */
Hashmap * hashmapCreate() {
Hashmap * hashmap = (Hashmap *) memoryCreate(sizeof(Hashmap));
hashmap->id = (char *) memoryCreate(2);
hashmap->id[0] = 'h'; hashmap->id[1] = 'm';
hashmap->firstKeyValuePair = hashmap->lastKeyValuePair = NULL;
hashmap->currentKeyValuePair = NULL;
hashmap->size = 0;
memorySetClass(hashmap,"Hashmap\0");
memorySetDestructor(hashmap,&hashmapDestroy);
return hashmap;
}
int hashmapDestroy(Hashmap * hashmap) {
int memoryFreed = 0;
memoryRemoveDestructor(hashmap);
if (!__hashmap_is_valid(hashmap)) return 0;
if (hashmap->size > 0)
while (hashmap->firstKeyValuePair != NULL) {
memoryFreed += hashmapRemove(hashmap->firstKeyValuePair->key, hashmap);
}
hashmap->lastKeyValuePair = hashmap->currentKeyValuePair = NULL;
hashmap->size = 0;
memoryFreed += memoryFree(hashmap->id);
memoryFreed += memoryFree(hashmap);
return memoryFreed;
}
int hashmapRemove(String * key, Hashmap * hashmap) {
int memoryFreed = 0;
// Sanity check, make sure valid values passed to method.
if (!__string_is_valid(key) || !__hashmap_is_valid(hashmap)) return 0;
// Try to find the key/value in the hashmap using the given key.
Hashmap_KeyValuePair * kvp = __hashmap_find(key, hashmap);
// Return false (0) if no key/value pair exists.
if (kvp == NULL) return 0;
// Record the pointer to the next kay/value pair in the hashmap.
Hashmap_KeyValuePair * NEXT_KVP = kvp->next;
// Update the pointers for previous/next key/value pair entries in the hashmap.
if (kvp->previous != NULL) kvp->previous->next = NEXT_KVP;
if (NEXT_KVP != NULL) NEXT_KVP->previous = kvp->previous;
// If this key/value pair is the first in the hashmap update the pointer accordingly.
if (kvp == hashmap->firstKeyValuePair) hashmap->firstKeyValuePair = NEXT_KVP;
if (kvp == hashmap->currentKeyValuePair)
hashmap->currentKeyValuePair = hashmap->firstKeyValuePair;
// Delete the data structure for the key/value pair.
memoryFreed += stringDestroy(kvp->key);
kvp->value = kvp->key = NULL;
kvp->next = kvp->previous = NULL;
memoryFreed += memoryFree(kvp);
// Reduce the size attribute by one.
hashmap->size--;
// Return true (1) to indicate removal was successful.
return memoryFreed;
}
int hashmapAdd(String * key, void * value, Hashmap * hashmap) {
if (!__string_is_valid(key) || !__hashmap_is_valid(hashmap)) return 0;
Hashmap_KeyValuePair * kvp = __hashmap_find(key, hashmap);
if (kvp != NULL) return 0;
kvp = hashmap -> firstKeyValuePair;
while (kvp != NULL && kvp->next != NULL) kvp = kvp->next;
if (kvp == NULL) {
kvp = (Hashmap_KeyValuePair *) memoryCreate(sizeof(Hashmap_KeyValuePair));
kvp->key = stringCopy(key);
kvp->value = value;
kvp->next = kvp->previous = NULL;
hashmap->firstKeyValuePair = kvp;
hashmap->lastKeyValuePair = hashmap->currentKeyValuePair = kvp;
} else {
Hashmap_KeyValuePair * newkvp =
(Hashmap_KeyValuePair *) memoryCreate(sizeof(Hashmap_KeyValuePair));
newkvp->key = stringCopy(key);
newkvp->value = value;
newkvp->next = NULL;
newkvp->previous = kvp;
kvp->next = newkvp;
hashmap->lastKeyValuePair = hashmap->currentKeyValuePair = newkvp;
memorySetClass(newkvp,"HashmapKVP\0");
}
hashmap->size++;
return 1;
}
int hashmapSet(String * key, void * value, Hashmap * hashmap) {
if (!__string_is_valid(key) || !__hashmap_is_valid(hashmap)) return 0;
Hashmap_KeyValuePair * kvp = __hashmap_find(key, hashmap);
if (kvp == NULL) return 0;
kvp->value = value;
hashmap->currentKeyValuePair = kvp;
return 1;
}
void * hashmapGet(String * key, Hashmap * hashmap) {
if (!__string_is_valid(key) || !__hashmap_is_valid(hashmap)) return NULL;
Hashmap_KeyValuePair * kvp = __hashmap_find(key, hashmap);
if (kvp == NULL) return NULL;
hashmap->currentKeyValuePair = kvp;
return kvp->value;
}
int hashmapSize(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return -1;
else return hashmap->size;
}
int hashmapHasKey(String * key, Hashmap * hashmap) {
if (!__string_is_valid(key) || !__hashmap_is_valid(hashmap)) return 0;
return (__hashmap_find(key, hashmap) != NULL);
}
Hashmap_KeyValuePair * hashmapGetFirst(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return NULL;
hashmap->currentKeyValuePair = hashmap->firstKeyValuePair;
return hashmap->currentKeyValuePair;
}
Hashmap_KeyValuePair * hashmapGetLast(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return NULL;
hashmap->currentKeyValuePair = hashmap->lastKeyValuePair;
return hashmap->currentKeyValuePair;
}
Hashmap_KeyValuePair * hashmapGetNext(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return NULL;
if (hashmap->currentKeyValuePair == NULL) return NULL;
hashmap->currentKeyValuePair = hashmap->currentKeyValuePair->next;
return hashmap->currentKeyValuePair;
}
Hashmap_KeyValuePair * hashmapGetPrevious(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return NULL;
if (hashmap->currentKeyValuePair == NULL) return NULL;
hashmap->currentKeyValuePair = hashmap->currentKeyValuePair->previous;
return hashmap->currentKeyValuePair;
}
int hashmapHasNext(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return 0;
return (hashmap->currentKeyValuePair->next != NULL);
}
int hashmapHasPrevious(Hashmap * hashmap) {
if (!__hashmap_is_valid(hashmap)) return 0;
return (hashmap->currentKeyValuePair->previous != NULL);
}
int __hashmap_is_valid(Hashmap * hashmap) {
if (hashmap == NULL) return 0;
if (hashmap->id[0] != 'h') return 0;
if (hashmap->id[1] != 'm') return 0;
return 1;
}
Hashmap_KeyValuePair * __hashmap_find(String * key, Hashmap * hashmap) {
// Sanity check, make sure the calling method has passed valid values.
if (!__string_is_valid(key) || !__hashmap_is_valid(hashmap)) return NULL;
// Get the first key/value pair in the hashmap.
Hashmap_KeyValuePair * kvp = hashmap->firstKeyValuePair;
// Iterate through all key/value pairs until there are none left.
while (kvp != NULL) {
// Do a case-sensitive comparision of the key value of the current pair's key with
// the required key value.
int i = 0;
while (i < key->length && key->data[i] !=0 && key->data[i] == kvp->key->data[i]) i++;
if (key->data[i] == 0 && kvp->key->data[i] == 0) break; // If we found a match, exit loop...
else kvp = kvp->next; // ... otherwise, get the next key/value pair.
}
// Return the last key/value pair pointer read (can be NULL if no match)
return kvp;
}<file_sep>/* String.c
A library of useful methods related to string interrogation and manipulation
(C)2019 <NAME> */
#include "String.h"
int __string_is_valid(String * string) {
if (string == NULL || string->id[0] != 's' || string->id[1] != 'g') return 0;
return 1;
}
String * stringCreate(const char * value) {
// Get the length of the source string, if any is given.
int stringLength = 0;
if (value != NULL)
while (value[stringLength] != 0 && stringLength < MAXIMUM_STRING_LENGTH) stringLength++;
String * string = (String *) memoryCreate(sizeof(String));
string->id = (char *) memoryCreate(2);
string->id[0] = 's'; string->id[1] = 'g';
string->data = NULL;
string->length = 0;
if (stringLength > 0) stringSetValue(string, value, stringLength + 1);
memorySetDestructor(string, &stringDestroy);
memorySetClass(string,"String\0");
return string;
}
int stringDestroy(String * string) {
int memoryFreed = 0;
memoryRemoveDestructor(string);
if (!__string_is_valid(string)) return;
memoryFreed += memoryFree(string->id);
memoryFreed += memoryFree(string->data);
string->id = string->data = NULL;
string->length = 0;
memoryFreed += memoryFree(string);
return memoryFreed;
}
int stringLength(String * string) {
if (!__string_is_valid(string)) return 0;
return string->length;
}
void stringSetValue(String * target, const char * string, int stringLength) {
if (!__string_is_valid(target)) return;
if (target->data != NULL) memoryFree(target->data);
target->data = (char *) memoryCreate(stringLength);
target->length = stringLength;
memoryCopy(target->data, string, stringLength);
target->data[stringLength] = 0;
}
char * stringGetValue(String * string) {
if (!__string_is_valid(string)) return NULL;
else return string->data;
}
int stringCompare(String * subject, String * reference, int caseType)
{
if (!__string_is_valid(subject) || !__string_is_valid(reference)) return 0;
const int STRING1_LEN = stringLength(subject);
if (STRING1_LEN != stringLength(reference)) return 0;
int i = 0;
const char * string1 = subject->data;
const char * string2 = reference->data;
if (caseType == STRING_CASE_SENSITIVE)
while (string1[i] == string2[i] && i < STRING1_LEN) i++;
else {
while (i < STRING1_LEN) {
if (string1[i] != string2[i]) {
if (string1[i] >= 'a' && string1[i] <= 'z' && string1[i] != string2[i] - 32) break;
else if (string1[i] >= 'A' && string1[i] <= 'Z' && string1[i] != string2[i] + 32) break;
else break;
}
}
}
if (i == STRING1_LEN) return 1;
return 0;
}
String * stringCopy(String * string) {
if (!__string_is_valid(string)) return NULL;
return stringCreate(string->data);
}
double stringParseDouble(String * string, int decimalPlaces)
{
if (!__string_is_valid(string)) return 0;
const int STRING_LENGTH = stringLength(string);
if (decimalPlaces < 0) decimalPlaces = 0;
int signs = 0, periods = 0, negative = 1, dp = 0;
double value = 0;
for (int i = 0; i < STRING_LENGTH; i++) {
if ((string->data[i] & 48) == 48) {
const int v = string->data[i] & 15;
if (v > 9) return 0;
else {
if (periods > 0 && dp == decimalPlaces) {
if (v >= 5) value++;
break;
} else
{
value = (value * 10) + v;
if (periods > 0) dp++;
}
}
} else if (string->data[i] == '-') {
signs++;
if (signs > 1) return 0;
else negative = -1;
} else if (string->data[i] == '.') {
periods++;
if (periods > 1) return 0;
} else return 0;
}
for (int i = 0; i < dp; i++) value = value / 10.0;
return value * negative;
}
int stringParseInt(String * string) {
return (int) stringParseDouble(string, 0);
}
<file_sep>#include "Memory.h"
int __memory_is_valid(Memory * memory) {
if (memory == NULL) return 0;
if (memory->id[0] != 'l' && memory->id[1] != 'm') return 0;
if (memory->size == 0) return 0;
if (memory->data == NULL) return 0;
return 1;
}
Memory * __memory_find(void * dataPtr) {
if (MEM_MAN == NULL || MEM_MAN->firstBlock == NULL) return NULL;
Memory * m = MEM_MAN->firstBlock;
while (m != NULL && m->data != dataPtr) m = m->nextBlock;
return m;
}
int __memory_size(void * dataPtr) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return 0;
if (m->sizeMethod != NULL) return (*m->sizeMethod)(dataPtr);
else return (m->size + sizeof(Memory));
}
int __memory_set(void * memoryPointer, char value, int charsToSet) {
if (memoryPointer == NULL) return 0;
for (int i = 0; i < charsToSet; i++) ((char *)memoryPointer)[i] = value;
return 1;
}
void * memoryCreate(int size) {
if (MEM_MAN == NULL) {
MEM_MAN = (MemoryManager *) malloc(sizeof(MemoryManager));
MEM_MAN->firstBlock = MEM_MAN->lastCreated = NULL;
}
if (size < 2) return NULL;
Memory * memory = (Memory *) malloc(sizeof(Memory));
memory->id = (char *) malloc(sizeof(char) * 2);
memory->id[0] = 'l'; memory->id[1] = 'm';
memory->size = size;
memory->data = (void *) malloc(sizeof(char) * size);
memory->nextBlock = memory->previousBlock = NULL;
memory->destructor = NULL;
memory->destructorSet = 0;
memory->sizeMethod = NULL;
memory->freed = 0;
memory->class = NULL;
if (MEM_MAN->firstBlock == NULL)
MEM_MAN->firstBlock = memory;
else {
MEM_MAN->lastCreated->nextBlock = memory;
memory->previousBlock = MEM_MAN->lastCreated;
}
MEM_MAN->lastCreated = memory;
return memory->data;
}
int memoryFree(void * dataPtr) {
int memoryFreed = 0;
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return 0;
if (m->freed) return 0;
if (m->destructorSet)
memoryFreed += (*m->destructor)(dataPtr);
else {
if (m->nextBlock != NULL)
m->nextBlock->previousBlock = m->previousBlock;
if (m->previousBlock != NULL)
m->previousBlock->nextBlock = m->nextBlock;
if (m == MEM_MAN->firstBlock) MEM_MAN->firstBlock = m->nextBlock;
if (m == MEM_MAN->lastCreated) MEM_MAN->lastCreated = m->previousBlock;
memoryFreed += m->size + sizeof(m->id) + sizeof(Memory);
if (m->class != NULL) memoryFreed += sizeof(m->class);
free(m->id);
free(m->data);
if (m->class != NULL) free(m->class);
m->size = 0;
m->id = m->data = NULL;
m->freed = 1;
m->class = NULL;
free(m);
}
return memoryFreed;
}
int memorySet(void * dataPtr, char value) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return 0;
return __memory_set(m->data, value, m->size);
}
int memorySetString(void * dataPtr, char * string, int stringLength) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return 0;
if (string == NULL || stringLength < 1) return 0;
int i = 0;
while (i < m->size) {
int j = 0;
while (i < m->size && j < stringLength)
m->data[i++] = string[j++];
}
return 1;
}
int memoryCheckRange(void * dataPtr, int startOffset, int endOffset) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return 0;
if (startOffset < 0 || endOffset < 0) return 0;
if (startOffset > endOffset) {
int temp = startOffset;
startOffset = endOffset;
endOffset = temp;
}
if (m->data + startOffset > m->data + m->size) return 0;
if (m->data + endOffset > m->data + m->size) return 0;
return 1;
}
void * memoryResize(void * dataPtr, const int newSize) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m) || newSize < 2) return 0;
m->data = (char *) realloc(m->data, newSize);
m->size = newSize;
return m->data;
}
void * memoryFill(void * dataPtr, void * (* fillMethod)(void *, void *, int), void * data, int dataSize) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m) || fillMethod == NULL) return 0;
return (*fillMethod)(m->data, data, dataSize);
}
int memoryCopy(void * dataPtr, const char * data, int maxCharsToCopy) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m) || data == NULL || maxCharsToCopy < 1) return 0;
if (maxCharsToCopy > m->size) maxCharsToCopy = m->size;
for (int i = 0; i < maxCharsToCopy; i++) m->data[i] = data[i];
return maxCharsToCopy;
}
int memoryClone(void * dataPtr1, void * dataPtr2) {
Memory * m1 = __memory_find(dataPtr1);
Memory * m2 = __memory_find(dataPtr2);
if (!__memory_is_valid(m1) || !__memory_is_valid(m2)) return 0;
if (m1->size != m2->size) {
m1->data = (char *) realloc(m1->data, m2->size);
m1->size = m2->size;
}
return memoryCopy(m1->data, m2->data, m2->size);
}
void memorySetDestructor(void * dataPtr, int (*destructor)(void *)) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return;
m->destructor = destructor;
m->destructorSet = (destructor == NULL) ? 0 : 1;
}
int memorySize(void * dataPtr) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return -1;
return m->size;
}
int memoryGC() {
int memoryFreed = 0;
if (MEM_MAN != NULL) {
while (MEM_MAN->firstBlock != NULL && __memory_is_valid(MEM_MAN->firstBlock))
memoryFreed += memoryFree(MEM_MAN->firstBlock->data);
free(MEM_MAN);
MEM_MAN = NULL;
}
return memoryFreed;
}
void memorySetClass(void * dataPtr, const char * className) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m) || className == NULL) return;
int stringLength = 0;
while (stringLength < 255 && className[stringLength] != 0) stringLength++;
if (stringLength == 0) return;
m->class = (char *) malloc(sizeof(char) * (stringLength + 1));
int i;
for (i = 0; i < stringLength; i++) m->class[i] = className[i];
m->class[i] = 0;
}
char * memoryGetClass(void * dataPtr) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return NULL;
return m->class;
}
void memoryRemoveDestructor(void *dataPtr) {
Memory * m = __memory_find(dataPtr);
if (!__memory_is_valid(m)) return;
if (m->destructorSet && m->destructor != NULL) {
m->destructorSet = 0;
m->destructor = NULL;
}
}<file_sep>/* String.h */
#ifndef MEVANS_LIBUTILS_STRING
#define MEVANS_LIBUTILS_STRING
#include <stdlib.h>
#include <stdint.h>
#include "Memory.h"
#define STRING_CASE_SENSITIVE 0
#define STRING_CASE_INSENSITIVE 1
#define MAXIMUM_STRING_LENGTH 32768
typedef struct __libutils_string {
char * id;
char * data;
int length;
} String;
/* Creates a new string object using the raw character string stored at 'value'. If
NULL is used for value, an empty string object is created. */
String * stringCreate(const char * value);
/* Used to destroy the string 'string' and free any memory assocaited with it. */
int stringDestroy(String * string);
/* Sets the value of the string 'target' to be the same as the raw character string
found at 'string' and of length 'stringLength'. */
void stringSetValue(String * target, const char * string, int stringLength);
/* Returns the raw character string value of the string at 'string'. */
char * stringGetValue(String * string);
/* Get length of string in characters. */
int stringLength(String * string);
/* Compare two strings, case sensitivity is given using the 'caseType' parameter and
should be given using one of the two constant values above prefixed as STRING_CASE_ */
int stringCompare(String * subject, String * reference, int caseType);
/* Returns a copy of the string stored at 'string'. */
String * stringCopy(String * string);
/* Takes a numerical string and tries to parse it as a double type value. The maximum
number of decimal places can be defined using 'decimalPlaces'. */
double stringParseDouble(String * string, int decimalPlaces);
/* Takes a numerical string and tries to parse it as an integer type value. */
int stringParseInt(String * string);
// Internal library methods, do not use!
int __string_is_valid(String * string);
#endif
<file_sep>/* test.c */
#include "String.h"
#include "Hashmap.h"
#include "Memory.h"
#include "LinkedList.h"
#include <stdio.h>
void * DegToRad(void * dataPtr, void * data, int dataLen) {
float * accuracyLevelPtr = (float *) data;
float accuracyLevel = *accuracyLevelPtr;
if (accuracyLevel < 1) accuracyLevel = 1;
const int requiredSize = sizeof(float) * (360 * accuracyLevel);
if (memorySize(dataPtr) != requiredSize)
dataPtr = memoryResize(dataPtr, requiredSize);
float pideg = (3.142 * 2) / (360.0 * accuracyLevel);
float * f = (float *) dataPtr;
for (int i = 0; i < 360 * accuracyLevel; i++) f[i] = pideg * i;
return dataPtr;
}
int main(int argc, char ** argv)
{
float * degrees = memoryCreate(sizeof(float) * 360);
printf("Size of degrees memory before fill = %d\n",
memorySize(degrees));
float accuracy = 2;
degrees = memoryFill(degrees, &DegToRad, &accuracy, 0);
printf("Size of degrees memory after DegToRad fill = %d\n",
memorySize(degrees));
LinkedList * ll = linkedListCreate();
linkedListAdd("Test\0", ll);
linkedListAdd("Test2\0", ll);
linkedListAdd("Banana pajama hamma\0", ll);
LinkedListElement * lle = linkedListGetFirst(ll);
while (lle != NULL) {
printf("\tLinked list value = %s\n", (char *)lle->data);
lle = linkedListGetNext(ll);
}
printf("Linked list size = %d\n", linkedListSize(ll));
Hashmap * hm = hashmapCreate();
hashmapAdd(stringCreate("Key0\0"), "10\0", hm);
hashmapAdd(stringCreate("Key1\0"), "20\0", hm);
printf("Hashmap size = %d entries.\n", hashmapSize(hm));
Hashmap_KeyValuePair * kvp = hashmapGetFirst(hm);
do {
printf("Hashmap key:value = %s:%s\n",stringGetValue(kvp->key),kvp->value);
kvp = hashmapGetNext(hm);
} while (kvp != NULL);
// Uncomment these two if you want them to be picked up by the garbage collector.
// hashmapDestroy(hm);
// linkedListDestroy(ll);
int memoryFreed = memoryGC();
printf("Garbage collector freed %d bytes.\n", memoryFreed);
return 1;
}
<file_sep>/* Error.h
Allows me to store an error number and message within data structutes.
(C)2019 <NAME> */
#ifndef MEVANSPN_LIBUTILS_ERROR
#define MEVANSPN_LIBUTILS_ERROR
#include "String.h"
typedef struct __libutils_error {
char * message;
int number;
} Error;
void setError(Error * error, int number, const char * message) {
if (error->number != 0 || error->message != NULL) {
free(error->message);
}
error->number = number;
error->message = stringCopy(message, 256);
}
void clearError(Error * error) {
if (error->number != 0 || error->message != NULL) {
free(error->message);
error->number = 0;
error->message = NULL;
}
}
int noError(Error * error) {
return (error->number == 0 && error->message == NULL);
}
#endif<file_sep>/* LinkedList.c
* A simple doubly-linked list storage library.
* (Note: This is the first library to make full use of libmemory to manage
* storage. The plan is to change libstring, libnetwork and libhashmap later.
* (C)2019 <NAME>
*/
#include "LinkedList.h"
LinkedList * linkedListCreate() {
LinkedList * linkedList = (LinkedList *) memoryCreate(sizeof(LinkedList));
linkedList->firstElement = linkedList->currentElement = NULL;
linkedList->size = 0;
memorySetDestructor(linkedList, &linkedListDestroy);
memorySetClass(linkedList, "LinkedList\0");
return linkedList;
}
int linkedListDestroy(LinkedList * list) {
int memoryFreed = 0;
memoryRemoveDestructor(list);
if (list == NULL || list->size <= 0) return 0;
while (list->firstElement != NULL)
memoryFreed += linkedListRemove(list->firstElement,list);
list->size = 0;
list->firstElement = list->currentElement = NULL;
return memoryFreed + memoryFree(list);
}
int linkedListRemove(LinkedListElement * listElement, LinkedList * list) {
int memoryFreed = 0;
if (!__linked_list_element_exists(listElement, list)) return 0;
if (listElement->nextElement != NULL)
listElement->nextElement->previousElement = listElement->previousElement;
if (listElement->previousElement != NULL)
listElement->previousElement->nextElement = listElement->nextElement;
if (listElement == list->firstElement)
list->firstElement = listElement->nextElement;
if (listElement == list->currentElement)
list->currentElement = list->firstElement;
listElement->nextElement = listElement->previousElement = NULL;
listElement->data = NULL;
memoryFreed += memoryFree(listElement);
list->size--;
return memoryFreed;
}
int linkedListAdd(void * data, LinkedList * list) {
if (data == NULL || list == NULL || list->size < 0) return 0;
LinkedListElement * lle = memoryCreate(sizeof(LinkedListElement));
lle->data = data;
lle->nextElement = lle->previousElement = NULL;
if (list->firstElement == NULL)
list->firstElement = list->currentElement = lle;
else {
LinkedListElement * e = list->firstElement;
while (e->nextElement != NULL) e = e->nextElement;
e->nextElement = lle;
lle->previousElement = e;
}
memorySetClass(lle, "LinkedListElement\0");
list->currentElement = lle;
list->size++;
return 1;
}
int linkedListInsert(void * data, LinkedListElement * target, LinkedList * list) {
if (!__linked_list_element_exists(target, list)) return 0;
if (data == NULL) return 0;
LinkedListElement * lle = memoryCreate(sizeof(LinkedListElement));
lle->data = data;
lle->nextElement = lle->previousElement = NULL;
LinkedListElement * e = list->firstElement;
while (e != NULL && e != target) e = e->nextElement;
if (e == NULL) return 0;
else {
if (e->nextElement != NULL) e->nextElement->previousElement = lle;
lle->nextElement = e->nextElement;
e->nextElement = lle;
lle->previousElement = e;
}
list->size++;
return 1;
}
LinkedListElement * linkedListGetFirst(LinkedList * list) {
if (list == NULL || list->size <= 0) return NULL;
list->currentElement = list->firstElement;
return list->firstElement;
}
LinkedListElement * linkedListGetLast(LinkedList * list) {
if (list == NULL || list->size <= 0) return NULL;
LinkedListElement * e = list->firstElement;
while (e->nextElement != NULL) e = e->nextElement;
list->currentElement = e;
return e;
}
LinkedListElement * linkedListGetNext(LinkedList * list) {
if (list == NULL || list->size <= 0) return NULL;
if (list->currentElement == NULL) return NULL;
list->currentElement = list->currentElement->nextElement;
return list->currentElement;
}
LinkedListElement * linkedListGetPrevious(LinkedList * list) {
if (list == NULL || list->size <= 0) return NULL;
if (list->currentElement == NULL) return NULL;
list->currentElement = list->currentElement->previousElement;
return list->currentElement;
}
int linkedListSize(LinkedList * list) {
if (list == NULL) return 0;
return list->size;
}
int __linked_list_element_exists(LinkedListElement * element,
LinkedList * list) {
if (list == NULL || list->size <= 0 || element == NULL) return 0;
LinkedListElement * e = list->firstElement;
while (e != NULL && e != element) e = e->nextElement;
if (e == element) return 1;
else return 0;
}
int __linked_list_size(LinkedList * ll) {
int size = sizeof(LinkedList);
LinkedListElement * lle = ll->firstElement;
while (lle != NULL) {
size += sizeof(LinkedListElement) + sizeof(lle->data);
lle = lle->nextElement;
}
return size;
}
|
6710dff190aa2435ac6aaadd2103002f544bccbd
|
[
"Markdown",
"C",
"Makefile"
] | 13 |
Markdown
|
gittymo/libutils
|
abecfa649c7b6bde46775694b73f99a7dcf35d0d
|
51b5a56262d0c9eaf88f12eb0a25a78212c6fcbc
|
refs/heads/master
|
<repo_name>skyhilam/bocmacau<file_sep>/telegram.js
require('dotenv').config()
const axios = require('axios')
const tg = {
send(message, token) {
return axios({
url: 'https://tg.iclover.net/send',
// timeout: 30,
method: 'post',
data: {
message,
token
}
})
}
}
module.exports = tg
<file_sep>/README.md
# 澳門中銀 澳門元/人民幣 匯率
每日下午三點自動透過 [clover_computer_ltd_bot](https://t.me/clover_computer_ltd_bot) 通知指定用戶最新匯率
## 安裝
```js
npm i
npm start
```
## 參數
TG_TOKEN=(your token)
## 其他參考資料
* https://www.npmjs.com/package/dotenv
* https://crontab.guru/every-day-8am
* https://www.npmjs.com/package/node-schedule
* https://github.com/axios/axios
* https://www.npmjs.com/package/node-html-parser
<file_sep>/index.js
require('dotenv').config()
const tg = require('./telegram');
const boc = require('./boc');
const schedule = require('node-schedule');
(async () => {
// const message = await boc.get()
// await tg.send(message, process.env.TG_TOKEN)
schedule.scheduleJob('0 15 * * *', async() => {
console.log('send message to client')
const message = await boc.get()
await tg.send(message, process.env.TG_TOKEN)
});
})()
|
2ec531aa091b86294ad81c576bf7532e0cec5be2
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
skyhilam/bocmacau
|
5cf7c0bef85ead162c9aaecd1ba822608f6ee9a9
|
7bdf3c162592bcebf81e19f8e4db5c4f23bd8033
|
refs/heads/master
|
<repo_name>crashantrax/debug<file_sep>/application/views/pages/login.php
<!DOCTYPE html>
<html>
<head>
<title><?= $pagename;?> : Student Information System</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body style="background-color: black;">
<div class="jumbotron text-center">
<h1>Student Information System</h1>
<p>University of Science and Technology of Southern Philippines</p>
</div>
<div class="container" style="padding-left: 20%;padding-top: 30px;">
<div class="col-md-8">
<form action="<?= base_url('system/dashboard'); ?>" method="POST">
<div>
<!-- <img src="">
<div class="panel-heading">
<h3>Login</h3>
</div> -->
<div class="well">
<h3>Login</h3>
<div class="form-group">
<i class="glyphicon glyphicon-user"></i>
<input class="form-control" type="text" name="username" placeholder="Username">
</div>
<div class="form-group">
<i class="glyphicon glyphicon-lock"></i>
<input class="form-control" type="password" name="password" placeholder="<PASSWORD>">
</div>
<a href="">Forgot Password</a>
<button type="submit" class="btn btn-primary" style="margin-left: 50%;width: 100px;">Login</button>
</div>
</div>
</form>
</div>
</div>
</body>
<div style="text-align: center;">
<h5>Copyright 2019 Server</h5>
</div>
</html><file_sep>/application/views/pages/dashboard.php
<!DOCTYPE html>
<html>
<head>
<title><?= $pagename;?> : Student Information System</title>
</head>
<body>
</body>
</html><file_sep>/application/views/pages/register.php
<!DOCTYPE html>
<html>
<head>
<title><?= $pagename;?> : Student Information System</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body style="background-color: black;">
<div class="jumbotron text-center">
<h1>Student Information System</h1>
<p>University of Science and Technology of Southern Philippines</p>
</div>
<nav class="navbar navbar-inverse" style="margin-top:-30px;">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#"> USTSP </a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">About</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphicon-user"></span> Register</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</nav>
<div class="container" style="padding-left: 20%;padding-top: 30px;">
<div class="col-md-8">
<form action="<?= base_url('system/dashboard'); ?>" method="POST">
<div>
<!-- <img src="">
<div class="panel-heading">
<h3>Login</h3>
</div> -->
<div class="well">
<h3>Login</h3>
<div class="form-group">
<i class="glyphicon glyphicon-user"></i>
<input class="form-control" type="text" name="username" placeholder="Username">
</div>
<div class="form-group">
<i class="glyphicon glyphicon-lock"></i>
<input class="form-control" type="<PASSWORD>" name="password" placeholder="<PASSWORD>">
</div>
<div class="form-group">
<i class="glyphicon glyphicon-lock"></i>
<input class="form-control" type="password" name="retype-password" placeholder="Retype Password">
</div>
<a href="<?= base_url() ?>">Forgot Password</a>
<button type="submit" class="btn btn-primary" style="margin-left: 50%;width: 100px;">Login</button>
</div>
</div>
</form>
</div>
</div>
</body>
<div style="text-align: center;">
<h5>Copyright by JPTiu</h5>
</div>
</html><file_sep>/application/views/pages/index.php
<!DOCTYPE html>
<html>
<head>
<title><?= $pagename;?> : Student Information System</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body style="background-color: black;">
<div class="jumbotron text-center">
<h1>Student Information System</h1>
<p>University of Science and Technology of Southern Philippines</p>
</div>
<nav class="navbar navbar-inverse" style="margin-top:-30px;">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#"> USTSP </a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">About</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="<?= base_url('system/register') ?>"><span class="glyphicon glyphicon-user"></span> Register</a></li>
<li><a href=""><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</nav>
<?php
if(isset($content)){
$this->load->view($content);
}else{
echo "No Page to Display!";
}
?>
</body>
<div style="text-align: center;">
<h5>Copyright by JPTiu</h5>
</div>
</html>
|
6fb1afef1a921998b563f2439dc7fbbb9ec8e009
|
[
"PHP"
] | 4 |
PHP
|
crashantrax/debug
|
5dafd238ab3dfc8fd9585d7778cf371fe4178a4d
|
dfe57dc26586510142ab04c4a7acd0ea16fc4811
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
try:
import pypandoc
description = pypandoc.convert('README.md', 'rst')
except:
description = ''
setup(
name='json_diff_patch',
version='0.5.0',
packages=['json_diff_patch'],
package_dir={'json_diff_patch': 'lib'},
install_requires=['colorama'],
entry_points={
'console_scripts': [
'json = json_diff_patch.__main__:main',
]
},
author='apack1001',
author_email='<EMAIL>',
url='https://github.com/apack1001/json-diff-patch',
description='A set of tools to manipulate JSON: diff, patch, pretty-printing',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License'
],
keywords=['json'],
long_description=description
)
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
from __future__ import print_function
from .loader import load
#!/usr/bin/env python
# coding: utf-8
def arrayPremitiveHaveSameType(value1, value2):
if isinstance(value1, dict) or isinstance(value2, dict):
return False
if isinstance(value1, list) or isinstance(value2, list):
return False
return True
##
# @brief When all the keys of this object are the same it take effect.
#
# @param value1 the first element
# @param value2 the second element
#
# @return True if match else False
def objectHaveCommonKeys(value1, value2):
if (value1 == value2):
return True
# fix issue #27. AttributeError: 'NoneType' object has no attribute 'has_key'
if value1 != None and value2 == None:
return False
if value1 == None and value2 != None:
return False
# issue 28. AttributeError: 'unicode' object has no attribute 'keys'
if type(value1) == dict and type(value2) == dict:
cntCommonKeys = 0
for key in value1.keys():
if value2.has_key(key):
cntCommonKeys = cntCommonKeys + 1
#TODO
if (len(value1.keys()) == cntCommonKeys or len(value2.keys()) == cntCommonKeys):
return True
if (float(cntCommonKeys) / float(len(value1.keys())) >= 0.8):
return True
else:
return False
return False
##
# @brief Determine whether two object have common keys and object-kind child.
#
# @param value1 the first element
# @param value2 the second element
#
def haveCompositeSimilarSubkeys(value1, value2):
if value1 == value2:
return True
# 1.1. value1 and value2 are not dict object
if isinstance(value1, dict) == False or \
isinstance(value2, dict) == False:
return False
# 1.2. value1 and value2 have same keys, and have dict or list child element.
has = False
for k in value1.keys():
if value2.has_key(k):
has = True
if has:
for k,item in value1.iteritems():
if isinstance(item, dict) or isinstance(item, list):
return True
for k,item in value2.iteritems():
if isinstance(item, dict) or isinstance(item, list):
return True
return False
return value1 == value2
##
# @brief a kind of json diff algorithm named after Benjamin.
#
# This algorithm gains inspiration from an open-source project on github.
# URL: https://github.com/benjamine/jsondiffpatch/
#
# Original algorithm is described on Wikipedia.
# URL: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
#
class BenjaminJsonDiff:
def __init__(self):
self.result = []
##
# @brief Try diff this two array child object element
#
# @param array1 the first array
# @param array2 the second array
# @param index1 the index of element in first array
# @param index2 the index of element in second array
# @param path the path of original array
#
def tryObjectInnerDiff(self, array1, array2, index1, index2, path):
delim = '/' if path != '/' else ''
# if isinstance(array1[index1], dict) == False or \
# isinstance(array2[index2], dict) == False:
# return
# self.__object_diff__(array1[index1], array2[index2], delim.join([path, str(index1)]))
self.__internal_diff__(array1[index1], array2[index2], delim.join([path, str(index1)]))
##
# @brief Try diff two arrays at given path, using optimized LCS algorithm
#
# @param array1 child array in old json
# @param array2 child array in new json
# @param path the path of child array in old json
#
def __internal_array_diff__(self, array1, array2, path):
def haveCompositeSimilarSubkeysByIndex(array1, array2, index1, index2):
return haveCompositeSimilarSubkeys(array1[index1], array2[index2])
def arrayObjectHaveCommonKeysByIndex(array1, array2, index1, index2):
ret = objectHaveCommonKeys(array1[index1], array2[index2])
return ret
def arrayIndexOf(array, target):
for index, item in enumerate(array):
if item == target:
return index
return -1
##
# @brief LCS backtrack method
#
# @param lengthMatrix LCS matrix
# @param array1 first array
# @param array2 second array
# @param index1 index in first array
# @param index2 index in second array
#
# @return common sequence of this tow array and each unique slices.
#
def backtrack(lengthMatrix, array1, array2, index1, index2):
if index1 == 0 and index2 == 0:
return { 'sequence' : [ ], 'indices1' : [ ], 'indices2' : [ ] }
# in both
if index1 > 0 and index2 > 0 and \
haveCompositeSimilarSubkeysByIndex(array1, array2, index1 - 1, index2 - 1):
subsequence = backtrack(lengthMatrix, array1, array2, index1 - 1, index2 - 1)
subsequence['sequence'].append(array1[index1 - 1])
subsequence['indices1'].append(index1 - 1)
subsequence['indices2'].append(index2 - 1)
return subsequence
# in array1
if index2 > 0 and (index1 == 0 or \
lengthMatrix[index1][index2 - 1] >= lengthMatrix[index1 - 1][index2]):
subsequence = backtrack(lengthMatrix, array1, array2, index1, index2 - 1)
return subsequence
# in array2
elif index1 > 0 and (index2 == 0 or \
lengthMatrix[index1][index2 - 1] < lengthMatrix[index1 - 1][index2]):
return backtrack(lengthMatrix, array1, array2, index1 - 1, index2)
##
# @brief LCS algorithm
#
# @param array1 first array
# @param array2 second array
#
# @return LCS matrix
def lengthMatrix(array1, array2):
def max(lhs, rhs):
if lhs > rhs:
return lhs
return rhs
len1 = len(array1)
len2 = len(array2)
# matrix[ll+1][lr+1]
matrix = [[0 for x in range(len2 + 1)] for y in range(len1 + 1)]
for x in range(1, len1 + 1):
for y in range(1, len2 + 1):
if (haveCompositeSimilarSubkeysByIndex(array1, array2, x - 1, y - 1)):
matrix[x][y] = matrix[x - 1][y - 1] + 1
else:
matrix[x][y] = max(matrix[x - 1][y], matrix[x][y - 1])
return matrix
##
# @brief Interface of LCS algorithm
#
# @param ll the first array
# @param rl the second array
#
# @return common sequence of this tow array and each unique slices.
def __internal_lcs__(ll, rl):
matrix = lengthMatrix(ll, rl)
return backtrack(matrix, ll, rl, len(ll), len(rl))
##
# __internal_array_diff__ started!
commonHead = 0
commonTail = 0
len1 = len(array1)
len2 = len(array2)
delim = '/' if path != '/' else ''
# seperate common head, perform diff to similar composite child object.
while commonHead < len1 and commonHead < len2 and \
haveCompositeSimilarSubkeysByIndex(array1, array2, commonHead, commonHead):
self.tryObjectInnerDiff(array1, array2, commonHead, commonHead, path)
commonHead = commonHead + 1
# seperate common tail, perform diff to similar composite child object.
while commonTail + commonHead < len1 and commonTail + commonHead < len2 and \
haveCompositeSimilarSubkeysByIndex(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail):
self.tryObjectInnerDiff(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, path)
commonTail = commonTail + 1
if commonHead + commonTail == len1:
# arrays are identical
if len1 == len2:
return
# keys in array1 all exists(haveCompositeSimilarSubkeysByIndex())\
# in array2 and length of array2 is larger than array1
for index in range(commonHead, len2 - commonTail):
self.result.append({
#'debug' : 'common head & tail pretreatment processing -- only in array2',
'add': delim.join([path, str(index)]),
'value': array2[index],
'details' : 'array-item'
})
return
elif commonHead + commonTail == len2:
for index in range(commonHead, len1 - commonTail):
self.result.append({
#'debug' : 'common head & tail pretreatment processing -- only in array1',
'remove' : delim.join([path, str(index)]),
'value' : array1[index],
'details' : 'array-item'
})
return
# diff is not trivial, find the LCS (Longest Common Subsequence)
lcs = __internal_lcs__(
array1[commonHead: len1 - commonTail],
array2[commonHead: len2 - commonTail]
)
# function: remove
removedItems = []
for index in range(commonHead, len1 - commonTail):
indexOnLcsOfArray1 = arrayIndexOf(lcs['indices1'], index - commonHead)
# not in first LCS-indices
if indexOnLcsOfArray1 < 0:
removedItems.append(index)
# function add or move(update)
for index in range(commonHead, len2 - commonTail):
indexOnLcsOfArray2 = arrayIndexOf(lcs['indices2'], index - commonHead)
# not in second LCS-indices
if indexOnLcsOfArray2 < 0:
# issue #2
# patch: replace --> original: added, try to match with a removed item and register as position move
isMove = False
if len(removedItems) > 0:
for indexOfRemoved in range(0, len(removedItems)):
if arrayObjectHaveCommonKeysByIndex(array1, array2, removedItems[indexOfRemoved], index):
# issue #2 added (with a removement and an add, optimize as an object replacement)
# try to match with a removed item and register as position move
self.tryObjectInnerDiff(array1, array2, removedItems[indexOfRemoved], index, path)
del removedItems[indexOfRemoved]
isMove = True
break;
# issue #28. fix issue of [1,2,3] diff [1,4,3] return one `add` and one `remove`
elif arrayPremitiveHaveSameType(array1[indexOfRemoved], array2[index]):
self.tryObjectInnerDiff(array1, array2, removedItems[indexOfRemoved], index, path)
del removedItems[indexOfRemoved]
isMove = True
break;
# real added
if isMove == False:
self.result.append({
#'debug' : 'not move',
'add' : delim.join([path, str(index)]),
'value' : array2[index],
'details' : 'array-item'
})
else:
# match, in Longest Common Sequence! do inner diff
if lcs['indices1'] != None and lcs['indices2'] != None:
self.tryObjectInnerDiff(array1, array2, \
lcs['indices1'][indexOnLcsOfArray2] + commonHead, \
lcs['indices2'][indexOnLcsOfArray2] + commonHead, \
path)
# issue 2
# after move-judging, it will be the final result
for removedItem in removedItems:
self.result.append({
#'debug:' : 'after issue #2 judging',
'remove' : delim.join([path, str(removedItem)]),
'value' : array1[removedItem],
'details' : 'array-item'
})
##
# @brief handling json array diff
#
# @param old child array in old json
# @param new child array in new json
# @param path the path of the array in old json
#
def __array_diff__(self, old, new, path = '/'):
self.__internal_array_diff__(old, new, path)
##
# @brief handling json object diff
#
# @param old child object element in old json
# @param new child object element in new json
# @param path the path of child object element in old json.
#
def __object_diff__(self, old, new, path = '/'):
def propDiff(key):
oval = old[key] if old.has_key(key) else None
nval = new[key] if new.has_key(key) else None
self.__internal_diff__(oval, nval, delim.join([path, key]))
delim = '/' if path != '/' else ''
for k, v in new.iteritems():
propDiff(k)
for k, v in old.iteritems():
if k in new:
continue
propDiff(k)
##
# @brief Control function of json diff algorithm. \
# It will recurisively call __array_diff__ and __object_diff__
#
# @param old the old json
# @param new the new json
# @param path the path of old json
#
def __internal_diff__(self, old, new, path = '/'):
##
# handle json object element diff
if isinstance(old, dict) and isinstance(new, dict):
self.__object_diff__(old, new, path)
##
# handle json array element diff
elif isinstance(old, list) and isinstance(new, list):
self.__array_diff__(old, new, path)
##
# handle json premitive element diff
else:
if old == None and new == None:
return
# new value is added
if old == None:
self.result.append({
'add' : path,
'value': new
})
# old vlaue has been removed
else:
if new == None:
self.result.append({
'remove': path,
'prev': old
})
# old value has been update into new value
else:
if old != new:
self.result.append({
'replace' : path,
'prev' : old,
'value' : new
})
##
# @brief This is interface of benjamin-jsondiffpatch diff algorithm.
#
# @param old the old json
# @param new the new json
#
# @return diff of this two object
def diff(self, old, new):
self.__internal_diff__(old, new)
return self.result
def _benjamin_jsondiff(old, new):
bjm_jsondiff = BenjaminJsonDiff()
return bjm_jsondiff.diff(old, new)
def diff(local, other):
return _benjamin_jsondiff(local, other)
def print_reduced(diff, pretty=True):
""" Prints JSON diff in reduced format (similar to plain diffs).
"""
for action in diff:
if 'add' in action:
print('+', action['add'], action['value'])
elif 'remove' in action:
print('-', action['remove'], action['prev'])
if __name__ == '__main__':
from sys import argv, stderr
from optparse import OptionParser
from json_diff_patch.printer import print_json
parser = OptionParser()
parser.add_option('-p', '--pretty', dest='pretty', action='store_true',
default=False)
parser.add_option('-j', '--json', dest='json_format', action='store_true',
default=False)
(options, args) = parser.parse_args()
if len(args) < 2:
print('Usage:', argv[0], '[options] local_file other_file', file=stderr)
exit(-1)
try:
with open(args[0]) as f:
local = load(f)
except IOError:
print('Local not found', file=stderr)
exit(-1)
except KeyError:
print('Path to file not specified', file=stderr)
exit(-1)
try:
with open(args[1]) as f:
other = load(f)
except IOError:
print('Other not found', file=stderr)
exit(-1)
except KeyError:
print('Path to other file not specified', file=stderr)
exit(-1)
res = diff(local, other)
if not options.json_format:
print_reduced(res, options.pretty)
else:
print_json(res, "/", options.pretty)
|
797aa5ecd4ed5eec676268daedb38a7d85af9ce9
|
[
"Python"
] | 2 |
Python
|
sandeep-gh/json-diff-patch
|
c0127799b37804507ea544e534facc3a8eae93cc
|
b013d3fbd062e09d1c06098c58bf1a303323fd60
|
refs/heads/master
|
<repo_name>keisuke-kiriyama/AndroidTutorial<file_sep>/BloodPressure/settings.gradle
include ':app'
rootProject.name='Blood Pressure'
<file_sep>/BataPikaEver/settings.gradle
include ':app'
rootProject.name='<NAME>'
<file_sep>/High and Low/settings.gradle
include ':app'
rootProject.name='Hi And Low'
<file_sep>/Out of Business Cards/app/src/main/java/com/example/outofbusinesscards/EditActivity.kt
package com.example.outofbusinesscards
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.preference.PreferenceManager
import kotlinx.android.synthetic.main.activity_edit.*
class EditActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit)
PreferenceManager.getDefaultSharedPreferences(this).apply {
val company = getString("company", "")
val postal = getString("postal", "")
val address = getString("address", "")
val tel = getString("tel", "")
val fax = getString("fax", "")
companyEdit.setText(company)
postalEdit.setText(postal)
addressEdit.setText(address)
telEdit.setText(tel)
faxEdit.setText(fax)
}
saveBtn.setOnClickListener() {
saveData()
finish()
}
cancelBtn.setOnClickListener() {
finish()
}
}
private fun saveData() {
// https://qiita.com/kph7mgb/items/bdaab20ca708df571b46
val pref = PreferenceManager.getDefaultSharedPreferences(this)
val editor = pref.edit()
editor.putString("company", companyEdit.text.toString())
.putString("postal", postalEdit.text.toString())
.putString("address", addressEdit.text.toString())
.putString("tel", telEdit.text.toString())
.putString("fax", faxEdit.text.toString())
.apply()
}
}
<file_sep>/README.md
# AndroidTutorial
- Android学習用Repository
<file_sep>/OurMenu/app/src/main/java/com/example/keisuke_kiriyama/ourmenu/MainActivity.kt
package com.example.keisuke_kiriyama.ourmenu
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mailBtn.setOnClickListener() {
sendMail()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
private fun sendMail () {
val subject = "メールテスト"
val text = "このメールはテスト用のメールです。"
val uri = Uri.fromParts("mailto", "<EMAIL>", null)
val intent = Intent(Intent.ACTION_SENDTO, uri)
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, text)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
}
}
}
|
6a9ba4a9a51c0fa016280e10ed74a983a52ab21f
|
[
"Markdown",
"Kotlin",
"Gradle"
] | 6 |
Gradle
|
keisuke-kiriyama/AndroidTutorial
|
e163c9c7991f25f8b8637e8f07f17b446460d59f
|
019e07bdbb9edbaa99eaadc327455471bc221058
|
refs/heads/master
|
<repo_name>Mottola64/oo-basics-online-web-pt-031119<file_sep>/lib/shoe.rb
class Shoe
attr_accessor :brand, :color, :size, :material, :condition
def initialize(brand)
@brand = brand
end
def cobble
@condition = "new"
puts "Your shoe is as good as new!"
end
end
|
a75be7250ec872a698d39df48a4c9c9b19d48b64
|
[
"Ruby"
] | 1 |
Ruby
|
Mottola64/oo-basics-online-web-pt-031119
|
c68c740098cdc505b87b2464a46970224fd05c3f
|
ed6aa0da5c3d5ec87d7c29917af1da5c0cde6d3b
|
refs/heads/master
|
<repo_name>MiracleBlue/blue-torrent<file_sep>/app/application/controller.js
import Ember from 'ember';
export default Ember.Controller.extend({
nw: Ember.inject.service(),
webtorrent: Ember.inject.service(),
settings: Ember.inject.service(),
actions: {
async addTorrentFile(filePath) {
const readFile = this.get('nw.fileUtil.readTorrentFile');
const file = await readFile(filePath);
console.log(file);
const parsedTorrent = this.get('webtorrent').parse(file);
console.log(parsedTorrent);
const record = this.store.createRecord('torrent', {
name: parsedTorrent.name,
torrentFilePath: filePath,
downloadPath: '/some/download/location'
});
}
}
});
<file_sep>/app/webtorrent/parse-torrent.js
export default window.requireNode && window.requireNode('parse-torrent');
<file_sep>/app/services/nw.js
import Ember from 'ember';
import nwGui from "../nw/gui";
const get = Ember.get;
export default Ember.Service.extend(Ember.Evented, {
fileUtil: get(window, 'process.mainModule.exports.fileUtil'),
gui: nwGui,
nwWindow: Ember.computed("gui.Window", function() {
return this.get("gui").Window.get();
}),
_showDevTools: function() {
this.get("nwWindow").showDevTools();
}.on("init")
});
<file_sep>/app/components/blue-table/row/component.js
import Ember from 'ember';
const {log, info, error, warn} = console;
export default Ember.Component.extend({
tagName: "",
// dynamic properties
selected: false,
expanded: false,
// Computed Properties
columns: Ember.computed("childViews.[]", {
get() {
return this.get("childViews").mapBy("attrs");
}
}),
// Event Handlers
click(event) {
console.log("click event", event);
this.send("expand");
},
_debug: Ember.on("init", "click", function() {
console.log("Hello?");
}),
actions: {
expand() {
console.log("expand");
this.set("expanded", true);
},
collapse() {
this.set("expanded", false);
},
select() {
this.set("selected", true);
},
deselect() {
this.set("selected", false);
}
}
}).reopenClass({
positionalParams: ["row"]
});
<file_sep>/app/components/directory-input/component.js
import Ember from 'ember';
export default Ember.TextArea.extend({
attributeBindings: ["nwdirectory"],
nwdirectory: true
});
<file_sep>/app/webtorrent/service.js
import Ember from 'ember';
import WebTorrent from "./webtorrent";
import ParseTorrent from './parse-torrent';
const {computed, inject} = Ember,
{alias} = computed;
export default Ember.Service.extend({
nw: inject.service("nw"),
settings: inject.service("settings"),
downloadPath: alias("settings.record.downloadPath"),
parse(data) {
return ParseTorrent(data);
},
client: computed({
get() {
return new WebTorrent();
}
}),
torrents: alias("client.torrents"),
addTorrent(file) {
const downloadPath = this.get("downloadPath"),
client = this.get("client");
console.log("addTorrent", {downloadPath, client, file});
client.add(file, {
path: `${downloadPath}/ubuntu`
}, torrent => {
console.log("onTorrent", ...arguments);
});
},
getByName(name) {
const torrents = this.get("torrents");
return torrents.filter(torrent => torrent.name === name);
}
});
<file_sep>/app/settings/service.js
import Ember from 'ember';
const {computed, inject} = Ember,
{alias} = computed;
export default Ember.Service.extend({
store: inject.service("store"),
nw: inject.service("nw"),
fileUtil: alias("nw.fileUtil"),
homePath: alias("nw.fileUtil.homePath"),
readSettingsFile() {
return this.get("fileUtil").readSettings();
},
record: computed({
async get() {
const store = this.get("store");
try {
return await store.find("settings", 1);
}
catch (error) {
const homePath = this.get("homePath");
const record = await store.createRecord("settings", {
downloadPath: `${homePath}/blue-torrent-downloads`
});
return record.save();
}
}
}),
apply() {
this.get("record").save();
},
_setup: Ember.on("init", async function() {
console.log("homePath", this.get("homePath"));
console.log("readSettings", await this.readSettingsFile());
})
});
<file_sep>/app/adapters/filesystem.js
import Ember from 'ember';
import DS from 'ember-data';
/**
* Borrowed from https://github.com/brzpegasus/ember-nw-markdown/blob/master/app/adapters/document.js
*/
var computed = Ember.computed;
var inject = Ember.inject;
var RSVP = Ember.RSVP;
// todo: clean this whole thing up to make more pretty
export default DS.Adapter.extend({
nw: inject.service("nw"),
fileUtil: computed.alias('nw.fileUtil'),
async findAll(store, type, sinceToken) {
const typeKey = type.modelName,
files = await this.get("fileUtil").getAllFiles(typeKey);
return files;
},
findRecord: function(store, type, id) {
const typeKey = type.modelName,
fileName = `${id}.json`,
filePath = `../datastore/${typeKey}/${fileName}`;
var promise = this.get('fileUtil').getRecord(typeKey, id);
return promise.then(function(data) {
return data[typeKey];
});
},
createRecord: function(store, type, snapshot) {
var promise = this.saveRecord(snapshot);
return promise.catch(function(error) {
snapshot.record.set('filename', null);
return RSVP.reject(error);
});
},
updateRecord: function(store, type, snapshot) {
return this.saveRecord(snapshot);
},
saveRecord: function(snapshot) {
console.log("snapshot", snapshot.serialize());
const modelName = snapshot.modelName,
record = snapshot.serialize();
return this.get('fileUtil').createRecord(modelName, record);
}
// todo: make a delete record that is safe-ish
});
<file_sep>/README.md
# Blue-torrent
This is just a pet project to create a simple bit torrent client that doesn't suck, and that works cross-platform.
This may not become anything usable, so please don't download it unless you're a developer that wants to contribute.
It uses Node Webkit (NW) to run in its own window and have access to the host system for file access etc. Please read
the Running / Development instructions.
## Prerequisites
You will need the following things properly installed on your computer.
* [Git](http://git-scm.com/)
* [Node.js](http://nodejs.org/) (with NPM)
* [Bower](http://bower.io/)
* [Ember CLI](http://www.ember-cli.com/)
* [PhantomJS](http://phantomjs.org/)
## Installation
* `git clone https://github.com/MiracleBlue/blue-torrent.git` this repository
* change into the new directory
* `npm install`
* `bower install`
## Running / Development
* `ember nw` - runs in a Webkit instance via NW
### Code Generators
Make use of the many generators for code, try `ember help generate` for more details
### Running Tests
* `ember nw:test`
* `ember nw:test --server`
### Building
* `ember nw:package` (development)
## Further Reading / Useful Links
* [ember.js](http://emberjs.com/)
* [ember-cli](http://www.ember-cli.com/)
* [ember-cli-node-webkit](https://github.com/brzpegasus/ember-cli-nwjs)
* Development Browser Extensions
* [ember inspector for chrome](https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi)
* [ember inspector for firefox](https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/)
<file_sep>/app/components/file-select/component.js
import Ember from 'ember';
export default Ember.Component.extend({
filePath: "",
actions: {
triggerFileSelect() {
const input = this.$(".file-select__input");
input.click();
},
fileSelected() {
console.log("file selected", ...arguments);
const filePath = this.get("filePath"),
inputValue = this.$('input').val();
console.log(inputValue);
this.set('filePath', inputValue);
this.sendAction('select', inputValue);
}
}
});
<file_sep>/app/torrent/adapter.js
import FileSystemAdapter from '../adapters/filesystem';
export default FileSystemAdapter.extend({
});
<file_sep>/app/index/route.js
import Ember from 'ember';
export default Ember.Route.extend({
webtorrent: Ember.inject.service("webtorrent"),
settings: Ember.inject.service("settings"),
_debug: Ember.on("init", function() {
console.log(this.get("settings"));
}),
model() {
// Should get torrents here
return this.store.findAll("torrent");
},
actions: {
addTorrent(torrentRecord) {
const record = torrentRecord;
record.start();
}
}
});
<file_sep>/app/webtorrent/webtorrent.js
export default window.requireNode && window.requireNode('webtorrent');
<file_sep>/app/settings/model.js
import DS from 'ember-data';
const {attr, hasMany, belongsTo} = DS;
export default DS.Model.extend({
downloadPath: attr("string")
});
<file_sep>/app/torrent/model.js
import DS from 'ember-data';
import filesize from "../utils/filesize";
const {attr, hasMany, belongsTo} = DS;
export default DS.Model.extend({
webtorrent: Ember.inject.service("webtorrent"),
nw: Ember.inject.service("nw"),
name: attr("string"),
torrentFilePath: attr("string"),
downloadPath: attr("string"),
isActive: attr("boolean"),
status: attr("string"),
isErrored: attr("boolean"),
error: attr("string"),
size: attr("number"),
downloaded: attr("number"),
uploaded: attr("number"),
seeds: attr("number"),
peers: attr("number"),
ratio: attr("number"),
uploadSpeed: 123,
downloadSpeed: "0 bytes/s",
// todo: Figure out how to make an ETA calculation
eta: function() {
console.log("ETA currently unavailable");
return "Unknown";
}.property("downloadSpeed", "downloaded", "size", "isActive"),
torrentItem: Ember.computed("webtorrent", "torrentFile", {
async get() {
const torrentFile = await this.get("torrentFile");
return this.get("webtorrent.client").get(torrentFile);
}
}),
torrentFile: Ember.computed({
get() {
const fileUtil = this.get("nw.fileUtil"),
torrentFilePath = this.get("torrentFilePath");
return fileUtil.readTorrentFile(torrentFilePath);
}
}),
_setupListener: Ember.on("init", function() {
console.log("Hello");
}),
_observeActiveMeta: Ember.observer("isActive", async function() {
console.log("isActive");
const torrentItem = await this.get("torrentItem");
const logDownloadSpeed = () => this.set("downloadSpeed", torrentItem.swarm.downloadSpeed()::filesize() + "/s");
torrentItem.swarm.on("download", metadata => {
Ember.run.throttle(this, logDownloadSpeed, 300);
});
}),
async start() {
const webtorrent = this.get("webtorrent");
webtorrent.addTorrent(await this.get("torrentFile"));
this.set("isActive", true);
}
});
<file_sep>/public/lib/file.js
var fs = require('fs');
var path = require('path');
var RSVP = require('rsvp');
var wrench = require('wrench');
var glob = require("glob-promise");
var fsJson = require("fs-json")();
var osenv = require("osenv");
var denodeify = RSVP.denodeify;
var readFile = denodeify(fs.readFile);
var fsWriteFile = denodeify(fs.writeFile);
var loadJson = denodeify(fsJson.load);
var fsWriteJson = denodeify(fsJson.save);
var writeFile = function(filePath, data) {
var dirname = path.dirname(filePath);
if (!fs.existsSync(dirname)) {
wrench.mkdirSyncRecursive(dirname, 0x1ff);
}
return fsWriteFile(filePath, data);
};
var writeJson = function(filePath, data) {
var dirname = path.dirname(filePath);
if (!fs.existsSync(dirname)) {
wrench.mkdirSyncRecursive(dirname, 0x1ff);
}
return fsWriteJson(filePath, data);
};
var datastorePath = path.resolve(__dirname, "../datastore/");
// /Users/MiracleBlue/DevelopmentLocal/blue-torrent/public/test-torrents/ubuntu-15.04-server-amd64.iso.torrent
var testTorrentPath = path.resolve(__dirname, "../test-torrents/ubuntu-15.04-server-amd64.iso.torrent");
var settingsRecordPath = path.resolve(datastorePath, "settings/1.json");
// todo: remove this call as this is just for testing!
exports.readTorrentFile = function(torrentPath) {
if (!torrentPath) return console.error("No torrent path was provided");
console.log("readTorrentFile", torrentPath);
return readFile(torrentPath);
};
exports.homePath = osenv.home();
exports.getDownloadPath = path.resolve(osenv.home(), "test-downloads/");
exports.readFile = function(filename) {
var filePath = path.resolve(__dirname, filename);
return loadJson(filePath);
};
exports.getRecord = function(modelName, id) {
var storeDirectory = datastorePath + "/" + modelName;
var filePath = storeDirectory + "/" + id + ".json";
return loadJson(filePath);
};
exports.createRecord = function(modelName, record) {
var storeDirectory = datastorePath + "/" + modelName;
var filePath = storeDirectory + "/" + record.id + ".json";
return writeJson(filePath, record);
};
exports.getAllFiles = function(typeName) {
var storeDirectory = datastorePath + "/" + typeName + "/";
console.log("storeDirectory", storeDirectory);
var files = glob( "*.json", {
cwd: storeDirectory
}).then(function(output) {
return RSVP.all(output.map(function(fileName) {
var filePath = path.resolve(storeDirectory, fileName);
return loadJson(filePath).then(function(file) {
return file[typeName];
});
}));
});
return files;
};
exports.writeFile = function(filename, data) {
return writeFile(filename, data);
};
exports.readSettings = function() {
return loadJson(settingsRecordPath);
};
exports.writeSettings = function(record) {
return writeJson(settingsRecordPath, record);
};
|
d0a79e641e14d836fcea724c3eb60f6a7a39af54
|
[
"JavaScript",
"Markdown"
] | 16 |
JavaScript
|
MiracleBlue/blue-torrent
|
7a745fe01cfe2e08b175695d3ccb932c3dea4855
|
12c49339ba76e98117e1222f856cf8e08dc1a151
|
refs/heads/master
|
<file_sep>// import axios from "axios";
// const createproduct = async data =>
// (await axios.post("http://localhost:44339/api/Create/ProductCreation", data));
// export default createproduct;
// let res = await axios.post('http://httpbin.org/post', payload);<file_sep>import React from 'react';
import { useEffect, useState } from 'react';
import ProductDetails from './ProductDetails';
import Product from './Product';
import ProductDataService from './Api';
import qs from 'qs';
import axios from 'axios';
import {
BrowserRouter as Router,
Route,
Link,
NavLink,
Redirect
} from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
function AddProduct() {
const initailproductdetails = {
ProductCode: 0,
ProductLineID: 0,
ProductName: "",
ProductScale: 0,
ProductVendor: "",
PdtDescription: "",
StoctAvailability: 0,
Price: 0,
MSRP: ""
}
const [product, setProduct] = useState(initailproductdetails);
// const [submitted, setSubmitted] = useState(false);
const handleInput = event => {
//const { name, value } = event.target;
setProduct({ ...product, [event.target.name]: event.target.value });
};
const handleAddProduct = async () => {
debugger;
var prodata = {
ProductCode: product.ProductCode,
ProductLineID: product.ProductLineID,
ProductName: product.ProductName,
ProductScale: product.ProductScale,
ProductVendor: product.ProductVendor,
PdtDescription: product.PdtDescription,
StoctAvailability: product.StoctAvailability,
Price: product.Price,
MSRP: product.MSRP
};
const response = await axios.post("http://localhost:44339/api/Create/ProductCreation", qs.stringify(prodata))
setProduct({
ProductCode: response.prodata.ProductCode,
ProductLineID: response.prodata.ProductLineID,
ProductName: response.prodata.ProductName,
ProductScale: response.prodata.ProductScale,
ProductVendor: response.prodata.ProductVendor,
PdtDescription: response.prodata.PdtDescription,
StoctAvailability: response.prodata.StoctAvailability,
Price: response.prodata.Price,
MSRP: response.prodata.MSRP
});
};
return (
<center>
<div className="col-md-4">
<form >
<div className="form-group">
<label for="exampleFormControlSelect1" className=" col-form-label">Product Code</label>
<div class="col-sm-10"><input
type="number"
className="form-control"
id="ProductCode"
name="ProductCode"
placeholder="ProductCode"
value={product.ProductCode}
onChange={handleInput}
>
</input></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className=" col-form-label">Product LineID</label>
<div class="col-sm-10"><input
type="number"
className="form-control"
id="ProductLineID"
name="ProductLineID"
placeholder="ProductLineID"
value={product.ProductLineID}
onChange={handleInput}
>
</input></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className=" col-form-label">Product Name</label>
<div class="col-sm-10"><input
type="text"
className="form-control"
id="ProductName"
name="ProductName"
placeholder="ProductName"
value={product.ProductName}
onChange={handleInput}
>
</input></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className=" col-form-label">Product Scale</label>
<div class="col-sm-10"><input
type="number"
className="form-control"
id="ProductScale"
name="ProductScale"
placeholder="ProductScale"
value={product.ProductScale}
onChange={handleInput}
/></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className="col-form-label">Product Vendor</label>
<div class="col-sm-10"><input
type="text"
className="form-control"
id="ProductVendor"
name="ProductVendor"
placeholder="ProductVendor"
required
value={product.ProductVendor}
onChange={handleInput}
/></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className=" col-form-label">Product Description</label>
<div class="col-sm-10"><input
type="text"
className="form-control"
id="PdtDescription"
name="PdtDescription"
placeholder="PdtDescription"
value={product.PdtDescription}
onChange={handleInput}
/></div>
</div>
<div className="form-group">
<label for="exampleFormControlSelect1" className="col-form-label">Product StockAvailability</label>
<div class="col-sm-10"><input
type="number"
className="form-control"
id="StoctAvailability"
name="StoctAvailability"
placeholder="StockAvailability"
value={product.StoctAvailability}
onChange={handleInput}
/></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className="col-form-label">Product Price</label>
<div class="col-sm-10"><input
type="number"
className="form-control"
id="Price"
name="Price"
placeholder="Price"
value={product.Price}
onChange={handleInput}
/></div>
</div>
<div className="form-group ">
<label for="exampleFormControlSelect1" className="col-form-label">Product MSRP</label>
<div class="col-sm-10"><input
type="text"
className="form-control"
id="MSRP"
name="MSRP"
placeholder="MSRP"
value={product.MSRP}
onChange={handleInput}
/></div>
</div>
<button className="btn btn-primary" onClick={handleAddProduct} className="btn btn-success">
Submit
</button>
</form>
</div>
</center>
);
}
export default AddProduct;
// const [tutorial, setTutorial] = useState(initialTutorialState);
// const handleAddProduct = () => {
// // debugger;
// var data = {
// ProductCode: product.ProductCode,
// ProductLineID: product.ProductLineID,
// ProductName: product.ProductName,
// ProductScale: product.ProductScale,
// ProductVendor: product.ProductVendor,
// PdtDescription: product.PdtDescription,
// StoctAvailability: product.StoctAvailability,
// Price: product.Price,
// MSRP: product.MSRP
// };
// sendPostRequest(data);
// }
// const sendPostRequest = async () => {
// try {
// const resp = await axios.post('https://jsonplaceholder.typicode.com/posts', newPost);
// console.log(resp.data);
// } catch (err) {
// // Handle Error Here
// console.error(err);
// }
// };
//const axios = require('axios').default;
// useEffect(() => {
// const setsData = async () => {
// const result = await axios.get('http://localhost:44339/api/GetProduct/All');
// setData(result.data);
// };
// setsData();
// }, []);
// const newTutorial = () => {
// setTutorial(initialTutorialState);
// setSubmitted(false);
// };
// const create = data => {
// return http.post(apiurl, data);
// };
// useEffect(() => {
// const setsData = async () => {
// const result = await axios.post();
// setData(result.data);
// };
// setsData();
// }, [value]);
// preventDefault() method cancels the event if it is cancelable
// <select onchange="myFunction()"></select>:
// Execute a JavaScript when a user changes the selected option of a <select> element:
{/* <form onsubmit="myFunction()"></form>:
Execute a JavaScript when a form is submitted */}
<file_sep>
import useAxios from 'axios-hooks';
import './Product.css';
import ProductDetails from './ProductDetails';
// [{ data, loading, error, response }, execute, manualCancel]
// data - The success response data property (for convenient access).
// loading - True if the request is in progress, otherwise False.
// error - The error value
// response - The whole success response object.
// execute([config[, options]]) - A function to execute the request manually,
// manualCancel() - A function to cancel outstanding requests manually
function Product() {
const [{ data, loading, error }, refetch] = useAxios(
'http://localhost:44339/api/GetProduct/All'
)
if (loading) return <p>Loading...</p>
if (error) return <p>Error!</p>
return (
<div>
{/* <button onClick={refetch}>refetch</button> */}
{/* To print the JSON result
stringyfy->COnverts the json objects/values to json string
<pre>{JSON.stringify(data, null, 2)}</pre> */}
{/* To list the products
<ul>
{data.map(person => <li>{person.ProductName}</li>)}
</ul>
*/}
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Product ID</th>
<th>Product Brand</th>
<th>Product Details</th>
</tr>
</thead>
<tbody>
{(data.map((droplet) => {
return (
<tr>
<td>{droplet.ProductCode}</td>
<td>{droplet.ProductName}</td>
<td>{droplet.ProductID}</td>
<td>{droplet.Brand}</td>
<td><button onClick={ProductDetails}>More Details</button></td>
</tr>
)
}))}
</tbody>
</table>
</div>
);
}
// import React, { useState, useEffect } from 'react';
// import axios from 'axios';
// import Home from './Home';
// import {
// BrowserRouter as Router,
// Route,
// Link,
// NavLink
// } from 'react-router-dom';
// function Product() {
// const [data, setData] = useState([]);
// useEffect(() => {
// const setData = async () => {
// const result = await axios.get('http://localhost:44339/api/GetProduct/All');
// setData(result.data);
// }
// setData();
// }, []);
// // function Product({ }) {
// // const [product, setProduct] = useState({ pro: [] });
// // useEffect(() => {
// // // By moving this function inside the effect, we can clearly see the values it uses.
// // async function fetchProduct() {
// // const response = await fetch('http://localhost:44339/api/GetProduct/All');
// // const json = await response.json();
// // setProduct(json);
// // }
// // fetchProduct();
// // }, []); // ✅ Valid because our effect only uses productId
// // // ...
// return (
// <ul>
// { product.map(person => <li>{person.ProductName}</li>)}
// </ul>
// <div>
// <table>
// <thead>
// <tr>
// <th>Id</th>
// <th>Name</th>
// <th>Brand</th>
// <th>Price</th>
// <th>StockAvailability</th>
// </tr>
// </thead>
// <tbody>
// {(data.pro.map((droplet) => {
// return (
// <tr>
// <td>{droplet.ProductID}</td>
// <td>{droplet.ProductName}</td>
// <td>{droplet.Brand}</td>
// <td>{droplet.price}</td>
// <td>{droplet.StockAvailability}</td>
// </tr>
// )
// }))}
// </tbody>
// </table>
// </div>
// );
// }
// const fetchURL = "http://localhost:44339/api/GetProduct/All";
// const getItems = () => fetch(fetchURL).then(res => res.json());
// function Product() {
// const [items, setItems] = useState();
// useEffect(() => {
// getItems().then(data => setItems(data));
// }, []);
// return (
// <div>
// {items.map(item => (
// <div key={item.ProductCode}>{item.ProductName}</div>
// ))}
// </div>
// );
// }
export default Product;<file_sep>import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Home from './Home';
import ProductDetails from './ProductDetails';
import {
BrowserRouter as Router,
Route,
Link,
NavLink
} from 'react-router-dom';
function Customer() {
const [data, setData] = useState([]);
//asyn--->when you're defining a function that contains asynchronous code
//await--->indicates that you want to resolve the Promise
useEffect(() => {
const setsData = async () => {
const result = await axios.get('http://localhost:44339/api/GetProduct/All');
setData(result.data);
};
setsData();
}, []);
return (
<div>
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Product ID</th>
<th>Product Brand</th>
<th>Product Details</th>
</tr>
</thead>
<tbody>
{(data.map((pro) => {
return (
<tr>
<td>{pro.ProductCode}</td>
<td>{pro.ProductName}</td>
<td>{pro.ProductID}</td>
<td>{pro.Brand}</td>
<td><Link to={"/details/" + pro.ProductCode}>More Details</Link></td>
{/* <td><Link to={{ pathname: `/more/${pro.ProductCode}` }}>More Detail</Link></td> */}
{/* <td><Link to="ProductDetails" params={{ id: pro.ProductID }}>More Details</Link></td> */}
</tr>
)
}))}
</tbody>
</table>
</div >
);
}
export default Customer;<file_sep>import React from 'react';
import { useEffect, useState } from 'react';
import ProductDetails from './ProductDetails';
import Product from './Product';
import ProductDataService from './Api';
import qs from 'qs';
import axios from 'axios';
import {
BrowserRouter as Router
} from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
const AddProduct = props => {
let code = props.match.params.id;
const initailproductdetails =
{
Code: 0,
ProductName: "",
VendorName: ""
}
const [products, setProduct] = useState(initailproductdetails);
// const [submitted, setSubmitted] = useState(false);
const handleInput = (event) => {
//const { name, value } = event.target;
setProduct({ ...products, [event.target.name]: event.target.value });
};
const handleUpdate = async () => {
debugger;
//const axiosconfig = JSON.stringify({ headers: { "Content-Type": "application/json" } });
var prodata = {
Code: 11,
ProductName: products.ProductName,
VendorName: products.VendorName
};
const response = await axios.put('http://localhost:44339/api/Update/product', qs.stringify(prodata));
// setProduct({
// Code: response.prodata.Code,
// ProductName: response.prodata.ProductName,
// VendorName: response.prodata.VendorName
// });
};
return (
<center>
<div className="col-md-4">
<form >
<div className="form-group">
<label htmlFor="exampleFormControlSelect1" className=" col-form-label">Product Code</label>
<div className="col-sm-10"><input
type="number"
className="form-control"
id="Code"
name="Code"
placeholder="enter above 11"
value={products.Code}
onChange={handleInput}
>
</input></div>
</div>
<div className="form-group ">
<label htmlFor="exampleFormControlSelect1" className=" col-form-label">Product Name</label>
<div className="col-sm-10"><input
type="text"
className="form-control"
id="ProductName"
name="ProductName"
placeholder="ProductName"
value={products.ProductName}
onChange={handleInput}
>
</input></div>
</div>
<div className="form-group ">
<label htmlFor="exampleFormControlSelect1" className="col-form-label">Product Vendor</label>
<div className="col-sm-10"><input
type="text"
className="form-control"
id="VendorName"
name="VendorName"
placeholder="VendorName"
required
value={products.VendorName}
onChange={handleInput}
/></div>
</div>
<button className="btn btn-success" onClick={handleUpdate} >
Submit
</button>
</form>
</div>
</center>
);
}
export default AddProduct;
<file_sep>
import React from 'react';
import { useEffect, useState } from 'react';
import ProductDetails from './ProductDetails';
import axios from 'axios';
import {
BrowserRouter as Router,
Route,
Link,
NavLink
} from 'react-router-dom';
function Home() {
const [data, setData] = useState([]);
const [value, setvalue] = useState(1);
// useEffect(() => {
// const setsData = async () => {
// const result = await axios.get('http://localhost:44339/api/ProductName?id=' + value);
// setData(result.data);
// };
// setsData();
// }, [value]);
return (
<div>
<div><center><NavLink to="/AddProduct" >Add Products</NavLink>
</center>
</div>
<div><center><NavLink to="/AddOrder" >Add Orders</NavLink>
</center>
</div></div>
);
}
export default Home;<file_sep>import React from 'react';
import ProductDetails from './ProductDetails';
import axios from 'axios';
export default class Order extends React.Component {
state = {
persons: []
}
componentDidMount() {
// var config = {
// headers: {'Access-Control-Allow-Origin': '*'}
// };
//axios.get('http://localhost/44339' + board + '/api/GetProduct/All', config)
axios.get(`http://localhost:44339/api/GetOrder/All`)
// headers: {
// 'Access-Control-Allow-Origin': 'http://localhost:44339/api/GetProduct/All',
// },
// proxy: {
// host: '192.168.43.1',
// port: 44339
// }
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<div>
<table>
<thead>
<tr>
<th>Order ID</th>
<th>Customer ID</th>
<th>Order Date</th>
<th>Comments</th>
<th>Order Details</th>
</tr>
</thead>
<tbody>
{(this.state.persons.map((droplet) => {
return (
<tr>
<td>{droplet.OrderID}</td>
<td>{droplet.CustomerID}</td>
<td>{droplet.OrderDate}</td>
<td>{droplet.Comments}</td>
<td><button onClick={ProductDetails}>More Details</button></td>
</tr>
)
}))}
</tbody>
</table>
</div>
)
}
}<file_sep>import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Home from './Home';
import ProductDetails from './ProductDetails';
import {
BrowserRouter as Router,
Route,
Link,
NavLink
} from 'react-router-dom';
function Customer() {
const [data, setData] = useState([]);
//asyn--->when you're defining a function that contains asynchronous code
//await--->indicates that you want to resolve the Promise
useEffect(() => {
const setsData = async () => {
const result = await axios.get('http://localhost:44339/api/GetProduct/All');
setData(result.data);
};
setsData();
}, []);
return (
<div>
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Product ID</th>
<th>Product Brand</th>
<th>Product Details</th>
</tr>
</thead>
<tbody>
{(data.map((pro) => {
return (
<tr>
<td>{pro.ProductCode}</td>
<td>{pro.ProductName}</td>
<td>{pro.ProductID}</td>
<td>{pro.Brand}</td>
<td><button onClick={ProductDetails}>More Details</button></td>
</tr>
)
}))}
</tbody>
</table>
</div>
);
}
export default Customer;
// import React from 'react';
// import axios from 'axios';
// export default class PersonList extends React.Component {
// state = {
// name: '',
// }
// handleChange = event => {
// this.setState({ name: event.target.value });
// }
// handleSubmit = event => {
// event.preventDefault();
// const user = {
// name: this.state.name
// };
// axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
// .then(res => {
// console.log(res);
// console.log(res.data);
// })
// }
// render() {
// return (
// <div>
// <form onSubmit={this.handleSubmit}>
// <label>
// Person Name:
// <input type="text" name="name" onChange={this.handleChange} />
// </label>
// <button type="submit">Add</button>
// </form>
// </div>
// )
// }
// }
// import React, { useEffect, useState } from 'react';
// import './App.css';
// function AppHook() {
// const [appState, setAppState] = useState({
// loading: false,
// repos: null,
// });
// useEffect(() => {
// setAppState({ loading: true });
// const apiUrl = 'https://api.github.com/users/hacktivist123/repos';
// axios.get(apiUrl).then((repos) => {
// const allRepos = repos.data;
// setAppState({ loading: false, repos: allRepos });
// });
// }, [setAppState]);
// return (
// <div className='App'>
// <div className='container'>
// <h1>My Repositories</h1>
// </div>
// <div className='repo-container'>
// </div>
// <footer>
// <div className='footer'>
// </div>
// </footer>
// </div>
// );
// }
// export default AppHook;
// import React from 'react';
// import axios from 'axios';
// var http = require('http');
// http.createServer(function (request, response) {
// response.writeHead(200, {
// 'Content-Type': 'text/plain',
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
// });
// response.end('Hello World\n');
// }).listen(3000);
// import React, { useState } from "react";
// import axios from "axios";
// import { Button, Container } from "react-bootstrap";
// function AppHook() {
// const url = "http://localhost:44339/api/Create/ProductCreation";
// const [data, setdata] = useState({
// Code: "",
// ProductlineID: "",
// Name: "",
// Scale: "",
// Vendor: "",
// PdtDescription: "",
// QtyInStock: "",
// BuyPrice: "",
// MSRP: "",
// });
// function submit(e) {
// e.preventDefault();
// axios
// .post(url, {
// Code: data.Code,
// ProductlineID: data.Code,
// Name: data.Name,
// Scale: data.Scale,
// Vendor: data.Vendor,
// PdtDescription: data.PdtDescription,
// QtyInStock: data.QtyInStock,
// BuyPrice: data.BuyPrice,
// MSRP: data.MSRP,
// })
// .then((res) => {
// console.log(res.data);
// });
// }
// function handle(e) {
// const newdata = { ...data };
// newdata[e.target.id] = e.target.value;
// setdata(newdata);
// console.log(newdata);
// }
// return (
// <div>
// <h1>ADD PRODUCT</h1>
// <Container>
// <form onSubmit={(e) => submit(e)}>
// <div className="form-group">
// <input
// onChange={(e) => handle(e)}
// id="Code"
// value={data.Code}
// className="form-control"
// placeholder="Code"
// type="text"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="ProductlineID"
// value={data.ProductlineID}
// className="form-control"
// placeholder="ProductlineID"
// type="number"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="Name"
// value={data.Name}
// className="form-control"
// placeholder="Name"
// type="text"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="Scale"
// value={data.Scale}
// className="form-control"
// placeholder="Scale"
// type="number"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="Vendor"
// value={data.Vendor}
// className="form-control"
// placeholder="Vendor"
// type="text"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="PdtDescription"
// value={data.PdtDescription}
// className="form-control"
// placeholder="PdtDescription"
// type="text"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="QtyInStock"
// value={data.QtyInStock}
// className="form-control"
// placeholder="QtyInStock"
// type="number"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="BuyPrice"
// value={data.BuyPrice}
// className="form-control"
// placeholder="BuyPrice"
// type="number"
// ></input>
// <input
// onChange={(e) => handle(e)}
// id="MSRP"
// value={data.MSRP}
// className="form-control"
// placeholder="MSRP"
// type="text"
// ></input>
// <button type="button" className="btn btn-primary">
// Submit
// </button>
// </div>
// </form>
// </Container>
// </div>
// );
// }
// export default AppHook;
<file_sep>import logo from './logo.svg';
import './App.css';
import {
BrowserRouter as Router,
Route, Switch,
Link,
} from 'react-router-dom';
import Header from './Components/Header';
import Home from './Components/Home';
import Product from './Components/Product';
import Order from './Components/Order';
import NotFound from './Components/Notfound';
import Customer from './Components/ProductList';
import AddProduct from './Components/AddProduct';
import AddOrder from './Components/AddOrder';
import AppHook from './Components/AppHook';
import ProductDetails from './Components/ProductDetails';
import Updateproduct from './Components/Updateproduct';
import UpdateProductaxios from './Components/UpdateProductaxios';
function App() {
return (
<Router>
<div>
<Header />
<Switch>
<Route path="/Home" component={Home} />
<Route path="/Product" component={Product} />
<Route path="/Order" component={Order} />
<Route path="/Customer" component={Customer} />
<Route path="/AddProduct" component={AddProduct} />
<Route path="/AddOrder" component={AddOrder} />
<Route exact path="/details/:code" component={ProductDetails} />
<Route exact path="/to/:id" component={Updateproduct} />
<Route path="/update" component={UpdateProductaxios} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
}
export default App;
<file_sep>// import React from 'react';
// import { useEffect, useState } from 'react';
// import ProductDetails from './ProductDetails';
// import Product from './Product';
// import ProductDataService from './Api';
// import qs from 'qs';
// import axios from 'axios';
// import {
// BrowserRouter as Router
// } from 'react-router-dom';
// import 'bootstrap/dist/css/bootstrap.min.css';
// const UpdateProductaxios = props => {
// let code = props.match.params.id;
// const initailproductdetails =
// {
// Code: 0,
// ProductName: "",
// VendorName: ""
// }
// const [products, setProduct] = useState(initailproductdetails);
// useEffect(() => {
// var prodata = {
// Code: products.Code,
// ProductName: products.ProductName,
// VendorName: products.VendorName
// };
// // PUT request using axios inside useEffect React hook
// axios.put('https://reqres.in/api/articles/1', prodata)
// .then(response => setUpdatedAt(response.data.updatedAt));
// // empty dependency array means this effect will only run once (like componentDidMount in classes)
// }, []);
// import React from 'react';
// import { useEffect, useState } from 'react';
// import ProductDetails from './ProductDetails';
// import Product from './Product';
// import ProductDataService from './Api';
// import qs from 'qs';
// import axios from 'axios';
// import {
// BrowserRouter as Router,
// Route,
// Link,
// NavLink,
// Redirect
// } from 'react-router-dom';
// import 'bootstrap/dist/css/bootstrap.min.css';
// function UpdateProductaxios() {
// const [updatedAt, setUpdatedAt] = useState(null);
// useEffect(() => {
// debugger;
// // PUT request using axios inside useEffect React hook
// const article =
// {
// "ID": 4101,
// "Status": 987,
// "Comments": "test customer"
// };
// axios.put('http://localhost:44339/api/Update/order', article)
// .then(response => setUpdatedAt(response.data.updatedAt));
// // empty dependency array means this effect will only run once (like componentDidMount in classes)
// }, []);
// return (
// <div className="card text-center m-3">
// <h5 className="card-header">PUT Request with React Hooks</h5>
// <div className="card-body">
// Returned Update Date: {updatedAt}
// </div>
// </div>
// );
// }
// export default UpdateProductaxios;
import React from 'react';
import axios from 'axios';
class UpdateProductaxios extends React.Component {
constructor(props) {
super(props);
this.state = {
updatedAt: null,
errorMessage: null
};
}
componentDidMount() {
// PUT request using axios with error handling
const article = {
"ID": 4101,
"Status": 987,
"Comments": "test customer"
};
axios.put('http://localhost:44339/api/Update/order', article)
.then(response => this.setState({ updatedAt: response.data.updatedAt }))
.catch(error => {
this.setState({ errorMessage: error.message });
console.error('There was an error!', error);
});
}
render() {
const { errorMessage } = this.state;
return (
<div className="card text-center m-3">
<h5 className="card-header">PUT Request with Error Handling</h5>
<div className="card-body">
Error: {errorMessage}
</div>
</div>
);
}
}
export default UpdateProductaxios;
|
13ce63d07ad59f1fd8ef784f04dc20f21cf98d5c
|
[
"JavaScript"
] | 10 |
JavaScript
|
GayathriSivaKTS/React-product_order
|
5465dd65b28723fe617a669861799d7b28203ee3
|
b3182008ef838b1d60cb6610236d8aa90a1ed937
|
refs/heads/master
|
<file_sep>#include <vector>
#include <queue>
using namespace std;
class ParPtrTree {
private:
vector<int> parents; // parent pointer vector
vector<int> weights; // weights for weighted union
public:
// constructor
ParPtrTree(size_t size) {
parents.resize(size); //create parents vector
fill(parents.begin(), parents.end(), -1); // each node is its own root to start
weights.resize(size);
fill(weights.begin(), weights.end(), 1);// set all base weights to 1
}
// Return the root of a given node with path compression
// recursive algorithm that makes all ancestors of the current node
// point to the root
int FIND(int node) {
if (parents[node] == -1) return node;
parents[node] = FIND(parents[node]);
return parents[node];
}
// Merge two subtrees if they are different
void UNION(int node1, int node2) {
int root1 = FIND(node1);
int root2 = FIND(node2);
// MERGE two trees
if (root1 != root2) {
if (weights[root1] < weights[root2]) {
parents[root1] = root2;
weights[root2] += weights[root1];
}
else {
parents[root2] = root1;
weights[root1] += weights[root2];
}
}
}
string toString() {
string nodes = "nodes:\t";
string prts = "parents:\t";
for (int i=0; i < this->parents.size(); i++) {
prts += to_string(this->parents[i]) + '\t';
nodes += " \t " + to_string(i);
}
return prts + "\n" + nodes;
}
};
struct Edge
{
int src, dest, weight;
// for min priority queue
bool operator<(const Edge &other) const {
return this->weight > other.weight;
}
};
struct Graph
{
// V -> Number of vertices, E -> Number of edges
int V, E;
// graph is stored in a min heap priority_queue
// Kruskal algo requires working with edges with smallest to highest weight
priority_queue<Edge, vector<Edge> > edges;
// constructor
Graph(int v, int e) {
V = v;
E = e;
}
void addEdge(int u, int v, int w) {
edges.push({u, v, w});
}
};
<file_sep>#include <iostream>
#include <fstream>
#include <vector>
#include <random>
using namespace std;
void generateRandomNumbers(vector<int> &rands, int start, int end) {
std::ios::sync_with_stdio(false);
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<> dis(start, end);
generate(rands.begin(), rands.end(), bind(dis, ref(mt)));
}
int main(){
ofstream outFile("randNum.file");
vector<int> test(100), hundredK(100000), fivehundredK(500000), million(1000000);
generateRandomNumbers(test, 0, 20);
for (auto i = test.begin(); i != test.end(); ++i)
outFile << *i << endl;
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<utility>
using namespace std;
const int MAX = 1e4 + 5;
const int oo = 1e9 + 5;
int n, m, q, s;
int u, v, w, e, t;
vector<pair<int, int>> a[MAX];
priority_queue<pair<int, int>> pq;
int dis[MAX];
void answer(){
pq.push({0, s});
fill(dis, dis + n, oo);
dis[s] = 0;
while((int) pq.size() > 0) {
auto p = pq.top();
pq.pop();
if(abs(p.first) == dis[p.second]) {
for(auto v : a[p.second]) {
if(dis[p.second] + v.second < dis[v.first]) {
dis[v.first] = dis[p.second] + abs(v.second);
pq.push({-dis[v.first], v.first});
}
}
}
}
}
void kattis(){
ios::sync_with_stdio(false);
cin.tie(0);
while(cin >> n >> m >> q >> s, n || m || q || s) {
if(t++) {
cout << "\n";
}
fill(a, a + n, vector<pair<int, int>>());
for(int i = 0; i < m; i++) {
cin >> u >> v >> w;
a[u].push_back({v, w});
}
answer();
for(int i = 0; i < q; i++) {
cin >> e;
cout << (dis[e] == oo ? "Impossible" : to_string(dis[e])) << "\n";
}
}
}
void test(){
int a =1;
}
int main(int argc, char* argv[]) {
if (argc > 1 && strncmp(argv[1], "test", 4) == 0)
test();
else
kattis();
return 0;
}
<file_sep>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int i, N,M,cd;
while( cin >>N>>M && N!=0 && M!=0 )
{
vector<int> ns;
vector<int>::iterator it;
for ( i=0; i<(N+M);i++ )
{
cin >> cd;
ns.push_back(cd);
}
sort(ns.begin(), ns.end());
it = unique(ns.begin(), ns.end());
cout << distance(it, ns.end());
}
return 0;
} <file_sep>#include <iostream>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <string>
#include "class.h"
using namespace std;
using iPair = pair<int, int>;
int KruskalMST(Graph& graph, vector<iPair> & MST)
{
std::ios::sync_with_stdio(false);
if (graph.E == 0)
return 0;
int numMST = graph.V; // initially V disjoint classes
ParPtrTree unionfind(graph.V);
int weight = 0;
while (numMST > 1 && !graph.edges.empty())
{
// pick the smallest edge
Edge edge = graph.edges.top();
graph.edges.pop();
int x = unionfind.FIND(edge.src); // root of src
int y = unionfind.FIND(edge.dest); // root of dest
// if src and dest nodes are in different sets
if (x != y)
{
int u = edge.src;
int v = edge.dest;
// add weight
weight += edge.weight;
// the ordering is not required, but...
if (u > v) swap(u, v);
// add u->v edge to MST
MST.push_back({u, v});
// combine equiv classes
unionfind.UNION(u, v);
numMST--; // one less MST
}
}
return weight;
}
vector<string> answer(Graph& graph){
vector<string> ans;
vector<iPair> MST;
ans.push_back( to_string(KruskalMST(graph, MST)));
sort(MST.begin(), MST.end());
for(auto &p:MST)
ans.push_back( to_string(p.first) + ' ' + to_string(p.second));
return ans;
}
void test() {
Graph test1( 5, 5 ), test2( 5, 3 ), test3( 2, 2 );
test1.addEdge(0,1,4); test1.addEdge(1,3,4); test1.addEdge(1,2,4);
test1.addEdge(2,3,4); test1.addEdge(3,4,4);
test2.addEdge(1,2,3); test2.addEdge(2,3,4); test2.addEdge(3,1,5);
test3.addEdge(0,1,3);
vector<string> assert1{ "16", "0 1", "1 3", "2 3", "3 4" };
vector<string> assert2{ "7", "1 2", "2 3" };
vector<string> assert3{ "3", "0 1" };
assert( answer(test1) == assert1 );
assert( answer(test2) == assert2 );
assert( answer(test3) == assert3 );
}
void kattis() {
int n, m, u, v, w, wt;
while( cin >> n >> m && n>0 ) {
Graph graph(n, m);
for ( int i = 0; i < m && cin >> u >> v >> w; i++ )
graph.addEdge(u, v, w);
if ( m != 0 ) {
vector<string> ans = answer(graph);
for (auto i = ans.begin(); i != ans.end(); ++i) cout << *i << endl;
}
}
cout << "Impossible" << endl;
}
int main( int argc, char* argv[] ) {
if( argc > 1 && strncmp(argv[1], "test", 4) == 0 )
test();
else
kattis();
return 0;
}
//cat minspantree.in | ./a.out | diff - minspantree.ans
<file_sep># CS3-skajiwara
## Introduction to Algorithms
I worked on many Kattis Problems listed below.
### Falling Apart
- solved using vector
- solution accepted 50 points
- 3 test case 30 points
- screenshot 10 points
### Babelfish
- solved using unoredered_map
- solution accepted 50 points
- 3 test case 30 points
- screenshot 10 points
### CD
- solved using vector
- solution accepted 50 points
- 3 test case 30 point
- screenshot 10 points
### Putovanje
- solved using vector and iterator head and current
- solution accepted 50 points
- 3 test case 30 points
- screenshot 10 points
### Icpctutorial
- solved using vector
- solution accepted 50 points
- 3 test case 30 points
- screenshot 10 points
### BST
- I DIDN'T DO IT
### SSSP
- solved using
- solution accepted 50 points
- 3 test case 30 points
- screenshot 10 points
### Minimum Spinning Tree
- solved using Kruskal MST
- solution not accepted accepted
- 3 test case 30 points
- screenshot one of the test cases didn't pass
### Final Project
- can generate 100k, 500k, 1m 5 points
- All sorting methods working 45 points
- Run 10 times 15 points
- searching methods working except BST 10/15 points
- I didn't sort in order
- No bonus
<file_sep>#include <iostream>
#include <string>
using namespace std;
int main()
{
bool state = true;
string word, meaning;
while(state)
{
getline(cin, word)
if (!word.empty()||!meaning.empty())
cout << word << " " << meaning << endl;
else
cout << "empty" << endl;
}
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
#define MAX 5000;
// Binary Tree - ADT
class BinaryTree {
// vector to store binary tree data of char types
private:
vector<char> bt;
size_t count;
// meta data
private: int root, size, max_size;
private: void inorder(int root) {
if (root >= this->bt.size() || this->bt[root] == '\0') // base case
return;
// inorder left-subtree
inorder(2*root+1);
// visit the node
cout << this->bt[root] << " ";
// inorder right-subtree
inorder(2*root+2);
}
private: void mirror(int node) {
if (this->bt[node] == '\0')
return;
int left = 2 * node + 1;
int right = 2 * node + 2;
mirror(left); // left substree
mirror(right); // right subtree
// swap the left/right nodes
swap(this->bt[left], this->bt[right]);
}
public: BinaryTree(int max_size) {
this->root = 0;
this->size = 0;
this->bt.resize(max_size);
this->max_size = max_size;
// initialize bt with \0 null character
fill(this->bt.begin(), this->bt.end(), '\0');
}
public:
int getSize() { return this->size; }
int getMaxSize() { return this->max_size; }
void updateRoot(char data) {
if (bt[this->root] == '\0')
this->size++;
bt[this->root] = data;
}
void insertNode(char data) { // left to right level by level
if (this->size == this->max_size) {
cout << "Binary Tree is Full!" << endl;
return;
}
bt[size++] = data;
}
void updateLeftNode(int parent, char data) {
int leftChild = 2 * parent + 1;
if (leftChild >= this->max_size || this->bt[parent] == '\0')
cout << "parent index " << parent << " does NOT exist!";
else {
if (bt[leftChild] == '\0')
size++;
bt[leftChild] = data;
}
}
void updateRightNode(int parent, char data) {
int rightChild = 2 * parent + 2;
if (rightChild >= this->max_size || this->bt[parent] == '\0')
cout << "parent index " << parent << " does NOT exist!";
else {
if (bt[rightChild] == '\0')
size++;
bt[rightChild] = data;
}
}
// print all nodes level by level
void print(ofstream& outf) const {
for(auto ch: this->bt)
if (ch == '\0') cout << "- ";
else cout << ch << " ";
cout << endl;
}
// printInorder traversal
void printInorder() {
inorder(0);
}
// FIXME: Write printPreorder traversal function
// FIXME: Write printPostorder traversal function
/*
Changes the tree into its mirror image.
So the tree...
4
/ \
2 5
/ \
1 3
is changed to...
4
/ \
5 2
/ \
3 1https://d2l.coloradomesa.edu/d2l/le/content/176833/Home?itemIdentifier=D2L.LE.Content.ContentObject.ModuleCO-2586145
Uses a recursive helper that recurs over the tree,
swapping the left/right pointers.
*/
void mirror() {
mirror(this->root); // call private mirror
}
};
int main()
{
ifstream inf("data.in");
ofstream outf("answer.ot");
BinaryTree test(10);
test.updateRoot('A');
char temp;
while(!inf.eof()){
inf >> temp;
test.insertNode(temp);
}
test.print(outf);
return 0;
}
<file_sep>#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cassert>
#include <string>
using namespace std;
void get_num(int &num)
{
cin >> num;
cin.ignore();
}
void get_line(vector<int> &vect, int N)
{
string temp;
getline (cin, temp);
istringstream iss(temp);
int sub=0;
for(int i=0; i<N; i++)
{
iss >> sub;
vect.push_back(sub);
}
}
void sort_vector(vector<int> &vect)
{
sort(vect.begin(), vect.end());
}
string falling_apart(int &N, int A, int B, vector<int>& V)
{
sort_vector(V);
for(int i=0; i<N; i++)
{
if (i%2 == 0)
{
A += V.back();
}
else
{
B += V.back();
}
V.pop_back();
}
return to_string(A) + " " + to_string(B);
}
void test()
{
int Alice = 0;
int Bob = 0;
int test1[] = { 5, 2, 4, 5, 3 };
int test2[] = { 3, 100 };
int test3[] = { 2, 2, 2, 2 };
int sizes[] = {5, 2, 4};
vector<int> test_vect1 ( test1, test1 + sizes[0] );
assert(falling_apart( sizes[0], Alice, Bob, test_vect1) == "11 8" );
vector<int> test_vect2 ( test2, test2 + sizes[1] );
assert(falling_apart( sizes[1], Alice, Bob, test_vect2 ) == "100 3" );
vector<int> test_vect3 ( test3, test3 + sizes[2] );
assert(falling_apart( sizes[2], Alice, Bob, test_vect3 ) == "4 4");
cout << "all test cases passed!\n";
}
void kattis()
{
int num = 0;
int Alice = 0;
int Bob = 0;
vector<int> vect;
get_num(num);
get_line(vect, num);
cout << falling_apart( num, Alice, Bob, vect );
}
int main(int argc, char *argv[])
{
if (argc > 1 && strncmp(argv[1], "test", 4) == 0)
{
test();
}
else
{
kattis();
}
return 0;
}
<file_sep>#include <iostream>
#include <unordered_map>
#include <utility>
#include <string>
#include <sstream>
#include <cassert>
#include <cstring>
#include <time.h>
using namespace std;
string answer( unordered_map<string, string> &dict, const string word )
{
if ( dict.count(word) == 1 )
return dict[ word ];
else
return "eh";
}
void test()
{
unordered_map<string, string> test = {{"Sune", "Shin"},
{"Atama", "Head"}, {"Onaka", "Stomach"}, {"Ashi", "Legs"},
{"Kusa", "Weed"}, {"Shippo", "Tail"}, {"Kitanai", "Dirty"}};
assert(answer(test, "Shippo") == "Tail");
assert(answer(test, "Onaka") == "Stomach");
assert(answer(test, "Suhydfjhasjbhdhjane") == "eh");
cout << "All test cases passed" << endl;
}
void kattis()
{
unordered_map<string, string> dict;
string line, meaning, word;
while(getline(cin, line))
{
if (!line.empty())
{
istringstream iss(line);
iss >> meaning >> word;
dict.insert( pair<string, string>(word, meaning) );
}
else
break;
}
while( cin >> word )
cout << answer( dict, word ) << endl;
}
int main(int argc, char *argv[])
{
if (argc > 1 && strncmp(argv[1], "test", 4) == 0)
test();
else
kattis();
return 0;
}<file_sep>#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cin >> a;
for (int i = 0; i < a.size() - 1; i++)
cout << a.substr(i,2) << " ";
cout << endl;
return 0;
}<file_sep>#include <iostream>
#include <vector>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <iterator>
using namespace std;
int answer(vector<int>& list, const int Fmax)
{
int ans, temp, count = 0;
vector<int>::iterator head, it = list.begin();
// When capacity C is 1 and there is fruit weights 1 in Forest
if (Fmax==1 && find(list.begin(), list.end(), 1) != list.end()) return 1;
while( (distance(it,list.end())>1 && distance(it,list.end())>=count) )
{
ans = *it;
head = it+1;
if( Fmax > ans) temp = 1;
while (distance(head,list.end())>= 1)
{
if( Fmax >= (ans + *head))
{
ans += *head;
temp++;
}
head++;
}
if (temp>count) count = temp;
it++;
}
return count;
}
void test()
{
vector<int> test = {4, 5, 3, 1, 6, 3, 2, 4, 1, 4, 5, 4, 2, 1, 4};
cout << answer(test, 1);
test = {4, 5, 3, 1, 6, 3, 2, 4, 1, 4, 5, 4, 2, 1, 4};
assert(answer(test, 10) == 5);
test = {8};
assert(answer(test, 5 ) == 0);
}
void kattis()
{
int i, Fnum, Fmax, in;
vector<int> list;
cin >> Fnum >> Fmax;
for ( i=0; i<Fnum&&cin >> in; i++ ) list.push_back( in );
cout << answer(list, Fmax)<< endl;
}
int main(int argc, char* argv[])
{
if(argc >1 && strncmp(argv[1], "test", 4)==0)
test();
else
kattis();
return 0;
}
//cat putovanje.1.in | ./a.out | diff - putovanje.1.ans
<file_sep>#include <iostream>
#include <unordered_set>
#include <algorithm>
using namespace std;
int main()
{
int i, N,M,cd, count = 0;
unordered_set<int> ns;
while( cin >>N>>M && N!=0 && M!=0)
{
for (i=N; i>0 && cin>>cd;i--) ns.insert(cd);
//sort(ns.begin(), ns.end());
for (i=0; i<M && cin>>cd && cd!=0;i++)
{
if(binary_search(ns.begin(), ns.end(), cd)&&cd!=ns.end())
count++;
}
}
cout << count << endl;
return 0;
} <file_sep>Write a C++ menu driven program that uses a Binary Search Tree (BST)
to store the input data.
The program will read in data from an input file, and store each word
in the tree, as well as keep a count of how many times each word appears
in the input file. Thus, each node in the tree will have the following
data: a string to store the word and an integer to keep track of the count.
An output will be a list of unique words that appear in the input file,
along with a count of how many times they appeared.
<file_sep>#include "class.h"
#include <iostream>
#include <string>
#include <vector>
#include <random>
#include <cstdlib>
#include <iterator>
#include <chrono>
#include <algorithm>
using namespace std;
void generateRandomNumbers(vector<int> &rands, int start, int end) {
std::ios::sync_with_stdio(false);
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<> dis(start, end);
generate(rands.begin(), rands.end(), bind(dis, ref(mt)));
}
void BubbleSort(vector<int> v) {
bool sorted;
for(int pass=0; pass<v.size()-1; pass++) {
sorted = true;
for (int i=1; i<v.size()-pass; i++) {
if (v[i-1] > v[i]) {
swap(v[i-1], v[i]);
sorted = false;
}
}
if (sorted)
break;
}
}
void SelectionSort(vector<int> v) {
for (int i=0; i<v.size()-1; i++) {
int minIndex = i;
for(int j=i+1; j < v.size(); j++) {
if (v[j] < v[minIndex])
minIndex = j;
}
if (v[minIndex] != v[i])
swap(v[minIndex], v[i]);
}
}
void InsertionSort(vector<int> v){
for(int i=1; i< v.size(); i++) {
for(int j=i; (j > 0) && (v[j] < v[j-1]); j--)
swap(v[j], v[j-1]);
}
}
void insertionSort2(vector<int> &v, int start, int incr) {
for(int i=start+incr; i<v.size(); i+=incr)
for(int j=i; (j >=incr) && v[j] < v[j-incr]; j-=incr)
swap(v[j], v[j-incr]);
}
void ShellSort(vector<int> v) {
for (int i=v.size()/2; i>2; i/=2)
for(int j=0; j<i; j++)
insertionSort2(v, j, i);
insertionSort2(v, 0, 1);
}
int partition(vector<int> &v, int left, int right) {
int pivotIndex = left + (right - left) / 2;
int pivotValue = v[pivotIndex];
int i = left, j = right;
int temp;
while(i <= j) {
while(v[i] < pivotValue) {
i++;
}
while(v[j] > pivotValue) {
j--;
}
if(i <= j) {
temp = v[i];
v[i] = v[j];
v[j] = temp;
i++;
j--;
}
}
return i;
}
void QuickSort(vector<int> &v, int left, int right) {
if(left < right) {
int pivotIndex = partition(v, left, right);
QuickSort(v, left, pivotIndex - 1);
QuickSort(v, pivotIndex, right);
}
}
void call_QuickSort(vector<int> v, int left, int right){
QuickSort(v, left, right);
}
void merge(vector<int> &v, int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
vector<int> L(n1); // auxiliary vector
vector<int> R(n2); // auxiliary vector
// copy data to temp Left and Right vectors
for(i=0; i<n1; i++)
L[i] = v[left+i];
for (j=0; j<n2; j++)
R[j] = v[mid+1+j];
// merge the temp vectors back into v
i = 0;
j = 0;
k = left; // initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
v[k] = L[i];
i++;
}
else {
v[k] = R[j];
j++;
}
k++;
}
// copy the remaining elements of L vector if there's any
while(i < n1) {
v[k] = L[i];
i++;
k++;
}
// copy the remaining elements of R vector if there's any
while(j < n2) {
v[k] = R[j];
j++;
k++;
}
}
void MergeSort(vector<int> &v, int left, int right){
if (left < right) { // general case
int mid = left+(right-left)/2; // same as (left+right)/2 but avoid overflow
MergeSort(v, left, mid);
MergeSort(v, mid+1, right);
// merge two sorted list
merge(v, left, mid, right);
}
}
void call_MergeSort(vector<int> v, int left, int right){
MergeSort(v, left, right);
}
void Swap(vector<int>& v, vector<int>::size_type i, vector<int>::size_type j) {
if(i == j) return;
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
void Sift(vector<int>& v, const vector<int>::size_type heapSize, const vector<int>::size_type siftNode) {
vector<int>::size_type i, j;
j = siftNode;
do
{
i = j;
if(((2*i + 1) < heapSize) && v[j] < v[2*i + 1])
j = 2*i + 1;
if(((2*i + 2) < heapSize) && v[j] < v[2*i + 2])
j = 2*i + 2;
Swap(v, i, j);
}
while(i != j);
}
void MakeInitialHeap(vector<int>& v) {
for(int i = v.size() - 1; i >= 0; --i)
Sift(v, v.size(), i);
}
void HeapSort(vector<int> v) {
MakeInitialHeap(v);
for(vector<int>::size_type i = v.size()-1; i > 0; --i) {
Swap(v, i, 0);
Sift(v, i, 0);
}
}
void AlgorithmHSort(vector<int> v){
sort(v.begin(), v.end());
}
void AlgorithmHStableSort(vector<int> v){
stable_sort(v.begin(), v.end());
}
void SequentialSearch(const vector<int> & v, int key) {
int index = 0;
while (index < v.size()) {
if (v[index] == key) // found our element; key comparison that controls the loop
return;
else
index ++;
}
}
void BinarySearch(const vector<int> &v, int key) {
int low = 0;
int high = v.size()-1;
while (low <= high) { // stop when low and high cross
int mid = (low+high)/2; // check middle of sequence
if (v[mid] == key) // found it
return; // return the index
else if (v[mid] > key) // check in left half
high = mid - 1;
else // check in right half
low = mid + 1;
}
return;
}
void BinarySearchTree() {
}
<file_sep>#include <iostream>
#include <cassert>
using namespace std;
string answer(int x)
{
if (x%2==0)
return " is even";
else
return " is odd";
}
void test()
{
assert(answer(0) == " is even");
assert(answer(99999) == " is odd");
cout << "all test cases passed" << endl;
}
void kattis()
{
int num, x;
cin >> num;
for (int i=0; i<num; i++)
{
cin >> x;
cout << x << answer(x) << endl;
}
}
int main(int argc, char* argv[])
{
if (argc > 1 && strncmp(argv[1], "test", 4) == 0 )
test();
else
kattis();
return 0;
}
//cat sample.in | ./a.out
//cat sample.in | ./a.out | diff -sample.ans<file_sep>#include <iostream>
#include <cmath>
#include <cassert>// g++ -std=c++11 icpctutorial.cpp
#include <cstring>
using namespace std;
string calculation(const int &a, const double &b, const int &c)
{
unsigned long int ans = 1;
switch(c)
{
case 1:
if (b>15) return "TLE";
for (int i = 2; i<=b; i++) ans*=i;
break;
case 2:
ans = pow(2, b);
break;
case 3:
ans = pow(b, 4);
break;
case 4:
ans = pow(b, 3);
break;
case 5:
ans = pow(b, 2);
break;
case 6:
ans = static_cast<long double>(ans);
ans = ceil ( static_cast<long double>(b) * log2(b));
break;
default:
ans = b;
break;
}
if (a<ans)
return "TLE";
else
return "AC";
}
void kattis()
{
int n, m, t;
cin >> n >> m >>t;
cout << calculation(n, m, t) << endl;
}
void test()
{
assert(calculation(10000000, 50, 6) == "AC");
assert(calculation(10000000, 10000001, 7) == "TLE");
assert(calculation(1000000000, 15, 1) == "TLE");
}
int main(int argc, char* argv[])
{
if (argc >1 && strncmp(argv[1], "test", 4) == 0)
test();
else
kattis();
return 0;
}<file_sep>#include <vector>
using namespace std;
void generateRandomNumbers(vector<int> &rands, int start, int end);
void BubbleSort(vector<int> v);
void SelectionSort(vector<int> v);
void InsertionSort(vector<int> v);
void insertionSort2(vector<int> &v, int start, int incr);
void ShellSort(vector<int> v);
int partition(vector<int> &v, int left, int right);
void QuickSort(vector<int> &v);
void call_QuickSort(vector<int> v, int left, int right);
void merge(vector<int> &v, int left, int mid, int right);
void MergeSort(vector<int> &v, int left, int right);
void call_MergeSort(vector<int> v, int left, int right);
void Swap(vector<int>& v, vector<int>::size_type i, vector<int>::size_type j);
void Sift(vector<int>& v, const vector<int>::size_type heapSize, const vector<int>::size_type siftNode);
void MakeInitialHeap(vector<int>& v);
void HeapSort(vector<int> v);
void AlgorithmHSort(vector<int> v);
void AlgorithmHStableSort(vector<int> v);
void SequentialSearch(const vector<int> & v, int key);
void BinarySearch(const vector<int> &v, int key);
void BinarySearchTree();
<file_sep>#include <iostream> // for the final project
#include <vector>
#include <random>
#include <iterator>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;
/*
template<class T> // worst case O(n). Best O(1). Average O(n/2)
int sequentialSearch(const vector<T> & v, T key)
{
int index = 0;
while (index < v.size())
{
if (v[index] == key) // found our element; key comparison that controls the loop
return index;
else
index ++;
}
return -1;
}
*/
void generateRandomNumbers(vector<int> &rands, int count, int start, int end)
{
random_device rd;
mt19937 mt(rd()); //create very random numbers
uniform_int_distribution<> dis(start, end); // numbers between start and end inclusive
generate(rands.begin(), rands.end(), bind( dis, ref(mt) ) );
}
int main()
{
vector<int> nums(20);
generateRandomNumbers(nums, 20, 0, 20);
cout << nums << endl;
return 0;
}
//binary_search() - use sort(v.begin(), v.end()) first to sort.<file_sep>#include "class.h"
#include <iostream>
#include <fstream>
#include <chrono>
using namespace std::chrono;
auto getTime = [](auto&& func, auto&&... params) {
const auto& start = high_resolution_clock::now();
std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
const auto& stop = high_resolution_clock::now();
duration<double> diff = stop - start;
return diff;
};
void calculate(vector<int> &randNumbers,double &a, double &b, double &c, double &d, double &e, double &f, double &g, double &h, double &i, double &j, double &k, ofstream& answer) {
for (int i = 0; i < 10; i ++){
generateRandomNumbers(randNumbers, 0, 20);
a+=getTime(BubbleSort, randNumbers).count();
b+=getTime(SelectionSort, randNumbers).count();
c+=getTime(InsertionSort, randNumbers).count();
d+=getTime(ShellSort, randNumbers).count();
e+=getTime(call_QuickSort, randNumbers, 0, randNumbers.size()-1).count();
f+=getTime(call_MergeSort, randNumbers, 0, randNumbers.size()-1).count();
g+=getTime(HeapSort, randNumbers).count();
h+=getTime(AlgorithmHSort, randNumbers).count();
i+=getTime(AlgorithmHStableSort, randNumbers).count();
j+=getTime(SequentialSearch, randNumbers, rand() % 10 + 1).count();
k+=getTime(BinarySearch, randNumbers, rand() % 10 + 1).count();
}
answer << "Bubble Sort: " << a/10 << endl;
answer << "Selection Sort: " << b/10<< endl;
answer << "Insertion Sort: " << c/10 << endl;
answer << "Shell Sort: " << d/10 << endl;
answer << "Quick Sort: " << e/10 << endl;
answer << "Merge Sort: " << f/10 << endl;
answer << "Heap Sort: " << g/10 << endl;
answer << "Algorithm.h Sort: " << h/10 << endl;
answer << "Algorithm.h Stable Sort: " << i/10 << endl;
answer << "Sequential Search: " << j/10<< endl;
answer << "Binary Search: " << k/10<< endl;
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
ofstream answer("answer.txt");
int sizes[3]= {1000, 5000, 10000};
for ( int n=0; n<3; n++ ) {
vector<int> randNumbers(sizes[n]);
double a=0.0,b=0.0,c=0.0,d=0.0,e=0.0,f=0.0,g=0.0,h=0.0,i=0.0,j=0.0,k=0.0;
calculate(randNumbers,a,b,c,d,e,f,g,h,i,j,k,answer);
}
return 0;
}
<file_sep>#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
//g++ -std=c++11 CD.cpp // USE SET
int counter(vector<int>& ns, int& cd, int count)
{
if( binary_search(ns.begin(), ns.end(), cd)) count++;
return count;
}
//testing
void kattis()
{
int i, N,M,cd, count;
vector<int> ns;
vector<int>::iterator n;
while( cin >>N>>M && N!=0 && M!=0)
{
count = 0;
ns.clear();
for (i=0; i<N&&cin>>cd;i++) ns.push_back(cd);
n= ns.begin();
for (i=0; i<M&&cin>>cd;i++) count = counter(ns, cd, count);
cout << count;
}
}
void test()
{
vector<int> test = {1, 5555, 6666, 99999, 100000, 1000000};
int nums[3] = {5555, 99999, 200000};
int count = 0;
assert(counter(test, nums[0],count)==1);
assert(counter(test, nums[1],count)==1);
assert(counter(test, nums[2],count)==0);
cout << "All test cases passed" << endl;
}
int main(int argc, char* argv[])
{
if (argc > 1 && strncmp(argv[1], "test", 1) == 0)
test();
else
kattis();
return 0;
}
|
72230374efb91e68ac92b453314dd85fed707551
|
[
"Markdown",
"Text",
"C++"
] | 21 |
C++
|
SKajiwara/CS3-skajiwara
|
aa7c9a0b6517696c2213102f7e999f44ef02c3f3
|
43a5dd94320692af133d235999d6041f869eafa6
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace General.Models
{
public class StoreViewModel
{
public List<Company> lCompany { get; set; }
public Store store { get; set; }
public Company selectetCompany { get; set; }
}
}
<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace General.Models
{
public class Store
{
public Guid id { get; set; }
public Guid companyId { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(30, ErrorMessage = "Name may not be longer then 30 letters")]
public string name { get; set; }
[Required(ErrorMessage = "Address is required")]
[StringLength(30, ErrorMessage = "Address may not be longer then 30 letters")]
public string address { get; set; }
[Required(ErrorMessage = "City is required")]
[StringLength(30, ErrorMessage = "City may not be longer then 30 letters")]
public string city { get; set; }
[Required(ErrorMessage = "Zip code is required")]
[StringLength(10, ErrorMessage = "Zip code may not be longer then 10 letters")]
public string zip { get; set; }
[Required(ErrorMessage = "Country is required")]
[StringLength(30, ErrorMessage = "Country may not be longer then 30 letters")]
public string country { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
public Guid selectedCompany { get; set; }
}
}
<file_sep>using Newtonsoft.Json;
using Repository.Interface;
using Repository.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Repositories
{
public class GoogleMapsRepository: IGoogleMapsRepository
{
IStoreRepository _StoreRepository;
public GoogleMapsRepository()
{
_StoreRepository = new StoreRepository();
}
public GoogleMapsRepository(StoreRepository storeRepository)
{
_StoreRepository = storeRepository;
}
/// <summary>
/// Gets Cordinates of Stores location information and saves it to database
/// (if fail location 0 will be saved instead)
/// </summary>
/// <param name="store">Repository.Store</param>
public async void Post(Stores store)
{
try
{
string address = store.Address + "+" + store.Zip + "+" + store.City + "+" + store.Country;
Results result = await APIRequest(address);
if (result.results.Count > 0 && result != null && result.results != null && result.results[0].geometry != null
&& result.results[0].geometry.location != null)
{
store.Latitude = result.results[0].geometry.location.lat.ToString();
store.Longitude = result.results[0].geometry.location.lng.ToString();
}
else
{
store.Latitude = "0";
store.Longitude = "0";
}
_StoreRepository.Update(store);
}
catch (Exception)
{
}
}
/// <summary>
/// Attempts to get cordinates from googlemaps
/// </summary>
/// <param name="address"></param>
/// <returns>Returns Result (objectified Json string)</returns>
public async Task<Results> APIRequest(string address)
{
try
{
using (var client = new HttpClient())
{
using (var r = await client.GetAsync("https://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false"))
{
if (r.StatusCode == System.Net.HttpStatusCode.OK)
{
string response = await r.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Results>(response);
}
return null;
}
}
}
catch (Exception)
{
return null;
}
}
}
}
<file_sep>using Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Repositories
{
public class StoreRepository: IStoreRepository
{
private IGoogleMapsRepository _iGoogleMapsRepository;
public StoreRepository()
{
_iGoogleMapsRepository = new GoogleMapsRepository(this);
}
/// <summary>
/// Returns a list of all stores with foreingKeyId companyId
/// </summary>
/// <param name="companyId">id of the company whos stores to return</param>
/// <returns>A List of Repository.Stores</returns>
public List<Repository.Stores> List(Guid companyId)
{
try
{
List<Repository.Stores> LStore = new List<Stores>();
using (var db = new CompaniesDBEntities())
{
LStore.AddRange(db.Stores.Where(x => x.CompanyId == companyId).ToList());
}
return LStore;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Returns Repository.Stores entity object
/// </summary>
/// <param name="companyId">CompanyId of Repository.Stores entity object to return</param>
/// <returns>Returns Repository.Stores entity object</returns>
public Repository.Stores Get(Guid storeId)
{
try
{
Repository.Stores store = new Repository.Stores();
using (var db = new CompaniesDBEntities())
{
store = db.Stores.Where(x => x.Id == storeId).First();
}
return store;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Adds a new Store to database
/// </summary>
/// <param name="NewStore">Store object to add</param>
public void Add(Stores NewStore)
{
try
{
using (var db = new CompaniesDBEntities())
{
db.Stores.Add(NewStore);
db.SaveChanges();
}
Task.Run(() => {
_iGoogleMapsRepository.Post(NewStore);
});
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Deletes Store with id storeId
/// </summary>
/// <param name="storeId">Id of the store to deltet (Guid)</param>
public void Delete(Guid storeId)
{
try
{
using (var db = new CompaniesDBEntities())
{
Repository.Stores storeToDelete = db.Stores.Find(storeId);
db.Stores.Attach(storeToDelete);
db.Stores.Remove(storeToDelete);
db.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Updates Store with id = updatedStore.Id
/// </summary>
/// <param name="updatedStore">Store to update</param>
public void Update(Stores updatedStore)
{
try
{
Repository.Stores storeToUpdate;
using (var db = new CompaniesDBEntities())
{
storeToUpdate = db.Stores.Find(updatedStore.Id);
storeToUpdate.CompanyId = updatedStore.CompanyId;
storeToUpdate.Name = updatedStore.Name;
storeToUpdate.Address = updatedStore.Address;
storeToUpdate.City = updatedStore.City;
storeToUpdate.Zip = updatedStore.Zip;
storeToUpdate.Country = updatedStore.Country;
storeToUpdate.Longitude = updatedStore.Longitude;
storeToUpdate.Latitude = updatedStore.Latitude;
db.SaveChanges();
}
Task.Run(() => {
_iGoogleMapsRepository.Post(storeToUpdate);
});
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Repositories
{
public class CompanyRepository: ICompanyRepository
{
/// <summary>
/// Gets ALL rows in table Companies
/// </summary>
/// <returns>Returns a list of ALL Repository.Companies</returns>
public List<Repository.Companies> List()
{
try
{
List<Repository.Companies> LCompany = new List<Repository.Companies>();
using (var db = new CompaniesDBEntities())
{
LCompany.AddRange(db.Companies.ToList());
}
return LCompany;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Gets Repository.company with Id = CompanyID (Guid)
/// </summary>
/// <param name="companyId">Id of Repository.Company to get (Guid)</param>
/// <returns>Returns Repository.Company with id = CompanyID (Guid)</returns>
public Repository.Companies Get(Guid companyId)
{
try
{
Repository.Companies company = new Repository.Companies();
using (var db = new CompaniesDBEntities())
{
company = db.Companies.Find(companyId);
}
return company;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Deletes Company with id = companyId
/// </summary>
/// <param name="companyId">Id of the Company to delete (Guid)</param>
public void Delete(Guid companyId)
{
try
{
using (var db = new CompaniesDBEntities())
{
Repository.Companies compToDelete = new Repository.Companies {Id = companyId };
db.Companies.Attach(compToDelete);
db.Companies.Remove(compToDelete);
db.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Adds a new Company to database
/// </summary>
/// <param name="newComp">Company object to add</param>
public void Add(Repository.Companies newComp)
{
try
{
using (var db = new CompaniesDBEntities())
{
db.Companies.Add(newComp);
db.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Updates Company with id = newComp.Id
/// </summary>
/// <param name="updatedComp">Company to update</param>
public void Update(Repository.Companies updatedComp)
{
try
{
using (var db = new CompaniesDBEntities())
{
Companies compToUpdate = db.Companies.Where(x => x.Id == updatedComp.Id).First();
compToUpdate.Name = updatedComp.Name;
compToUpdate.Notes = updatedComp.Notes;
compToUpdate.OrganizationNumber = updatedComp.OrganizationNumber;
db.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using General.Models;
namespace Service.CustomMapper
{
public class MapTo
{
/// <summary>
/// Maps a repository company entity object to a General.Model company object
/// </summary>
/// <param name="repCompany">repository company entity object</param>
/// <returns>General.Model Company object</returns>
public static Company Company(Repository.Companies repCompany)
{
try
{
Company comp = new Company
{
id = repCompany.Id,
name = repCompany.Name,
notes = repCompany.Notes,
organizationNumber = repCompany.OrganizationNumber.ToString()
};
return comp;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Maps a General.Model company object to a repository company entity object
/// </summary>
/// <param name="modelCompany">General.Model Company</param>
/// <returns>repository company entity object</returns>
public static Repository.Companies Company(Company modelCompany)
{
try
{
Repository.Companies comp = new Repository.Companies
{
Id = modelCompany.id,
Name = modelCompany.name,
Notes = modelCompany.notes,
OrganizationNumber = Convert.ToInt32(modelCompany.organizationNumber)
};
return comp;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Maps a List of repository company entity object to a list of general.model company objects
/// </summary>
/// <param name="compToMap">List of repository company entity object</param>
/// <returns>List of General.Model company object</returns>
public static List<Company> Companies(List<Repository.Companies> compToMap)
{
try
{
List<Company> LComp = new List<Company>();
foreach (Repository.Companies c in compToMap)
{
LComp.Add(Company(c));
}
return LComp;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Maps a List of repository stores entity objects to a list of general.model storeviewmodel objects
/// </summary>
/// <param name="LResosStore">List of repository stores entity objects</param>
/// <returns>List of general.model storeviewmodel objects</returns>
public static List<Store> Stores(List<Repository.Stores> LResosStore)
{
try
{
List<Store> LStore = new List<Store>();
foreach (Repository.Stores reposStore in LResosStore)
{
LStore.Add(Store(reposStore));
}
return LStore;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Mapps a StoreViewModel object to a repository store entity object
/// </summary>
/// <param name="store">StoreViewModel object</param>
/// <returns>repository store entity object</returns>
public static Repository.Stores Store(Store store)
{
try
{
Repository.Stores reposStore = new Repository.Stores();
reposStore.Id = store.id;
reposStore.CompanyId = store.companyId;
reposStore.Name = store.name;
reposStore.Address = store.address;
reposStore.City = store.city;
reposStore.Zip = store.zip;
reposStore.Country = store.country;
reposStore.Longitude = store.longitude;
reposStore.Latitude = store.latitude;
return reposStore;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// Mapps a repository store entity object to a StoreViewModel object
/// </summary>
/// <param name="reposStore">repository store entity object</param>
/// <returns>StoreViewModel object</returns>
public static Store Store(Repository.Stores reposStore)
{
try
{
Store store = new Store();
store.id = reposStore.Id;
store.companyId = reposStore.CompanyId;
store.name = reposStore.Name;
store.address = reposStore.Address;
store.city = reposStore.City;
store.zip = reposStore.Zip;
store.country = reposStore.Country;
store.longitude = reposStore.Longitude;
store.latitude = reposStore.Latitude;
return store;
}
catch (Exception e)
{
throw e;
}
}
}
}
<file_sep>using General.Models;
using Repository.Interface;
using Repository.Repositories;
using Service.Interface;
using Service.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.ModelBinding;
using System.Web.Mvc;
namespace ConsidTestuppgift2016.Controllers
{
public class CompanyController : Controller
{
private ICompanyServices _iCompanyServices;
public CompanyController()
{
_iCompanyServices = new CompanyServices();
}
// GET: Company/Home
// Returns View that shows all Companys
public ActionResult Home()
{
try
{
CompanyHomeViewModel companyHomeViewModel = new CompanyHomeViewModel();
companyHomeViewModel.lCompany = _iCompanyServices.List().OrderBy(o => o.name).ToList();
return View(companyHomeViewModel);
}
catch (Exception)
{
return View("Error");
}
}
// DELETE: Company/DeleteCompany
// Deletes chosen company with connected storys
public ActionResult DeleteCompany()
{
try
{
string companyId = RouteData.Values["id"].ToString();
_iCompanyServices.Delete(new Guid(companyId));
}
catch (Exception)
{
return View("Error");
}
return RedirectToAction("Home");
}
// GET: Company/EditCompany
// Allows user to edit a Company
public ActionResult EditCompany()
{
try
{
Company company = _iCompanyServices.Get(Guid.Parse(RouteData.Values["id"].ToString()));
return View(company);
}
catch (Exception)
{
return View("Error");
}
}
// POST: Company/EditCompany
// Saves updated Company
[HttpPost]
public ActionResult EditCompany(Company updatedComp)
{
try
{
if (!ModelState.IsValid)
{
return View(updatedComp);
}
_iCompanyServices.Update(updatedComp);
return RedirectToAction("Home");
}
catch (Exception)
{
return View("Error");
}
}
// GET: Company/AddCompany
// Allows user to add a new Company
public ActionResult AddCompany()
{
return View(new Company());
}
// POST: Company/AddCompany
// Saves new Company
[HttpPost]
public ActionResult AddCompany(Company company)
{
try
{
if (!ModelState.IsValid)
{
return View();
}
company.id = Guid.NewGuid();
_iCompanyServices.Add(company);
return RedirectToAction("Home");
}
catch (Exception)
{
return View("Error");
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Interface
{
public interface ICompanyRepository
{
/// <summary>
/// Gets ALL rows in table Companies
/// </summary>
/// <returns>Returns a list of ALL Repository.Companies</returns>
List<Repository.Companies> List();
/// <summary>
/// Gets Repository.company with Id = CompanyID (Guid)
/// </summary>
/// <param name="companyId">Id of Repository.Company to get (Guid)</param>
/// <returns>Returns Repository.Company with id = CompanyID (Guid)</returns>
Repository.Companies Get(Guid companyId);
/// <summary>
/// Deletes Company with id = companyId
/// </summary>
/// <param name="companyId">Id of the Company to delete (Guid)</param>
void Delete(Guid companyId);
/// <summary>
/// Adds a new Company to database
/// </summary>
/// <param name="newComp">Company object to add</param>
void Add(Repository.Companies newComp);
/// <summary>
/// Updates Company with id = newComp.Id
/// </summary>
/// <param name="updatedComp">Company to update</param>
void Update(Repository.Companies updatedComp);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Models
{
/// <summary>
/// Models for GoogleMaps Api request for easy convertion
/// </summary>
public class Results
{
public List<Result> results { get; set; }
public string status { get; set; }
}
public class Result
{
public List<Components> address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public string place_id { get; set; }
public IList<string> types { get; set; }
}
public class Components
{
public string long_name { get; set; }
public string short_name { get; set; }
public IList<string> types { get; set; }
}
public class Geometry
{
public Location location { get; set; }
public string location_type { get; set; }
public Location northeast { get; set; }
public Location southwest { get; set; }
}
public class Location
{
public float lat { get; set; }
public float lng { get; set; }
}
}
<file_sep>using General.Models;
using Service.Interface;
using Service.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ConsidTestuppgift2016.Controllers
{
public class StoreController : Controller
{
private IStoreServices _iStoreServices;
private ICompanyServices _iCompanyServices;
public StoreController()
{
_iStoreServices = new StoreServices();
_iCompanyServices = new CompanyServices();
}
// Get: /Store/Home
// Shows a list of a Companys Stories
public ActionResult Home()
{
try
{
string companyId = RouteData.Values["id"].ToString();
StoreHomeViewModel stores = new StoreHomeViewModel();
stores.company = _iCompanyServices.Get(new Guid(companyId));
stores.lStore = _iStoreServices.List(new Guid(companyId));
return View(stores);
}
catch (Exception)
{
return View("Error");
}
}
// GET: Store/AddStore
// Allows user to edit a Store
public ActionResult AddStore()
{
try
{
StoreViewModel store = new StoreViewModel();
store.lCompany = _iCompanyServices.List();
return View(store);
}
catch (Exception)
{
return View("Error");
}
}
// POST: Store/AddStore
// Adds a new store
[HttpPost]
public ActionResult AddStore(Store store)
{
try
{
if (!ModelState.IsValid)
{
StoreViewModel storeViewModel = new StoreViewModel();
storeViewModel.store = store;
storeViewModel.lCompany = _iCompanyServices.List();
return View(storeViewModel);
}
store.id = Guid.NewGuid();
_iStoreServices.Add(store);
return RedirectToAction("Home/" + store.companyId);
}
catch (Exception)
{
return View("Error");
}
}
// GET: Store/EditStore
// Allows user to edit a store
public ActionResult EditStore()
{
try
{
string storeId = RouteData.Values["id"].ToString();
StoreViewModel store = new StoreViewModel();
store.store = _iStoreServices.Get(new Guid(storeId));
store.lCompany = _iCompanyServices.List();
store.selectetCompany = _iCompanyServices.Get(store.store.companyId);
return View(store);
}
catch (Exception)
{
return View("Error");
}
}
// POST: Store/EditStore
// Updates the edited store
[HttpPost]
public ActionResult EditStore(Store store)
{
try
{
if (!ModelState.IsValid)
{
StoreViewModel storeViewModel = new StoreViewModel();
storeViewModel.store = store;
storeViewModel.lCompany = _iCompanyServices.List();
storeViewModel.selectetCompany = _iCompanyServices.Get(storeViewModel.store.companyId);
return View(storeViewModel);
}
_iStoreServices.update(store);
return RedirectToAction("Home/" + store.companyId);
}
catch (Exception)
{
return View("Error");
}
}
// DELETE: Store/DeleteStore
// Deletes the selected store
public ActionResult DeleteStore(Store store)
{
try
{
_iStoreServices.Delete(store.id);
return RedirectToAction("Home/" + store.companyId);
}
catch (Exception)
{
return View("Error");
}
}
}
}<file_sep>using General.Models;
using Repository.Interface;
using Repository.Repositories;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Services
{
public class StoreServices: IStoreServices
{
private IStoreRepository _iStoreRepository;
public StoreServices()
{
_iStoreRepository = new StoreRepository();
}
/// <summary>
/// Adds a new Store to database
/// </summary>
/// <param name="store">New storeViewModel to add</param>
public void Add(Store store)
{
try
{
_iStoreRepository.Add(CustomMapper.MapTo.Store(store));
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Returns store with id = storeId
/// </summary>
/// <param name="storeId">id of store to return</param>
/// <returns>Returns store with id = storeId</returns>
public Store Get(Guid companyId)
{
try
{
Store store = CustomMapper.MapTo.Store(_iStoreRepository.Get(companyId));
return store;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Updates a view model with id store.id
/// </summary>
/// <param name="store">The updated Store</param>
public void update(Store store)
{
try
{
_iStoreRepository.Update(CustomMapper.MapTo.Store(store));
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Deletes store with Id storeId (Guid)
/// </summary>
/// <param name="storeId">Id of store to delete (Guid)</param>
public void Delete(Guid storeId)
{
try
{
_iStoreRepository.Delete(storeId);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// returns a list of a companys stores
/// </summary>
/// <param name="companyId">Id of Company (Guid)</param>
/// <returns>returns a list of a companys stores</returns>
public List<Store> List(Guid companyId)
{
try
{
List<Store> LStore = CustomMapper.MapTo.Stores(_iStoreRepository.List(companyId));
return LStore;
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using General.Models;
using Repository.Interface;
using Repository.Repositories;
using Service.Interface;
using System;
using System.Collections.Generic;
namespace Service.Services
{
public class CompanyServices: ICompanyServices
{
private ICompanyRepository _companyRepository;
public CompanyServices()
{
_companyRepository = new CompanyRepository();
}
/// <summary>
/// Returns a List of All Companys
/// </summary>
/// <returns>Returns a List of All Companys</returns>
public List<Company> List()
{
try
{
List<Company> LComp = new List<Company>();
LComp.AddRange(CustomMapper.MapTo.Companies(_companyRepository.List()));
return LComp;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Returns Company with id = companyId
/// </summary>
/// <param name="companyId">Id of company to Get (Guid)</param>
/// <returns>Returns Company with id = companyId</returns>
public Company Get(Guid companyId)
{
try
{
Company company = CustomMapper.MapTo.Company(_companyRepository.Get(companyId));
return company;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Deletes the Company and connected stories
/// </summary>
/// <param name="companyId">Id of Company to delete (Guid)</param>
public void Delete(Guid companyId)
{
try
{
_companyRepository.Delete(companyId);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Adds a new company to database
/// </summary>
/// <param name="company">Company to add</param>
public void Add(Company company)
{
try
{
_companyRepository.Add(CustomMapper.MapTo.Company(company));
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Uppdates a company
/// </summary>
/// <param name="company">The updated Company</param>
public void Update(Company company)
{
try
{
_companyRepository.Update(CustomMapper.MapTo.Company(company));
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace General.Models
{
public class CompanyHomeViewModel
{
public List<Company> lCompany { get; set; }
}
}
<file_sep>using General.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Interface
{
public interface ICompanyServices
{
/// <summary>
/// Returns a List of All Companys
/// </summary>
/// <returns>Returns a List of All Companys</returns>
List<Company> List();
/// <summary>
/// Returns Company with id = companyId
/// </summary>
/// <param name="companyId">Id of company to Get (Guid)</param>
/// <returns>Returns Company with id = companyId</returns>
Company Get(Guid companyId);
/// <summary>
/// Deletes the Company and connected stories
/// </summary>
/// <param name="companyId">Id of Company to delete (Guid)</param>
void Delete(Guid companyId);
/// <summary>
/// Adds a new company to database
/// </summary>
/// <param name="company">Company to add</param>
void Add(Company company);
/// <summary>
/// Uppdates a company
/// </summary>
/// <param name="company">The updated Company</param>
void Update(Company company);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Interface
{
public interface IStoreRepository
{
/// <summary>
/// Returns a list of all stores with foreingKeyId companyId
/// </summary>
/// <param name="companyId">id of the company whos stores to return</param>
/// <returns>A List of Repository.Stores</returns>
List<Repository.Stores> List(Guid companyId);
/// <summary>
/// Returns Repository.Stores entity object
/// </summary>
/// <param name="companyId">CompanyId of Repository.Stores entity object to return</param>
/// <returns>Returns Repository.Stores entity object</returns>
Repository.Stores Get(Guid storeId);
/// <summary>
/// Adds a new Store to database
/// </summary>
/// <param name="NewStore">Store object to add</param>
void Add(Stores NewStore);
/// <summary>
/// Deletes Store with id storeId
/// </summary>
/// <param name="storeId">Id of the store to deltet (Guid)</param>
void Delete(Guid storeId);
/// <summary>
/// Updates Store with id = updatedStore.Id
/// </summary>
/// <param name="updatedStore">Store to update</param>
void Update(Stores updatedStore);
}
}
<file_sep>using General.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Interface
{
public interface IStoreServices
{
/// <summary>
/// Adds a new Store to database
/// and Async gets location from GoogleMaps API
/// </summary>
/// <param name="store">New storeViewModel to add</param>
void Add(Store store);
/// <summary>
/// Returns store with id = storeId
/// </summary>
/// <param name="storeId">id of store to return</param>
/// <returns>Returns store with id = storeId</returns>
Store Get(Guid companyId);
/// <summary>
/// Updates a view model with id store.id
/// and Async gets location from GoogleMaps API
/// </summary>
/// <param name="store">The updated Store</param>
void update(Store store);
/// <summary>
/// Deletes store with Id storeId (Guid)
/// </summary>
/// <param name="storeId">Id of store to delete (Guid)</param>
void Delete(Guid storeId);
/// <summary>
/// returns a list of a companys stores
/// </summary>
/// <param name="companyId">Id of Company (Guid)</param>
/// <returns>returns a list of a companys stores</returns>
List<Store> List(Guid companyId);
}
}
<file_sep>using General.Models;
using Repository.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repository.Interface
{
public interface IGoogleMapsRepository
{
/// <summary>
/// Gets Cordinates of Stores location information and saves it to database
/// (if fail location 0 will be saved instead)
/// </summary>
/// <param name="store">Repository.Store</param>
void Post(Stores store);
/// <summary>
/// Attempts to get cordinates from googlemaps
/// </summary>
/// <param name="address"></param>
/// <returns>Returns Result (objectified Json string)</returns>
Task<Results> APIRequest(string address);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace General.Models
{
public class Company
{
public Guid id { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(30,ErrorMessage = "Name may not be longer then 30 chars")]
public string name { get; set; }
[Required(ErrorMessage = "organizationnumber is required")]
[Range(1, int.MaxValue, ErrorMessage = "Number is to big")]
public string organizationNumber { get; set; }
public string notes { get; set; }
}
}
|
ab771a6233f9ef22a307b2ab991604bda1bc24e9
|
[
"C#"
] | 18 |
C#
|
shriok/Testuppgift
|
9199170b8d2a700c604245a8ab267c6579f9e8f0
|
88eaf3235a25ac1e87130f391b2ba4ef31a51a99
|
refs/heads/development
|
<file_sep># rubocop: disable Lint/RedundantCopDisableDirective
# rubocop: disable Layout/Tab
class User
attr_accessor :name, :nickname, :work, :bio, :location, :website, :pinned, :summary
def initialize
@summary = []
@pinned = []
end
end
# rubocop: enable Layout/Tab
# rubocop: enable Lint/RedundantCopDisableDirective
<file_sep>#!/usr/bin/env ruby
require 'colorize'
require_relative '../lib/scraper'
# rubocop:disable Metrics/AbcSize
def display_output(array)
puts
puts "Name: #{"#{array[0]} (#{array[1]})".red}"
puts
puts "Bio: #{(array[2]).to_s.red}"
puts
puts "Work: #{(array[3]).to_s.red}"
puts
puts "Location: #{(array[4]).to_s.red}"
puts
puts "Website: #{(array[5]).to_s.red}"
puts
puts '---------------------------------'
puts 'pinned Repositories'
puts '---------------------------------'
puts "1. #{(array[12]).to_s.red}"
puts "2. #{(array[13]).to_s.red}"
puts "3. #{(array[14]).to_s.red}"
puts "4. #{(array[15]).to_s.red}"
puts "5. #{(array[16]).to_s.red}"
puts "6. #{(array[17]).to_s.red}"
puts '--------------------------------'
end
# rubocop:enable Metrics/AbcSize
def display_prompt(_summary_info, scraper)
puts ''
puts "Enter a category name like #{'repositories'.red} or #{'stars'.red} or #{'followers'.red} or #{'following'.red} to get a list of its contents."
puts "Or Enter #{'\'q\''.red} to exit the program."
puts ''
list = scraper.page(gets.chomp)
puts '-------------------'
list.each.with_index { |item, idx| puts "#{idx + 1}. #{item.red}" }
puts '-------------------'
end
puts ''
puts 'Welcome!. This is a github scraping tool.'
puts ''
puts 'Enter your github username and follow the instructions.'
display_output(Array.new(18, 'xxxxx'))
puts ''
puts 'Enter any Github username: '
# rubocop:disable Lint/Loop
begin
scraper = Scraper.new(gets.chomp)
puts '---------------------------'
puts 'Invalid!, Enter a valid Github Username: ' unless scraper.valid
end until scraper.valid
# rubocop:enable Lint/Loop
summary_info = scraper.profile_info
display_output(summary_info)
loop do
display_prompt(summary_info, scraper)
end
<file_sep>source 'https://rubygems.org'
gem 'colorize '
gem 'nokogiri'
gem 'rspec'
gem 'rubocop'
<file_sep># Github Scraper
A Github Scraping Tool developed with Ruby and the Nokogiri gem
<!-- PROJECT SCRENSHOOT -->




<p align="center">
<a href="https://github.com/billodiallo/scraper-capstone-ruby">
</a>
<h1 align="center">My Github Scraper</h1> </p>
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [About the Project](#about-the-project)
* [Built With](#built-with)
* [Testing](#testing)
* [Contact](#contact)
* [Acknowledgements](#acknowledgements)
<!-- ABOUT THE PROJECT -->
## About The Project
This is Github Scrapping Tool built with ruby. This Tools is built as a capstone project for completing one of Microverse's Main Technical Curriculum sections.
[![Product Name Screen Shot][product-screenshot]][screenshot-url]
<!-- ABOUT THE PROJECT -->
## Installation
To use this scraper this is what you need to:
* Have ruby installed in your computer
* [Download](https://github.com/billodiallo/scraper-capstone-ruby.git) or clone this repo:
- Clone with SSH:
```
https://github.com/billodiallo/scraper-capstone-ruby.git
```
- Clone with HTTPS
```
github.com/billodiallo/scraper-capstone-ruby.git
```
* `cd` into `scraper-capstone-ruby` directory and run `bundle install`
* Finally, run `bin/main` in your terminal.
## How to use
When you first run this github scraping tool it begins by showing you the summary info output format
```
Github User
-------------------------------
Name: xxxxxx (xxxxxxx)
Bio: xxxxxx
Work: xxxxxx
Location: xxxxxx
Website: xxxxxx
---------------------------------
pinned Repositories
---------------------------------
1. xxxxxx
2. xxxxxx
3. xxxxxx
4. xxxxxx
5. xxxxxx
6. xxxxxx
--------------------------------
```
After this, you are prompted to enter a valid github username. Then it returns the above output format with all the information filled in.
```
Categories
---------------------------------
repositories: xxxxxx
stars: xxxxxx
followers: xxxxxxx
following: xxxxxx
----------------------------------
```
Then you will be prompted to enter a category name to see a full list of its contents. For instance enter `repositories` or `stars`, or `followers` or `following` to get a list of those scrapped categories. This will continue until you exit the program by typing `'q'` in the terminal and pressing Enter.
### Built With
This project was built using these technologies.
* Ruby
* Rspec
* Nokogiri gem
* Colorize gem
### Testing
If you wish to test it. Install `Rspec`with `gem install rspec`. Clone this repo to your local machine, cd into github-scraper directory and run `rspec`
<!-- LIVE VERSION -->
### LIVE DEMO VIDEO
https://www.loom.com/share/7c3fe4<KEY>
<!-- CONTACT -->
## Contact
👤 <NAME>
- GitHub: [@billodiallo](https://github.com/billodiallo)
- Twitter: [@BilloDi83547008](https://twitter.com/BilloDi83547008)
<!-- ACKNOWLEDGEMENTS -->
## Acknowledgements
* [Microverse](https://www.microverse.org/)
* [Ruby Documentation](https://www.ruby-lang.org/en/documentation/)
## 📝 License
This project is [MIT](LICENSE) licensed.
<file_sep>require_relative '../lib/scraper'
RSpec.describe Scraper do
let(:scraper1) { Scraper.new('billodiallo') }
describe '#initialize' do
it 'should be initialied with a valid Github Username' do
expect(scraper1.valid).to be true
end
let(:scraper2) { Scraper.new('amanioopqqzz') }
it 'should return false when username is invalid' do
expect(scraper2.valid).to be false
end
end
describe '#name' do
it 'should get scrapped name and set it to user name' do
result = scraper1.send(:name)
expect(result).to eq(' <NAME>')
end
it 'negative scenario' do
result = scraper1.send(:name)
expect(result).not_to eq(' mamadou')
end
end
describe '#nickname' do
it 'should get scrapped nickname and set it to user nickname' do
result = scraper1.send(:nickname)
expect(result).to eq('billodiallo')
end
it 'negative scenario user another nickname' do
result = scraper1.send(:nickname)
expect(result).not_to eq('arikarim')
end
end
describe '#work' do
it 'should get scrapped work and set it to user work' do
result = scraper1.send(:work)
expect(result).to eq('Microverse')
end
it 'negative scenario user work' do
result = scraper1.send(:work)
expect(result).not_to eq('freelancer')
end
end
describe '#location' do
it 'should get scrapped location and set it to user location' do
result = scraper1.send(:location)
expect(result).to eq('Nairobi')
end
it 'negative scenario for location' do
result = scraper1.send(:location)
expect(result).not_to eq('lagos')
end
end
describe '#website' do
it 'should get scrapped website and set it to user website' do
result = scraper1.send(:website)
expect(result).to eq('https://www.linkedin.com/in/mabillodiallo/')
end
it 'negative scenario for another website' do
result = scraper1.send(:website)
expect(result).not_to eq('www.facebook.com')
end
end
describe '#bio' do
it 'should get scrapped bio and set it to user bio' do
result = scraper1.send(:bio)
expect(result).not_to eq('Full stack Web DeveloperHTML & CSS ,Ruby on Rails, JavaScript and React) and Cloud Computing, AWS')
end
end
describe '#pinned_repos' do
it 'should get scrapped pinned repos and set it to user pinned repos' do
result = scraper1.send(:pinned_repos)
expect(result).to include('awaards')
end
it 'negative scenario for pinned' do
result = scraper1.send(:pinned_repos)
expect(result).not_to include('javamaia')
end
it 'should return an array of pinned repositories' do
result = scraper1.send(:pinned_repos)
expect(result).to be_an Array
end
end
describe '#profile_info' do
it 'should add all user info to an array' do
expect(scraper1.profile_info).to be_an Array
end
it 'negative scenario profile_info' do
expect(scraper1.profile_info).not_to eql(Array)
end
it 'returned array should include user info' do
result = scraper1.profile_info
expect(result).not_to eql('[" <NAME>", "billodiallo", "Full stack Web DeveloperHTML & CSS ,Ruby on Rails, JavaScript and R... 0, 0, 0, 67, 0, 0, "NYTproject", "awaards", "TNW-Project", "newsweek2020", "instagramapp", "Pitch"] ')
end
end
describe '#counters' do
it 'should get scrapped number of each category and add it to user summary array' do
result = scraper1.send(:counters)
expect(result).to be_an Array
end
it 'negative scenario' do
result = scraper1.send(:counters)
expect(result).not_to eql(Array)
end
it 'returned array should include numbers of each category' do
result = scraper1.send(:counters)
expect(result.any?(Integer)).to be true
end
it 'negative scenario' do
result = scraper1.send(:counters)
expect(result.any?(Integer)).not_to be false
end
end
describe '#page' do
it 'should return error if category is invalid' do
expect(scraper1.page('shopping')).to eq(['Error!, category invalid'])
end
it 'negative scenario' do
expect(scraper1.page('shopping')).not_to eq(['try again'])
end
it 'should return an array if valid' do
expect(scraper1.page('repositories')).to be_an Array
end
it 'negative scenario' do
expect(scraper1.page('repositories')).not_to eql(Array)
end
it 'returned array should include category items' do
result = scraper1.page('repositories')
expect(result).not_to include('TNW-Project')
end
end
describe '#repos' do
it 'should get scrapped user repos and add them to an array' do
result = scraper1.send(:page, 'repositories')
expect(result).to be_an Array
end
end
describe '#stars' do
it 'should get scrapped user stars and add them to an array' do
result = scraper1.send(:page, 'stars')
expect(result).to be_an Array
end
end
describe '#followers' do
it 'should get scrapped user followers and add them to an array' do
result = scraper1.send(:page, 'followers')
expect(result).to be_an Array
end
it 'negative scenario' do
result = scraper1.send(:page, 'followers')
expect(result).not_to eql(Array)
end
it 'negative scenario' do
result = scraper1.send(:page, 'another1')
expect(result).not_to eql(Array)
end
end
describe '#following' do
it 'should get scrapped user following and add them to an array' do
result = scraper1.send(:page, 'following')
expect(result).to be_an Array
end
it 'negative scenario' do
result = scraper1.send(:page, 'following')
expect(result).not_to eql(Array)
end
end
end
|
a763d8509e25d315a262631a6f7361da10a8e8a8
|
[
"Markdown",
"Ruby"
] | 5 |
Ruby
|
billodiallo/scraper-capstone-ruby
|
bc00a80a606faa052d4ec81cdfb86a39021313cf
|
e4582fcfd00deb8f4a522c637393eeeb02251045
|
refs/heads/master
|
<repo_name>Gannicus91/GraphF<file_sep>/src/Function.java
public interface Function {
public double eval(double arg);
}
<file_sep>/src/Main.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws IOException {
Expression func = new Expression
(BiOperator.PLUS,
new Operand(UOperator.ABS, new Expression(BiOperator.POW, new Operand(Argument.ARGUMENT), new Operand(3))),
new Operand(5));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String s = bufferedReader.readLine();
ExString f = new ExString(s);
/*for (Object o : f.INtoRPN()){
System.out.println(o);
}*/
Function e = f.StrToExpr();
for(double i = 0; i<10 ; i+=0.1){
System.out.println(e.eval(i));
}
}
public static String format(String inputString){
inputString = inputString.replaceAll(" ", "");
inputString = inputString.toLowerCase();
return inputString;
}
}
<file_sep>/src/ExString.java
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExString {
private String inputString;
public ExString(String inputString){
this.inputString = inputString;
}
public boolean is_valid(){
inputString = inputString.replaceAll(" ", "");
inputString = inputString.toLowerCase();
Pattern p = Pattern.compile("^[-+*/a-z0-9()^.]+$");
Matcher m = p.matcher(inputString);
if(!m.matches()){
return false;
}
Stack<Integer> circle = new Stack<>();
Stack<Integer> square = new Stack<>();
int size = inputString.length();
for (int i = 0; i < size; i++){
switch (inputString.charAt(i)){
case '(':
circle.push(i);
break;
case '[':
square.push(i);
break;
case ')':
if (!circle.empty()){
if(!square.empty() && square.peek() > circle.peek()){
return false;
}else circle.pop();
}else return false;
break;
case ']':
if (!square.empty()){
if(!circle.empty() && circle.peek() > square.peek()){
return false;
}else square.pop();
}else return false;
}
}
p = Pattern.compile("^[-+*/0-9()^.xe]+$");
String s = inputString.replaceAll("(?:abs|sin|cos|tg|ctg|asin|acos|atan|acot|sh|ch|th|cth|log2|lg|ln|sign)(?=\\(.+\\))|pi|fi", "");
m = p.matcher(s);
if (!m.matches()){
return false;
}
p = Pattern.compile("^[0-9().\\[\\]x]+$");
s = s.replaceAll("(?!=[^-+*/^.])(?:[-+*/^])(?<![^-+*/^])", "");
m = p.matcher(s);
if (!m.matches()){
return false;
}
return circle.empty() && square.empty();
}
public ArrayList<Object> getObjectList(){
if(!is_valid()){
return null;
}
ArrayList<Object> lex = new ArrayList<>();
int size = inputString.length();
ArrayList<Pattern> patterns = new ArrayList<>();
ArrayList<Matcher> matchers = new ArrayList<>();
patterns.add(Pattern.compile("[-+*/^()x]"));
patterns.add(Pattern.compile("[a-z0-9.]"));
int k = 0;
for (int i = 0; i < size; i++){
String it = new Character(inputString.charAt(i)).toString();
matchers.add(patterns.get(0).matcher(it));
matchers.add(patterns.get(1).matcher(it));
if(matchers.get(0).matches()){
lex.add(it);
}else{
String num = "";
while (matchers.get(1).matches()){
num += it;
i++;
if (i == size)
break;
it = new Character(inputString.charAt(i)).toString();
matchers.remove(1);
matchers.add(patterns.get(1).matcher(it));
}
i--;
lex.add(num);
}
matchers.clear();
}
size = lex.size();
for (int i = 0; i < size; i++){
Pattern num = Pattern.compile("([0-9]+(\\.[0-9]+)?)+");
Pattern arg = Pattern.compile("x");
Matcher m = num.matcher(lex.get(i).toString());
if (m.matches()){
Operand op = new Operand(Double.valueOf(lex.get(i).toString()));
lex.set(i, op);
}
m = arg.matcher(lex.get(i).toString());
if (m.matches()){
Operand op = new Operand(Argument.ARGUMENT);
lex.set(i, op);
}
}
for (int i = 1; i < size; i++){
if(lex.get(i-1).equals("-") && i - 1 == 0 || lex.get(i).equals("-") && lex.get(i-1).equals("(")){
if (i-1==0){
lex.set(i-1, "u-");
}else {
lex.set(i, "u-");;
}
}
if(lex.get(i-1).equals("+") && i - 1 == 0 || lex.get(i).equals("+") && lex.get(i-1).equals("(")){
if (i-1==0){
lex.set(i-1, "u+");
}else {
lex.set(i, "u+");
}
}
}
return lex;
}
public ArrayList<Object> INtoRPN(){
ArrayList<Object> lex = getObjectList();
Pattern p = Pattern.compile("abs|sin|cos|tg|ctg|asin|acos|atan|acot|sh|ch|th|cth|log2|lg|ln|sign|u-|u\\+");
Map<String, Integer> priority = new HashMap<>();
priority.put("-", 1);
priority.put("+", 1);
priority.put("*", 2);
priority.put("/", 2);
priority.put("^", 3);
priority.put("(", 0);
ArrayList<String> Right = new ArrayList<>();
Right.add("^");
Stack<Object> RPNStack = new Stack<>();
ArrayList<Object> RPNList = new ArrayList<>();
for(Object token : lex){
if(token instanceof Operand){
RPNList.add(token);
}
if(p.matcher(token.toString()).matches()){
RPNStack.push(token);
}
if(token.equals("(")){
RPNStack.push(token);
}
if(token.equals(")")){
if(!RPNStack.empty()) {
Object peek = RPNStack.pop();
while (!peek.equals("(")) {
RPNList.add(peek);
peek = RPNStack.pop();
}
}
}
Pattern p1 = Pattern.compile("[-+*/^]");
if(p1.matcher(token.toString()).matches()){
if (!RPNStack.empty()){
Object peek = RPNStack.peek();
while (p.matcher(peek.toString()).matches() ||
priority.get(peek.toString()) > priority.get(token.toString()) ||
!Right.contains(token.toString()) && priority.get(peek.toString()) == priority.get(token.toString())){
RPNList.add(RPNStack.pop());
if(RPNStack.empty()){
break;
}
peek = RPNStack.peek();
}
}
RPNStack.add(token);
}
}
while (!RPNStack.empty()){
RPNList.add(RPNStack.pop());
}
return RPNList;
}
public Function StrToExpr(){
ArrayList<Object> lex = INtoRPN();
int i = 0;
while(lex.size()!=1){
Expression exp;
Operand op;
switch (lex.get(i).toString()){
case "^":
i = i - 2;
exp = new Expression(BiOperator.POW, (Function)lex.get(i), (Function) lex.get(i+1));
lex.remove(i);
lex.remove(i);
lex.set(i, exp);
break;
case "*":
i = i - 2;
exp = new Expression(BiOperator.PRODUCT, (Function)lex.get(i), (Function) lex.get(i+1));
lex.remove(i);
lex.remove(i);
lex.set(i, exp);
break;
case "/":
i = i - 2;
exp = new Expression(BiOperator.FRACT, (Function)lex.get(i), (Function) lex.get(i+1));
lex.remove(i);
lex.remove(i);
lex.set(i, exp);
break;
case "+":
i = i - 2;
exp = new Expression(BiOperator.PLUS, (Function)lex.get(i), (Function) lex.get(i+1));
lex.remove(i);
lex.remove(i);
lex.set(i, exp);
break;
case "-":
i = i - 2;
exp = new Expression(BiOperator.MINUS, (Function)lex.get(i), (Function) lex.get(i+1));
lex.remove(i);
lex.remove(i);
lex.set(i, exp);
break;
case "u+":
i = i - 1;
op = new Operand(UOperator.PLUS, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "u-":
i = i - 1;
op = new Operand(UOperator.MINUS, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "sin":
i = i - 1;
op = new Operand(UOperator.SIN, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "cos":
i = i - 1;
op = new Operand(UOperator.COS, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "tg":
i = i - 1;
op = new Operand(UOperator.TAN, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "ctg":
i = i - 1;
op = new Operand(UOperator.COT, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "asin":
i = i - 1;
op = new Operand(UOperator.ASIN, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "acos":
i = i - 1;
op = new Operand(UOperator.ACOS, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "atan":
i = i - 1;
op = new Operand(UOperator.ATAN, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "acot":
i = i - 1;
op = new Operand(UOperator.ACOT, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "sh":
i = i - 1;
op = new Operand(UOperator.SH, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "ch":
i = i - 1;
op = new Operand(UOperator.CH, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "th":
i = i - 1;
op = new Operand(UOperator.TH, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "cth":
i = i - 1;
op = new Operand(UOperator.CTH, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "log2":
i = i - 1;
op = new Operand(UOperator.LOG2, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "lg":
i = i - 1;
op = new Operand(UOperator.LG, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "ln":
i = i - 1;
op = new Operand(UOperator.LN, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "sign":
i = i - 1;
op = new Operand(UOperator.SIGNUM, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
case "abs":
i = i - 1;
op = new Operand(UOperator.ABS, (Function) lex.get(i));
lex.remove(i);
lex.set(i, op);
break;
}
i++;
}
return (Function)lex.get(0);
}
}
|
087aa2cdd5b5f278720f91cf81cddb231723d6d8
|
[
"Java"
] | 3 |
Java
|
Gannicus91/GraphF
|
6f11c2e3e2ddf7f705784c7bf9964f0d009b2303
|
a96c3be89690f7da1bbc27bb07ed683f77146370
|
refs/heads/main
|
<file_sep>import React, { Component } from "react";
import "../../style/Badge.css";
const IMAGE_URL = "https://image.flaticon.com/icons/png/512/432/432548.png";
export default class NewClients extends Component {
constructor() {
super();
this.clientOfCurrentMounth = 0;
this.currentMounth = "";
}
getClientsWithcurrentMounth() {
let d = new Date();
let mounth = d.getMonth() + 1;
let year = d.getFullYear();
this.clientOfCurrentMounth = this.props.clients.filter(
(client) =>
client.date.split("/")[0] == mounth && client.date.split("/")[2] == year
).length;
this.currentMounth = this.getCurrentMonth(mounth - 1);
}
getCurrentMonth(n) {
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
return month[n];
}
render() {
this.getClientsWithcurrentMounth();
return (
<div className="badgeBox">
<img src={IMAGE_URL} className="imageIcon" />
<h3 className="newClientCount">{this.clientOfCurrentMounth}</h3>
<h6 className="currentMounth"> New {this.currentMounth} Clients</h6>
</div>
);
}
}
<file_sep>import React from 'react'
import { Button } from 'react-bootstrap'
import Form from 'react-bootstrap/Form'
import { useState, useEffect } from 'react'
import { observer, inject } from 'mobx-react'
import axios from 'axios'
const apiUpdate = "http://localhost:8080"
const UpdateClient = inject("CustomerStore")(observer((props) => {
const [formValues, setFormValues] = useState({})
const [owner, setOwner] = useState("");
const [emailType, setEmailType] = useState("")
const [sold, setSold] = useState(false)
const [name, setName] = useState("")
const handleChange = (e) => {
setName(e.target.value)
// setFormValues({
// ...formValues,
// [e.target.name]: e.target.value
// })
}
const handleSelectOwner = (e) => {
setOwner(e.target.value)
}
const handleSubmit = () => {
console.log(formValues)
}
const handleEmailType = (e) => {
setEmailType(e.target.value)
}
const handleClickEmail = () => {
axios.put(`${apiUpdate}/emails/?email=${emailType}&name=${name}`)
}
const handleClickOwner = () => {
axios.put(`${apiUpdate}/owners/?owner=${owner}&name=${name}`)
}
const handleClickSold = (e) => {
e.preventDefault();
setSold(!sold);
axios.put(`${apiUpdate}/sold/?name=${name}`)
}
return (
<div>
<Form>
<h3>UPDATE</h3>
<span>client Name</span><input name="client" placeholder="<NAME>" onChange={handleChange}></input>
<br></br>
<label >Transfer OwnerShip To
<select
className="selectUpdate"
onChange={handleSelectOwner}
value={owner}
>
{props.CustomerStore.owners.map((o, index) => {
return (
<option key={index} value={o.owner}>
{o.owner}
</option>
);
})}
</select>
<button onClick={handleClickOwner}>setOwner</button>
</label>
<br></br>
<label > send Email
<select name="email" onChange={handleEmailType} placeholder="sendEmail">
<option value="A" >A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<button onClick={handleClickEmail}> sendEmail</button>
</label>
<br></br>
<button onClick={handleClickSold}> sold</button>
</Form>
</div>
)
}))
export default UpdateClient
<file_sep>import React, { useState, useEffect } from 'react'
import { observer, inject } from 'mobx-react'
const AddClient = inject("CustomerStore")(observer((props) => {
const [newClient, setNewClient] = useState({})
useEffect(() => {
setNewClient({owner:"<NAME>"})
}, [])
const handleChange = (e) => {
setNewClient({
...newClient,
[e.target.name]: e.target.value
})
}
const handleSubmit = () => {
console.log(newClient)
props.CustomerStore.addNewClient(newClient)
}
return (
<div>
<h3>Add Client</h3>
<span>first Name</span><input name="firstName" placeholder="<NAME>" onChange={handleChange}></input>
<br></br>
<span>SureName</span><input name="lastName" placeholder="SurName" onChange={handleChange}></input>
<br></br>
<span>Country</span><input name="country" placeholder="Country" onChange={handleChange}></input>
<br></br>
<select
className="selectUpdate"
onChange={handleChange}
name="owner"
value={newClient.owner}
>
{props.CustomerStore.owners.map((o, index) => {
return (
<option key={index} value={o.owner}>
{o.owner}
</option>
);
})}
</select>
<br></br>
<button onClick={handleSubmit}> Add new Client</button>
</div>
)
}))
export default AddClient
<file_sep>import React, { Component } from "react";
// import "../../css/Badge.css";
import "../../style/Badge.css"
const IMAGE_URL =
"https://w7.pngwing.com/pngs/410/105/png-transparent-gmail-logo-g-suite-gmail-computer-icons-google-email-e-mail-angle-text-rectangle.png";
export default class EmailsSent extends Component {
constructor() {
super();
this.clientsEmailNotSend = 0;
}
getUnsentedClientsEmail() {
let CountClientsUnsentedEmail = 0;
this.props.clients.forEach((client) => {
if (client.email_type_id != null) {
CountClientsUnsentedEmail++;
}
});
this.clientsEmailNotSend = CountClientsUnsentedEmail;
}
render() {
this.getUnsentedClientsEmail();
return (
<div className="badgeBox">
<img src={IMAGE_URL} className="imageIcon" />
<h3 className="newClientCount"> {this.clientsEmailNotSend}</h3>
<h6 className="currentMounth"> Emails Sent</h6>
</div>
);
}
}
<file_sep>import React from "react";
import { useState, useEffect, useRef } from "react";
import Table from "react-bootstrap/Table";
import { observer, inject } from "mobx-react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faHeart } from "@fortawesome/free-regular-svg-icons";
import "../../style/CustomerDisplay.css";
import debounce from "lodash.debounce";
import ModalSelected from "./ModalSelected";
const CustomerDisplay = inject("CustomerStore")(
observer((props) => {
const listInnerRef = useRef();
const [tableColumns, setTableColumns] = useState([
"Name",
"SureName",
"Country",
"FirstContact",
"Email",
"sold",
"Owner",
]);
const [data, setData] = useState([]);
const [selectedCustomer, setSelectedCustomer] = useState({});
const [showAlert, setShowAlert] = useState(false);
const [isFetching, setIsFetching] = useState(false);
const [isBottom, setIsBottom] = useState(false);
const [isTop, setIsTop] = useState(false);
useEffect(() => {
props.CustomerStore.getData();
window.addEventListener("scroll", handleScroll, {
passive: true,
});
window.addEventListener("wheel", handleWheel);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
useEffect(() => {
if (isBottom === false) {
return;
}
window.scrollTo(0, 0);
setIsBottom(false);
console.log(window);
}, [isBottom]);
useEffect(() => {
if (isTop === false) {
return;
}
window.scrollTo(0, 0);
setIsTop(false);
}, [isTop]);
///
////
const handleWheel = (e) => {
// console.log(e);
};
const handleAlertModal = (proxy) => {
const customer = Object.assign({}, proxy);
console.log(customer);
props.CustomerStore.handleAlertModalChange();
setShowAlert(!showAlert);
setSelectedCustomer(customer);
};
const handleScroll = () => {
// console.info("scrolling ", window.scrollY);
let top = window.scrollY === 0;
let bottom =
Math.ceil(window.innerHeight + window.scrollY) >=
document.documentElement.scrollHeight;
console.log(window.scrollY);
if (bottom) {
setIsBottom(true); // bottom true
props.CustomerStore.incrementPage();
console.log(props.CustomerStore.page);
props.CustomerStore.getData();
console.log("at the bottom");
} else if (top) {
console.log(" ------------------------top ", window.scrollY);
props.CustomerStore.decrementPage();
props.CustomerStore.getData();
setIsTop(true); // top
}
};
return (
<div>
<Table striped bordered hover variant="dark" ref={listInnerRef}>
<thead>
<tr className="keys-column">
{tableColumns.map((d) => (
<td key={d}>{d}</td>
))}
</tr>
</thead>
<tbody>
{props.CustomerStore.list.map((customer, index) => (
<tr
key={index + customer.first}
onClick={() => {
handleAlertModal(customer);
}}
>
<td key={index + "f"}>{customer.first}</td>
<td key={index + "l"}>{customer.last}</td>
<td key={index + "c"}>{customer.country}</td>
<td key={index + "d"}>{customer.date}</td>
<td key={index + "e"}>{customer.email_type}</td>
<td key={index + "s"}>
{customer.sold == 1 ? (
<FontAwesomeIcon icon={faHeart}></FontAwesomeIcon>
) : null}
</td>
<td key={index + "o"}>{customer.owner}</td>
</tr>
))}
</tbody>
</Table>
{isFetching ? (
<div className="spinner-border" role="status">
<span className="sr-only">Loading...</span>
</div>
) : null}
<ModalSelected customer={selectedCustomer}></ModalSelected>
</div>
);
})
);
export default CustomerDisplay;
<file_sep>import React, { Component } from "react";
import "../../style/Badge.css";
const IMAGE_URL = "https://icon-library.com/images/world-icon/world-icon-3.jpg";
const axios = require("axios");
const MOST_COUNTRY_SALES = "http://localhost:8080/mostcountrysales";
export default class HottestCountry extends Component {
constructor() {
super();
this.state = {
country: "",
};
}
componentDidMount = () => {
axios
.get(MOST_COUNTRY_SALES)
.then((response) => this.setState({ country: response.data[0].country }));
};
render() {
return (
<div className="badgeBox">
<img src={IMAGE_URL} className="imageIcon" />
<h3 className="newClientCount">{this.state.country}</h3>
<h6 className="currentMounth"> Hottest Country</h6>
</div>
);
}
}
<file_sep>import React, { Component } from "react";
import EmailsSent from "./EmailsSent";
import HottestCountry from "./HottestCountry";
import NewClients from "./NewClients";
import OutstandingClients from "./OutstandingClients";
export default class Badges extends Component {
constructor() {
super();
this.state = {
clients: [],
};
}
render() {
return (
<div>
<NewClients clients={this.props.clients} />
<EmailsSent clients={this.props.clients} />
<OutstandingClients clients={this.props.clients} />
<HottestCountry clients={this.props.clients} />
</div>
);
}
}
<file_sep>import React, { Component } from "react";
import "../../style/Badge.css";
const IMAGE_URL =
"https://www.clipartmax.com/png/middle/192-1927276_business-clients-icon.png";
export default class OutstandingClients extends Component {
constructor() {
super();
this.qutstandingClients = 0;
}
getUnSoldClientsNum() {
this.qutstandingClients = this.props.clients.filter(
(client) => client.sold == 0
).length;
}
render() {
this.getUnSoldClientsNum();
return (
<div className="badgeBox">
<img src={IMAGE_URL} className="imageIcon" />
<h3 className="newClientCount">{this.qutstandingClients}</h3>
<h6 className="currentMounth"> Qutstanding Clients</h6>
</div>
);
}
}
<file_sep>import React, { useEffect } from 'react'
import UpdateClient from './UpdateClient'
import { observer, inject } from 'mobx-react'
import AddClient from './AddClient'
const Actions = inject("CustomerStore")(observer((props) => {
useEffect(() => {
props.CustomerStore.getOwners()
console.log(props.CustomerStore.owners)
}, [])
return (
<div>
<UpdateClient></UpdateClient>
<AddClient></AddClient>
</div>
)
}))
export default Actions
<file_sep>import { observer, inject } from "mobx-react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import NavBar from "./components/NavBar";
import { useEffect } from "react";
import CustomerDisplay from "./components/client/CustomerDisplay";
//CustomerStore
const App = inject("CustomerStore")(
observer((props) => {
useEffect(async () => {
props.CustomerStore.getPageNumber();
}, []);
return (
<div>
<NavBar></NavBar>
</div>
);
})
);
export default App;
<file_sep>import React, { Component } from "react";
import "../../style/Charts.css";
import {
BarChart,
CartesianGrid,
XAxis,
Tooltip,
Legend,
Bar,
YAxis,
} from "recharts";
const axios = require("axios");
const SALES_BY_COUNTRY = "http://localhost:8080/salesByCountry";
export default class SalesByCountry extends Component {
constructor() {
super();
this.state = {
salesByCountry: [],
};
}
componentDidMount = () => {
this.getSalesByCountries();
};
getSalesByCountries = () => {
axios.get(SALES_BY_COUNTRY).then((response) => {
this.setState({ salesByCountry: response.data });
console.log(response.data);
});
};
render() {
return (
<div className="chartComponent">
<BarChart width={600} height={250} data={this.state.salesByCountry}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="country" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="Sales" fill="#8884d8" />
</BarChart>
</div>
);
}
}
<file_sep>import React from 'react'
import CustomerDisplay from './CustomerDisplay'
function Clients() {
return (
<div>
<CustomerDisplay></CustomerDisplay>
</div>
)
}
export default Clients
<file_sep>import React, { Component } from "react";
import "../../style/Charts.css";
import {
BarChart,
CartesianGrid,
XAxis,
Tooltip,
Legend,
Bar,
YAxis,
} from "recharts";
const axios = require("axios");
const TOP_OWNERS = "http://localhost:8080/topOwners";
export default class TopEmployees extends Component {
constructor() {
super();
this.state = {
topThreeOwners: [],
};
}
componentDidMount = () => {
axios.get(TOP_OWNERS).then((response) => {
this.setState({ topThreeOwners: response.data });
});
};
render() {
return (
<div className="chartComponent">
<BarChart
width={600}
height={300}
data={this.state.topThreeOwners}
layout="vertical"
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<XAxis type="number" dataKey="total" />
<YAxis type="category" dataKey="owner" />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Bar
dataKey="total"
fill="#d63031"
stroke="#000000"
strokeWidth={1}
barSize={30}
/>
</BarChart>
</div>
);
}
}
|
314d0af61e1e544be510683d015e19ac60d56f3b
|
[
"JavaScript"
] | 13 |
JavaScript
|
MusaUnleashed/CoustmerRM
|
53882ffdd6e19527a72680d15f5d2437e336083d
|
7a10781c591add653eb01877b579208b6ea20680
|
refs/heads/master
|
<repo_name>FatecSocialFit/SocialFit_Official<file_sep>/wwwroot/js/login.js
/***busca um endereço pelo cep****/
$(document).ready(function () {
});
/*
$.ajax({
type: 'POST',
url: '/Questionario/ObterPorPalavraChave',
data: { Palavra: $("#txtPalavraChave").val(), idUsuario: getCookie("token", 0) },
success: function (result) {
if (result != null && result.length > 0) {
PreencherTabela(result);
}
else {
bootbox.alert("Nenhum questionário encontrado.");
}
$("#divLoading").hide(300);
},
error:
}
});
<file_sep>/Pages/PageUser.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using SocialFit.Data;
using SocialFit.Models;
namespace SocialFit.Pages
{
[Authorize]
public class PageUserModel : PageModel
{
private readonly SocialFit.Data.SocialFitContext _context;
public const string SessionKeyName = "_Name";
public PageUserModel(SocialFit.Data.SocialFitContext context)
{
_context = context;
}
public Client Client { get;set; }
public async Task OnGetAsync()
{
// Client = await _context.Client.ToListAsync();
Client = await _context.Client.FirstOrDefaultAsync(b => b.Login.Equals(User.Identity.Name));
}
}
}
<file_sep>/Models/Client.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace SocialFit.Models
{
public class Client
{
public int Id { get; set; }
[MaxLength(45)]
[Required]
[Display(Name = "Email")]
public string Login { get; set; }
[MaxLength(800)]
[Required]
public string Password { get; set; }
[Display(Name = "Nome")]
public string Name { get; set; }
[Display(Name = "Genero")]
public string genre { get; set; }
public bool isActive { get; set; }
[Display(Name = "Data de Nascimento")]
public Nullable<System.DateTime> DateBorn { get; set; }
public Nullable<System.DateTime> CreatedAt { get; set; }
public Nullable<System.DateTime> UpdatedAt { get; set; }
}
}
<file_sep>/Models/Company.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace SocialFit.Models
{
public class Company
{
public virtual Client Cliente { get; set; }
public int Id { get; set; }
public string Nome { get; set; }
public string Cnpj {get; set;}
public string Endereco { get; set; }
}
}
<file_sep>/ClientConfig/ClientsConfig.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SocialFit.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SocialFit.ClientConfig
{
public class ClientsConfig : IEntityTypeConfiguration<Client>
{
public void Configure(EntityTypeBuilder<Client> builder)
{
builder.HasKey(c => c.Id);
builder.Property(c => c.isActive)
.HasDefaultValue(true)
.IsRequired();
builder.Property(c => c.Name)
.IsRequired(false)
.HasDefaultValue("");
builder.Property(c => c.genre)
.IsRequired(false);
builder.Property(c => c.Login)
.IsRequired()
.HasMaxLength(45);
builder.Property(c => c.Password)
.HasMaxLength(800)
.IsRequired();
builder.Property(c => c.CreatedAt)
.HasDefaultValueSql("getdate()");
}
}
}
<file_sep>/Data/SocialFitContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SocialFit.ClientConfig;
using SocialFit.Models;
namespace SocialFit.Data
{
public class SocialFitContext : DbContext
{
public SocialFitContext (DbContextOptions<SocialFitContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modeBuilder)
{
modeBuilder.ApplyConfiguration(new ClientsConfig());
base.OnModelCreating(modeBuilder);
}
public DbSet<SocialFit.Models.Client> Client { get; set; }
public DbSet<SocialFit.Models.Company> Companies { get; set; }
}
}
<file_sep>/ClientConfig/CompanyConfig.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SocialFit.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SocialFit.ClientConfig
{
public class CompanyConfig : IEntityTypeConfiguration<Company>
{
public void Configure(EntityTypeBuilder<Company> builder)
{
}
}
}
<file_sep>/Pages/Clients/Create.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SocialFit.Data;
using SocialFit.Models;
namespace SocialFit.Pages.Clients
{
[AllowAnonymous]
public class CreateModel : PageModel
{
private readonly SocialFit.Data.SocialFitContext _context;
public CreateModel(SocialFit.Data.SocialFitContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public Client Client { get; set; }
public Client cli { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
string repeatPassword = Request.Form["repeat-passwd"];
string password = <PASSWORD>;
string aceitar = Request.Form["concordar"];
var cli = await _context.Client.FirstOrDefaultAsync(m => m.Login == Client.Login);
if (!string.Equals(password, repeatPassword) || password.Length < 8 || cli!=null || aceitar==null )
{
return RedirectToPage("/Erros");
}
Hash hash = new Hash(SHA512.Create());
// generate password hash SHA512
Client.Password = <PASSWORD>(Client.Password);
_context.Client.Add(Client);
await _context.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}<file_sep>/Pages/Account/Login.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SocialFit.Data;
using SocialFit.Models;
namespace SocialFit.Pages.Account
{
public class LoginModel : PageModel
{
private readonly SocialFit.Data.SocialFitContext _context;
[BindProperty]
public Client Client { get; set; }
public LoginModel(SocialFit.Data.SocialFitContext context)
{
_context = context;
}
public async Task<IActionResult> OnPost()
{
if(!IsUserAuthenticade(Request.Form["email"], Request.Form["passwd"]))
{
ModelState.AddModelError(string.Empty, "Usuário ou senha inválidos");
return Page();
}
var cli = _context.Client.FirstOrDefault(c => c.Login.Equals(Request.Form["email"]));
var claims = new List<Claim>{
new Claim(ClaimTypes.Name, Request.Form["email"]),
};
var userIdentify = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentify);
await HttpContext.SignInAsync(principal);
ViewData["usuario"] = cli.Id.ToString();
return RedirectToPage("/PageUser");
}
public async Task<IActionResult> OnPostLogoutAsync()
{
await HttpContext.SignOutAsync();
return RedirectToPage("/Index");
}
public bool IsUserAuthenticade(string email, string senha)
{
Hash hash = new Hash(SHA512.Create());
var cli = _context.Client.FirstOrDefault(c => c.Login == email);
if(cli!=null && hash.VerificarSenha(senha, cli.Password))
{
return true;
}
return false;
}
}
}
|
af217a63e48f69123a02126241581607154b312a
|
[
"JavaScript",
"C#"
] | 9 |
JavaScript
|
FatecSocialFit/SocialFit_Official
|
8951c7153c08ea715d33fcde7fcbef6b75130771
|
65033af7111721dd89a25cd83ff9aed03d027685
|
refs/heads/master
|
<repo_name>Trent-Farley/SPC<file_sep>/pricing.php
<?php
include "./scripts/nav.php";
?>
<head>
<title>Services</title>
</head>
<div id="columns">
<ul class="price">
<li class="header">ATV/Dirt Bike Frame</li>
<li class="grey">$130 - $140</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Full Size Truck Bumpers</li>
<li class="grey">$150 each</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Valve Covers</li>
<li class="grey">$40 each</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Lawn Mower Deck</li>
<li class="grey">Starting at $75</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Headache Rack</li>
<li class="grey">$200</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Wheels up to 48 inches</li>
<li class="grey">Starting at $150</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">4cyl: turbo(manifold)-shorty-long tube</li>
<li class="grey">$40--$75-$125</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">6cyl: manifold--long tube</li>
<li class="grey">$65-$100-$150</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">8cyl Small block: manifold--shorty--long tube</li>
<li class="grey">$75-150-200</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Piston coating</li>
<li class="grey">$25 per piston</li>
</ul>
</div>
<div id="columns">
<ul class="price">
<li class="header">Cylinder heads</li>
<li class="grey">$75 per head</li>
</ul>
</div>
<!-- <div id="columns">
<ul class="price">
<li class="header"></li>
<li class="grey"></li>
</ul>
</div> -->
<!-- This WOULD be the best way of doing this, but there is no way to style
the information to make it look better
-->
<!-- <button type="button" onclick="loadData()">Load Spreadsheet Data</button>
<div id="items"></div>
<div id="price"></div>
<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTyUPdfSeM8UAXMssTzmGXoI2TUqhvM1_bd2Se1Hfs-e_VCHaqTYallSyUHcwEG0hi-6ZNXd3QvpvXB/pubhtml?widget=false&headers=false" width="80%" height="80%"></iframe>
<script src="./scripts/pricing.js"></script> -->
</body>
</html><file_sep>/index.php
<?php
include "./scripts/nav.php";
?>
<head>
<title>Home</title>
</head>
<h1 class="censpc"><img src="./images/SPC(Blacksword).PNG" alt="Santiam Powder Coating" id="llogo"></h1>
<h1 id="ta1">What We're Up To</h1>
<div id="fbcont">
<iframe id="fb" src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2FSantiamPowderCoating&tabs=timeline&width=800&height=500&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true&appId" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>
</div>
<div class="minfo">
<h1 id="ta">Contact Us</h1>
<p id="info">
(541) 791-6515
<br>
<ul id="info1">
<h1 id="ta">Business Hours</h1>
Monday: 9:00 AM - 6:00 PM
<br>Tuesday: 9:00 AM - 6:00 PM
<br>Wednesday: 9:00 AM - 6:00 PM
<br>Thursday: 9:00 AM - 6:00 PM
<br>Friday: 9:00 AM - 6:00 PM
<br>Saturday: Closed
<br>Sunday: Closed
</ul>
</div>
<h1 id="ta">
Map
</h1>
<div style="width:100%"><iframe width="100%" height="400" src="https://maps.google.com/maps?width=100%&height=400&hl=en&q=39144%20Shilling%20Dr%2C%20Scio%2C%20OR%2097374+(Santiam%20Powder%20Coating)&ie=UTF8&t=&z=14&iwloc=B&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"><a href="https://www.maps.ie/map-my-route/">Draw map route</a></iframe></div><br />
</body>
</html>
<file_sep>/scripts/pricing.ts
function loadData() {
let names:any = new Array();
const url ='https://docs.google.com/spreadsheets/d/e/2PACX-1vTyUPdfSeM8UAXMssTzmGXoI2TUqhvM1_bd2Se1Hfs-e_VCHaqTYallSyUHcwEG0hi-6ZNXd3QvpvXB/pub?output=csv';
let xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
let lines = xmlhttp.responseText.split('\n')
names[0].push(lines);
readCSV(names);
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
readCSV(names);
}
let readCSV = (names:any)=>{
let header = new Array();
header[0] = names[0]
console.log(header);
// header.split(',');
// let headers = names[0].split(",")
// console.log(header);
}
<file_sep>/gallery.php
<?php
include "./scripts/nav.php";
?>
<head>
<title>Gallery</title>
</head>
<h1 id="ta">Gallery</h1>
<iframe src="https://drive.google.com/embeddedfolderview?id=17-YxJx44E6jPFYxNIGK2dJZTfExMfNSP#grid" style="position:fixed; left:0; bottom:0; right:0; width:100%; height:85%; border:none; margin:0; padding:0; overflow:hidden; ">
Sorry! your browser does not support our current gallery.
</iframe></body>
</html><file_sep>/scripts/pricing.js
function loadData() {
var names = new Array();
var url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTyUPdfSeM8UAXMssTzmGXoI2TUqhvM1_bd2Se1Hfs-e_VCHaqTYallSyUHcwEG0hi-6ZNXd3QvpvXB/pub?output=csv';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var lines = xmlhttp.responseText.split('\n');
names[0].push(lines);
readCSV(names);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
readCSV(names);
}
var readCSV = function (names) {
var header = new Array();
header[0] = names[0];
console.log(header);
// header.split(',');
// let headers = names[0].split(",")
// console.log(header);
};
<file_sep>/about.php
<?php
include "./scripts/nav.php";
?>
<head>
<title>About</title>
</head>
<h1 id="ta">About Us</h1>
<p id="about">
Santiam Powder Coating was founded by <NAME> and <NAME>
looking to provide the Mid-Willamette Valley with quality Powder and
High-Temp Ceramic coatings. We are a small job shop dedicated to
individual projects weather you are a industrial company looking to
coat thousands of items or a home hobbyist hoping to refinish the metal
patio furniture. We can offer custom powder coat with over 6500 different
colors, state of the art high temperature ceramic coating for exhaust
systems, high performance internal engine coatings and can source many
other coatings based on your specific task at hand. Santiam Powder
coating enjoys customizing the vision in your hands to the reality
in your project. Dylan and Roy always enjoy answering questions,
so feel free to give us a call and schedule your next visit. Be sure
to visit us on Facebook and Instagram
</p></body>
</html>
|
fce305b0747b2e5576665bd3dd8dc87b5acbce51
|
[
"JavaScript",
"TypeScript",
"PHP"
] | 6 |
PHP
|
Trent-Farley/SPC
|
83c1ec6180f875eb153eb48b21dd6db430cf483b
|
26dfea712c9373f30d5dc7142b9e8c0173103a61
|
refs/heads/master
|
<repo_name>arshiay/EmailRBOT<file_sep>/README.md
# EmailRBOT
سورس ربات t.me/emailrbot در تلگرام
<file_sep>/index.php
<?php
##----------------------OnyxTM---------------------#
define("TOKEN","XXX:XXX");
function onyx($method, $datas=[]){
$url = "https://api.telegram.org/bot".TOKEN."/".$method;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
$res = curl_exec($ch);
if(curl_error($ch)){
var_dump(curl_error($ch));
}else{
return json_decode($res);
}
}
##----------------------OnyxTM---------------------#
function sendMessage($chat_id,$text,$btn){
onyx("sendMessage",[
'chat_id'=>$chat_id,
'text'=>$text,
'parse_mode'=>"HTML",
'reply_markup'=>$btn
]);
}
##----------------------OnyxTM---------------------#
function sendAction($chat_id,$action){
onyx("sendChatAction",[
'chat_id'=>$chat_id,
'action'=>$action,
]);
}
##----------------------OnyxTM---------------------#
function sendMail($to,$subject,$txt){
$headers = "From: <EMAIL>" . "\r\n" .
"CC: <EMAIL>";
mail($to,$subject,$txt,$headers);
}
##----------------------OnyxTM---------------------#
$update = json_decode(file_get_contents("php://input"));
$chat_id = $update->message->chat->id;
$text = $update->message->text;
$reply = $update->message->reply_to_message;
$data = $update->callback_query->data;
$id = $update->callback_query->message->chat->id;
##----------------------OnyxTM---------------------#
$btn = json_encode([
'inline_keyboard'=>[
[['text'=>'قوانین 🔴','callback_data'=>'gavanin']]
]
]);
##----------------------OnyxTM---------------------#
if($text == "/start"){
sendAction($chat_id,'typing');
sendMessage($chat_id,"سلام دوست من🤡
اول ایمیل شخصی رو که میخوا براش پیام بفرستی رو برای من ارسال کن🤳
بعد با ریپلای ایمیل پیامت رو بفرست😘
",$btn);
}elseif($text == "/about"){
sendAction($chat_id,'typing');
sendMessage($chat_id,"گروه برنامه نویسی ONYX 🤡
اعضای تیم:
@mench 🤡
@shitilestan 🤡
کانال های ما :
@ch_jockdoni 🤡
@phpbots 🤡",$btn);
}elseif($data == "gavanin"){
sendAction($id,'typing');
sendMessage($id,"قوانین 🔰:
هر گونه پیام گمراه کننده و دادن وعده دروغ یا پیامی مبنا بر برنده شدن و... 🤠
✅- درصورت مشاهده هرگونه تخلف اعم از ارسال ایمیل های سیاسی، غیر اخلاقی، فریبنده، هر گونه ایجاد رعب، ایجاد مزاحمت برای اشخاص و ...، تمامی مشخصات و سوابق استفاده کاربر بدون اطلاع قبلی دراختیار پلیس فتا و نیز مراجع قضایی ذیصلاح قرارخواهد گرفت.
✅- کاربر می پذیرد هيچگونه استفاده خلاف قوانين و مقررات جاري جمهوري اسلامي ايران انجام ندهد.
✅- ایمیل بات هیچگونه مسئولیتی در قبال ایمیل های ارسالی نمی پذیرد.
👨🏻🏫با تشکر مدیریت onyx
دوستان برتر :
🥇جوکدونی
🥈اپکس
🥉بینام",$btn);
}else {
sendAction($id, 'typing');
$to = $reply->text;
$headers = "From: <EMAIL>" . "\r\n" .
"CC: <EMAIL>";
if(mail($to,"New Mail",$text,$headers)){
sendMessage($id, "ایمیل ارسال شد.
دریافت کننده : $to
متن ایمیل :
$text", $btn);
}else{
$a = array('خطای ۱۰۱','خطای ۲۰۲','خطای ۴۰۴');
sendMessage($id, $a[rand(0,2)], $btn);
}
}
##----------------------OnyxTM---------------------#
|
f0ab283e207f90e3806dfbbb525aeacf59e2de18
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
arshiay/EmailRBOT
|
c099daf036d0608b1f3e25adbf75cc611dd4b872
|
fc19c7fb86c86de42008c693fc4311a14dcc3c84
|
refs/heads/master
|
<file_sep>pub use core::{convert, fmt, option, result, str};
#[inline]
pub fn align(val: usize, to: usize) -> usize {
val + (to - (val % to)) % to
}
#[derive(Debug)]
pub enum SliceReadError {
UnexpectedEndOfInput,
}
pub type SliceReadResult<T> = Result<T, SliceReadError>;
pub trait SliceRead {
fn read_be_u32(&self, pos: usize) -> SliceReadResult<u32>;
fn read_be_u64(&self, pos: usize) -> SliceReadResult<u64>;
fn read_bstring0(&self, pos: usize) -> SliceReadResult<&[u8]>;
fn subslice(&self, start: usize, len: usize) -> SliceReadResult<&[u8]>;
}
impl<'a> SliceRead for &'a [u8] {
fn read_be_u32(&self, pos: usize) -> SliceReadResult<u32> {
// check size is valid
if !(pos + 4 <= self.len()) {
return Err(SliceReadError::UnexpectedEndOfInput);
}
Ok(
(self[pos] as u32) << 24 | (self[pos + 1] as u32) << 16 | (self[pos + 2] as u32) << 8
| (self[pos + 3] as u32),
)
}
fn read_be_u64(&self, pos: usize) -> SliceReadResult<u64> {
// check size is valid
if !(pos + 8 <= self.len()) {
return Err(SliceReadError::UnexpectedEndOfInput);
}
Ok(
(self[pos] as u64) << 56 | (self[pos + 1] as u64) << 48 | (self[pos + 2] as u64) << 40
| (self[pos + 3] as u64) << 32 | (self[pos + 4] as u64) << 24
| (self[pos + 5] as u64) << 16 | (self[pos + 6] as u64) << 8
| (self[pos + 7] as u64),
)
}
fn read_bstring0(&self, pos: usize) -> SliceReadResult<&[u8]> {
let mut cur = pos;
while cur < self.len() {
if self[cur] == 0 {
return Ok(&self[pos..cur]);
}
cur += 1;
}
Err(SliceReadError::UnexpectedEndOfInput)
}
fn subslice(&self, start: usize, end: usize) -> SliceReadResult<&[u8]> {
if !(end < self.len()) {
return Err(SliceReadError::UnexpectedEndOfInput);
}
Ok(&self[start..end])
}
}
#[derive(Debug)]
pub enum VecWriteError {
NonContiguousWrite,
UnalignedWrite,
}
pub type VecWriteResult = Result<(), VecWriteError>;
pub trait VecWrite {
fn write_be_u32(&mut self, pos: usize, val: u32) -> VecWriteResult;
fn write_be_u64(&mut self, pos: usize, val: u64) -> VecWriteResult;
fn write_bstring0(&mut self, val: &str) -> VecWriteResult;
fn pad(&mut self, alignment: usize) -> VecWriteResult;
}
impl VecWrite for Vec<u8> {
fn write_be_u32(&mut self, pos: usize, val: u32) -> VecWriteResult {
if pos % 4 != 0 {
return Err(VecWriteError::UnalignedWrite);
}
if pos > self.len() {
return Err(VecWriteError::NonContiguousWrite);
}
if pos + 4 > self.len() {
for _ in 0..(pos + 4 - self.len()) {
self.push(0);
}
}
assert!(pos + 3 < self.len());
self[pos] = ((val >> 24) & 0xff) as u8;
self[pos + 1] = ((val >> 16) & 0xff) as u8;
self[pos + 2] = ((val >> 8) & 0xff) as u8;
self[pos + 3] = (val & 0xff) as u8;
Ok(())
}
fn write_be_u64(&mut self, pos: usize, val: u64) -> VecWriteResult {
if pos % 8 != 0 {
return Err(VecWriteError::UnalignedWrite);
}
if pos > self.len() {
return Err(VecWriteError::NonContiguousWrite);
}
if pos > self.len() - 8 {
for _ in 0..(pos + 8 - self.len()) {
self.push(0);
}
}
assert!(pos + 7 < self.len());
self[pos] = ((val >> 56) & 0xff) as u8;
self[pos + 1] = ((val >> 48) & 0xff) as u8;
self[pos + 2] = ((val >> 40) & 0xff) as u8;
self[pos + 3] = ((val >> 32) & 0xff) as u8;
self[pos + 4] = ((val >> 24) & 0xff) as u8;
self[pos + 5] = ((val >> 16) & 0xff) as u8;
self[pos + 6] = ((val >> 8) & 0xff) as u8;
self[pos + 7] = (val & 0xff) as u8;
Ok(())
}
fn write_bstring0(&mut self, val: &str) -> VecWriteResult {
for b in val.bytes() {
self.push(b);
}
self.push(0);
Ok(())
}
fn pad(&mut self, alignment: usize) -> VecWriteResult {
let misalignment = self.len() % alignment;
if misalignment > 0 {
for _ in 0..(alignment - misalignment) {
self.push(0);
}
}
Ok(())
}
}
<file_sep>[package]
name = "device_tree"
version = "1.0.3"
authors = ["<NAME> <<EMAIL>>"]
license = "MIT"
description = "Reads and parses Linux device tree images"
repository = "https://github.com/mbr/device_tree-rs"
documentation = "https://mbr.github.io/device_tree-rs/device_tree/"
[features]
string-dedup = [] # Requires std
<file_sep>//! Parse flattened linux device trees
//!
//! Device trees are used to describe a lot of hardware, especially in the ARM
//! embedded world and are also used to boot Linux on these device. A device
//! tree describes addresses and other attributes for many parts on these
//! boards
//!
//! This library allows parsing the so-called flattened device trees, which
//! are the compiled binary forms of these trees.
//!
//! To read more about device trees, check out
//! [the kernel docs](https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/devicetree/booting-without-of.txt?id=HEAD).
//! Some example device trees
//! to try out are [the Raspberry Pi ones]
//! (https://github.com/raspberrypi/firmware/tree/master/boot).
//!
//! The library does not use `std`, just `core`.
//!
//! # Examples
//!
//! ```ignore
//! fn main() {
//! // read file into memory
//! let mut input = fs::File::open("sample.dtb").unwrap();
//! let mut buf = Vec::new();
//! input.read_to_end(&mut buf).unwrap();
//!
//! let dt = device_tree::DeviceTree::load(buf.as_slice ()).unwrap();
//! println!("{:?}", dt);
//! }
//! ```
extern crate core;
pub mod util;
use core::str;
use util::{align, SliceRead, SliceReadError, VecWrite, VecWriteError};
const MAGIC_NUMBER: u32 = 0xd00dfeed;
const SUPPORTED_VERSION: u32 = 17;
const COMPAT_VERSION: u32 = 16;
const OF_DT_BEGIN_NODE: u32 = 0x00000001;
const OF_DT_END_NODE: u32 = 0x00000002;
const OF_DT_PROP: u32 = 0x00000003;
const OF_DT_END: u32 = 0x00000009;
/// An error describe parsing problems when creating device trees.
#[derive(Debug)]
pub enum DeviceTreeError {
/// The magic number `MAGIC_NUMBER` was not found at the start of the
/// structure.
InvalidMagicNumber,
/// An offset or size found inside the device tree is outside of what was
/// supplied to `load()`.
SizeMismatch,
/// Failed to read data from slice.
SliceReadError(SliceReadError),
/// The data format was not as expected at the given position
ParseError(usize),
/// While trying to convert a string that was supposed to be ASCII, invalid
/// utf8 sequences were encounted
Utf8Error,
/// The device tree version is not supported by this library.
VersionNotSupported,
/// The device tree structure could not be serialized to DTB
VecWriteError(VecWriteError),
}
/// Device tree structure.
#[derive(Debug, PartialEq)]
pub struct DeviceTree {
/// Version, as indicated by version header
pub version: u32,
/// The number of the CPU the system boots from
pub boot_cpuid_phys: u32,
/// A list of tuples of `(offset, length)`, indicating reserved memory
// regions.
pub reserved: Vec<(u64, u64)>,
/// The root node.
pub root: Node,
}
/// A single node in the device tree.
#[derive(Debug, PartialEq)]
pub struct Node {
/// The name of the node, as it appears in the node path.
pub name: String,
/// A list of node properties, `(key, value)`.
pub props: Vec<(String, Vec<u8>)>,
/// Child nodes of this node.
pub children: Vec<Node>,
}
#[derive(Debug)]
pub enum PropError {
NotFound,
Utf8Error,
Missing0,
SliceReadError(SliceReadError),
}
impl From<SliceReadError> for DeviceTreeError {
fn from(e: SliceReadError) -> DeviceTreeError {
DeviceTreeError::SliceReadError(e)
}
}
impl From<VecWriteError> for DeviceTreeError {
fn from(e: VecWriteError) -> DeviceTreeError {
DeviceTreeError::VecWriteError(e)
}
}
impl From<str::Utf8Error> for DeviceTreeError {
fn from(_: str::Utf8Error) -> DeviceTreeError {
DeviceTreeError::Utf8Error
}
}
#[cfg(feature = "string-dedup")]
mod advancedstringtable {
use std::collections::HashMap;
pub struct StringTable {
pub buffer: Vec<u8>,
index: HashMap<String, u32>,
}
impl StringTable {
pub fn new() -> StringTable {
StringTable {
buffer: Vec::new(),
index: HashMap::new(),
}
}
pub fn add_string(&mut self, val: &str) -> u32 {
if let Some(offset) = self.index.get(val) {
return *offset;
}
let offset = self.buffer.len() as u32;
self.buffer.extend(val.bytes());
self.buffer.push(0);
self.index.insert(val.to_string(), offset);
offset
}
}
}
#[cfg(not(feature = "string-dedup"))]
mod stringtable {
pub struct StringTable {
pub buffer: Vec<u8>,
}
impl StringTable {
pub fn new() -> StringTable {
StringTable { buffer: Vec::new() }
}
pub fn add_string(&mut self, val: &str) -> u32 {
let offset = self.buffer.len();
self.buffer.extend(val.bytes());
self.buffer.push(0);
offset as u32
}
}
}
#[cfg(not(feature = "string-dedup"))]
use stringtable::StringTable;
#[cfg(feature = "string-dedup")]
use advancedstringtable::StringTable;
impl DeviceTree {
//! Load a device tree from a memory buffer.
pub fn load(buffer: &[u8]) -> Result<DeviceTree, DeviceTreeError> {
// 0 magic_number: u32,
// 4 totalsize: u32,
// 8 off_dt_struct: u32,
// 12 off_dt_strings: u32,
// 16 off_mem_rsvmap: u32,
// 20 version: u32,
// 24 last_comp_version: u32,
// // version 2 fields
// 28 boot_cpuid_phys: u32,
// // version 3 fields
// 32 size_dt_strings: u32,
// // version 17 fields
// 36 size_dt_struct: u32,
if try!(buffer.read_be_u32(0)) != MAGIC_NUMBER {
return Err(DeviceTreeError::InvalidMagicNumber);
}
// check total size
if try!(buffer.read_be_u32(4)) as usize != buffer.len() {
return Err(DeviceTreeError::SizeMismatch);
}
// check version
let version = try!(buffer.read_be_u32(20));
if version != SUPPORTED_VERSION {
return Err(DeviceTreeError::VersionNotSupported);
}
let off_dt_struct = try!(buffer.read_be_u32(8)) as usize;
let off_dt_strings = try!(buffer.read_be_u32(12)) as usize;
let off_mem_rsvmap = try!(buffer.read_be_u32(16)) as usize;
let boot_cpuid_phys = try!(buffer.read_be_u32(28));
// load reserved memory list
let mut reserved = Vec::new();
let mut pos = off_mem_rsvmap;
loop {
let offset = try!(buffer.read_be_u64(pos));
pos += 8;
let size = try!(buffer.read_be_u64(pos));
pos += 8;
reserved.push((offset, size));
if size == 0 {
break;
}
}
let (_, root) = try!(Node::load(buffer, off_dt_struct, off_dt_strings));
Ok(DeviceTree {
version: version,
boot_cpuid_phys: boot_cpuid_phys,
reserved: reserved,
root: root,
})
}
pub fn find<'a>(&'a self, path: &str) -> Option<&'a Node> {
// we only find root nodes on the device tree
if !path.starts_with('/') {
return None;
}
self.root.find(&path[1..])
}
pub fn store<'a>(&'a self) -> Result<Vec<u8>, DeviceTreeError> {
let mut dtb = Vec::new();
let mut strings = StringTable::new();
// Magic
let len = dtb.len();
try!(dtb.write_be_u32(len, MAGIC_NUMBER));
let size_off = dtb.len();
try!(dtb.write_be_u32(size_off, 0)); // Fill in size later
let off_dt_struct = dtb.len();
try!(dtb.write_be_u32(off_dt_struct, 0)); // Fill in off_dt_struct later
let off_dt_strings = dtb.len();
try!(dtb.write_be_u32(off_dt_strings, 0)); // Fill in off_dt_strings later
let off_mem_rsvmap = dtb.len();
try!(dtb.write_be_u32(off_mem_rsvmap, 0)); // Fill in off_mem_rsvmap later
// Version
let len = dtb.len();
try!(dtb.write_be_u32(len, SUPPORTED_VERSION));
// Last comp version
let len = dtb.len();
try!(dtb.write_be_u32(len, COMPAT_VERSION));
// boot_cpuid_phys
let len = dtb.len();
try!(dtb.write_be_u32(len, self.boot_cpuid_phys));
let off_size_strings = dtb.len();
try!(dtb.write_be_u32(off_size_strings, 0)); // Fill in size_dt_strings later
let off_size_struct = dtb.len();
try!(dtb.write_be_u32(off_size_struct, 0)); // Fill in size_dt_struct later
// Memory Reservation Block
try!(dtb.pad(8));
let len = dtb.len();
try!(dtb.write_be_u32(off_mem_rsvmap, len as u32));
for reservation in self.reserved.iter() {
// address
let len = dtb.len();
try!(dtb.write_be_u64(len, reservation.0));
// size
let len = dtb.len();
try!(dtb.write_be_u64(len, reservation.1));
}
// Structure Block
try!(dtb.pad(4));
let structure_start = dtb.len();
try!(dtb.write_be_u32(off_dt_struct, structure_start as u32));
try!(self.root.store(&mut dtb, &mut strings));
try!(dtb.pad(4));
let len = dtb.len();
try!(dtb.write_be_u32(len, OF_DT_END));
let len = dtb.len();
try!(dtb.write_be_u32(off_size_struct, (len - structure_start) as u32));
try!(dtb.write_be_u32(off_size_strings, strings.buffer.len() as u32));
// Strings Block
try!(dtb.pad(4));
let len = dtb.len();
try!(dtb.write_be_u32(off_dt_strings, len as u32));
dtb.extend_from_slice(&strings.buffer);
let len = dtb.len();
try!(dtb.write_be_u32(size_off, len as u32));
Ok(dtb)
}
}
impl Node {
fn load(
buffer: &[u8],
start: usize,
off_dt_strings: usize,
) -> Result<(usize, Node), DeviceTreeError> {
// check for DT_BEGIN_NODE
if try!(buffer.read_be_u32(start)) != OF_DT_BEGIN_NODE {
return Err(DeviceTreeError::ParseError(start));
}
let raw_name = try!(buffer.read_bstring0(start + 4));
// read all the props
let mut pos = align(start + 4 + raw_name.len() + 1, 4);
let mut props = Vec::new();
while try!(buffer.read_be_u32(pos)) == OF_DT_PROP {
let val_size = try!(buffer.read_be_u32(pos + 4)) as usize;
let name_offset = try!(buffer.read_be_u32(pos + 8)) as usize;
// get value slice
let val_start = pos + 12;
let val_end = val_start + val_size;
let val = try!(buffer.subslice(val_start, val_end));
// lookup name in strings table
let prop_name = try!(buffer.read_bstring0(off_dt_strings + name_offset));
props.push((try!(str::from_utf8(prop_name)).to_owned(), val.to_owned()));
pos = align(val_end, 4);
}
// finally, parse children
let mut children = Vec::new();
while try!(buffer.read_be_u32(pos)) == OF_DT_BEGIN_NODE {
let (new_pos, child_node) = try!(Node::load(buffer, pos, off_dt_strings));
pos = new_pos;
children.push(child_node);
}
if try!(buffer.read_be_u32(pos)) != OF_DT_END_NODE {
return Err(DeviceTreeError::ParseError(pos));
}
pos += 4;
Ok((
pos,
Node {
name: try!(str::from_utf8(raw_name)).to_owned(),
props: props,
children: children,
},
))
}
pub fn find<'a>(&'a self, path: &str) -> Option<&'a Node> {
if path == "" {
return Some(self);
}
match path.find('/') {
Some(idx) => {
// find should return the proper index, so we're safe to
// use indexing here
let (l, r) = path.split_at(idx);
// we know that the first char of slashed is a '/'
let subpath = &r[1..];
for child in self.children.iter() {
if child.name == l {
return child.find(subpath);
}
}
// no matching child found
None
}
None => self.children.iter().find(|n| n.name == path),
}
}
pub fn has_prop(&self, name: &str) -> bool {
if let Some(_) = self.prop_raw(name) {
true
} else {
false
}
}
pub fn prop_str<'a>(&'a self, name: &str) -> Result<&'a str, PropError> {
let raw = try!(self.prop_raw(name).ok_or(PropError::NotFound));
let l = raw.len();
if l < 1 || raw[l - 1] != 0 {
return Err(PropError::Missing0);
}
Ok(try!(str::from_utf8(&raw[..(l - 1)])))
}
pub fn prop_raw<'a>(&'a self, name: &str) -> Option<&'a Vec<u8>> {
for &(ref key, ref val) in self.props.iter() {
if key == name {
return Some(val);
}
}
None
}
pub fn prop_u64(&self, name: &str) -> Result<u64, PropError> {
let raw = try!(self.prop_raw(name).ok_or(PropError::NotFound));
Ok(try!(raw.as_slice().read_be_u64(0)))
}
pub fn prop_u32(&self, name: &str) -> Result<u32, PropError> {
let raw = try!(self.prop_raw(name).ok_or(PropError::NotFound));
Ok(try!(raw.as_slice().read_be_u32(0)))
}
pub fn store(
&self,
structure: &mut Vec<u8>,
strings: &mut StringTable,
) -> Result<(), DeviceTreeError> {
try!(structure.pad(4));
let len = structure.len();
try!(structure.write_be_u32(len, OF_DT_BEGIN_NODE));
try!(structure.write_bstring0(&self.name));
for prop in self.props.iter() {
try!(structure.pad(4));
let len = structure.len();
try!(structure.write_be_u32(len, OF_DT_PROP));
// Write property value length
try!(structure.pad(4));
let len = structure.len();
try!(structure.write_be_u32(len, prop.1.len() as u32));
// Write name offset
try!(structure.pad(4));
let len = structure.len();
try!(structure.write_be_u32(len, strings.add_string(&prop.0)));
// Store the property value
structure.extend_from_slice(&prop.1);
}
// Recurse on children
for child in self.children.iter() {
try!(child.store(structure, strings));
}
try!(structure.pad(4));
let len = structure.len();
try!(structure.write_be_u32(len, OF_DT_END_NODE));
Ok(())
}
}
impl From<str::Utf8Error> for PropError {
fn from(_: str::Utf8Error) -> PropError {
PropError::Utf8Error
}
}
impl From<SliceReadError> for PropError {
fn from(e: SliceReadError) -> PropError {
PropError::SliceReadError(e)
}
}
#[cfg(test)]
mod test {
use std::fs;
use std::io::{Read, Write};
use super::*;
#[test]
fn roundtrip() {
// read file into memory
let buf = include_bytes!("../examples/bcm2709-rpi-2-b.dtb");
let original_fdt = DeviceTree::load(buf).unwrap();
let dtb = original_fdt.store().unwrap();
let mut output = fs::OpenOptions::new()
.write(true)
.create(true)
.open("output.dtb")
.unwrap();
output.write_all(&dtb).unwrap();
let mut input = fs::File::open("output.dtb").unwrap();
let mut buf = Vec::new();
input.read_to_end(&mut buf).unwrap();
let generated_fdt = DeviceTree::load(buf.as_slice()).unwrap();
assert!(original_fdt == generated_fdt);
}
}
|
ca5e175307a605e32cd76f9006d6dc9a7a2d371b
|
[
"TOML",
"Rust"
] | 3 |
Rust
|
mbr/device_tree-rs
|
bed843c6f5904abd3bc397df221925c8252478e6
|
b72ad76c4c755b3915b2cab1f5a3b54e658c5e9a
|
refs/heads/master
|
<file_sep><?php
class Sertifikasi_model extends CI_Model
{
public function get_user($username)
{
return $this->db->get_where('user', ['username' => $username])->row_array();
}
public function getAllMahasiswa()
{
return $this->db->get('mahasiswa')->result_array();
}
public function getAllMahasiswaFakultas($fakultas)
{
$this->db->order_by('input_time DESC');
return $this->db->get_where('mahasiswa', ['fakultas' => $fakultas])->result_array();
}
public function deleteMahasiswa($nim)
{
$this->db->where('nim', $nim);
$this->db->delete('mahasiswa');
}
public function insertMahasiswa($query)
{
$this->db->insert('mahasiswa', $query);
}
public function updateMahasiswa($nim, $query)
{
$this->db->where('nim', $nim);
$this->db->update('mahasiswa', $query);
}
public function get_prodi($id_fakultas)
{
return $this->db->get_where('prodi', ['id_fakultas' => $id_fakultas])->result_array();
}
public function get_nama_fakultas($id_fakultas)
{
return $this->db->get_where('fakultas', ['id_fakultas' => $id_fakultas])->row_array();
}
}
<file_sep><?php
defined('BASEPATH') or exit('No direct script access allowed');
class Akademik extends CI_Controller
{
public function index()
{
/* Mencegah Masuk tanpa login */
if (!$this->session->userdata('username')) {
redirect('Account');
} else {
$this->load->model('Sertifikasi_model');
}
/* Pengolahan Data */
$data['username'] = $this->session->userdata('username');
$data['level_akun'] = $this->session->userdata('level_akun');
$data['id_fakultas'] = $this->session->userdata('id_fakultas');
/* Load View */
$this->load->view('akademik/Dashboard', $data);
}
public function mahasiswa()
{
/* Mencegah Masuk tanpa login */
if (!$this->session->userdata('username')) {
redirect('Account');
} else {
$this->load->model('Sertifikasi_model');
}
/* Pengolahan Data */
$data['username'] = $this->session->userdata('username');
$data['level_akun'] = $this->session->userdata('level_akun');
$data['id_fakultas'] = $this->session->userdata('id_fakultas');
$data['data_mahasiswa'] = $this->Sertifikasi_model->getAllMahasiswa();
/* Load View */
$this->load->view('akademik/Data_mahasiswa', $data);
}
}
<file_sep><?php
defined('BASEPATH') or exit('No direct script access allowed');
class TU_Fakultas extends CI_Controller
{
public function index()
{
/* Mencegah Masuk tanpa login */
if (!$this->session->userdata('username')) {
redirect('Account');
} else {
$this->load->model('Sertifikasi_model');
}
/* Pengolahan Data */
$data['username'] = $this->session->userdata('username');
$data['level_akun'] = $this->session->userdata('level_akun');
$data['id_fakultas'] = $this->session->userdata('id_fakultas');
/* Load View */
$this->load->view('tu_fakultas/Dashboard', $data);
}
public function mahasiswa()
{
$this->load->model('Sertifikasi_model');
$this->form_validation->set_rules('checkKonfirmasi', 'Check', 'required');
if ($this->form_validation->run()) {
if ($this->input->post('kodeDelete')) { // Delete
$idDelete = $this->input->post('kodeDelete');
$this->Sertifikasi_model->deleteMahasiswa($idDelete);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Berhasil DELETE Data Mahasiswa.</div>');
redirect('TU_Fakultas/mahasiswa');
} else if ($this->input->post('idTambahMhs')) { // Tambah
$query = [
'nim' => $this->input->post('idTambahMhs'),
'nama' => $this->input->post('namaMhs'),
'alamat' => $this->input->post('alamatMhs'),
'tanggal_lahir' => $this->input->post('lahirMhs'),
'gender' => $this->input->post('genderMhs'),
'agama' => $this->input->post('agamaMhs'),
'fakultas' => $this->input->post('fakultasMhs'),
'prodi' => $this->input->post('prodiMhs')
];
$this->Sertifikasi_model->insertMahasiswa($query);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Berhasil TAMBAH Data Mahasiswa.</div>');
redirect('TU_Fakultas/mahasiswa');
} else if ($this->input->post('idEditMhs')) { // Edit Running Text
$idEdit = $this->input->post('idEditMhs');
$query = [
'nama' => $this->input->post('namaMhs'),
'alamat' => $this->input->post('alamatMhs'),
'tanggal_lahir' => $this->input->post('lahirMhs'),
'gender' => $this->input->post('genderMhs'),
'agama' => $this->input->post('agamaMhs'),
'fakultas' => $this->input->post('fakultasMhs'),
'prodi' => $this->input->post('prodiMhs')
];
$this->Sertifikasi_model->updateMahasiswa($idEdit, $query);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Berhasil EDIT Data Mahasiswa.</div>');
redirect('TU_Fakultas/mahasiswa');
} else {
$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Gagal TAMBAH/EDIT/DELETE Data Mahasiswa.</div>');
redirect('TU_Fakultas/mahasiswa');
}
} else {
/* Mencegah Masuk tanpa login */
if (!$this->session->userdata('username')) {
redirect('Account');
} else {
$this->load->model('Sertifikasi_model');
}
/* Pengolahan Data */
$data['username'] = $this->session->userdata('username');
$data['level_akun'] = $this->session->userdata('level_akun');
$data['id_fakultas'] = $this->session->userdata('id_fakultas');
$data['fakultas'] = $this->Sertifikasi_model->get_nama_fakultas($data['id_fakultas']);
$data['data_mahasiswa'] = $this->Sertifikasi_model->getAllMahasiswaFakultas($data['fakultas']['nama_fakultas']);
$data['prodi_user'] = $this->Sertifikasi_model->get_prodi($data['id_fakultas']);
/* Load View */
$this->load->view('tu_fakultas/Data_mahasiswa', $data);
}
}
}
<file_sep><?php
defined('BASEPATH') or exit('No direct script access allowed');
class Account extends CI_Controller
{
public function index()
{
/* Harus logout terlebih dahulu */
if ($this->session->userdata('username')) {
if ($this->session->userdata('level_akun') == "akademik") {
redirect('Akademik'); // dashboard akademik
} else if ($this->session->userdata('level_akun') == "tu_fakultas") {
redirect('TU_Fakultas'); //dashboard TU
}
}
$this->form_validation->set_rules('username', 'Username', 'required|trim');
$this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>');
if ($this->form_validation->run()) {
$this->pvt_login();
} else {
$this->load->view('account/Login');
}
}
private function pvt_login()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('Sertifikasi_model');
$user = $this->Sertifikasi_model->get_user($username);
if ($user) {
// user ada
// cek password
if ($password == $user['password']) {
$akun = [
'username' => $user['username'],
'level_akun' => $user['level_akun'],
'id_fakultas' => $user['id_fakultas']
];
$this->session->set_userdata($akun);
if ($user['level_akun'] == "akademik") {
redirect('Akademik'); // dashboard akademik
} else {
redirect('TU_Fakultas'); //dashboard TU
}
} else {
$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Mohon maaf PASSWORD salah. Mohon Ulangi lagi!</div>');
redirect('Account');
}
} else {
// user tidak ada
$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Mohon maaf USERNAME tidak ditemukan. Mohon Ulangi lagi!</div>');
redirect('Account');
}
}
public function logout()
{
/* Harus login terlebih dahulu */
if (!$this->session->userdata('username')) {
$this->session->set_flashdata('message', '<div class="alert alert-danger" role="alert">Tidak Ada akun yang login.</div>');
redirect('Account');
}
$this->session->unset_userdata('username');
$this->session->unset_userdata('level_akun');
$this->session->unset_userdata('id_fakultas');
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Berhasil Logout.</div>');
redirect('Account');
}
}
|
174969cd22c85a17c39f42207b55964f9e43ce4a
|
[
"PHP"
] | 4 |
PHP
|
dmgroad/sertifjuniorweb
|
7f62137db3ceb7fce8910b1d9e18098adfbb939c
|
26f49e899968d2f3ecd9d38e30422b84c1274fb2
|
refs/heads/master
|
<repo_name>AstraKiseki/13a-Hackathon<file_sep>/QuoteHangman/QuoteHangman.Core/Domain/Quote.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuoteHangman.Core.Domain
{
public class Quote
{
public string quote { get; set; }
public string author { get; set; }
public string category { get; set; }
public string cat { get; set; }
}
}
<file_sep>/QuoteHangman/QuoteHangman.Core/Services/QuoteRetriever.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using unirest_net.http;
using unirest_net.request;
using Newtonsoft.Json.Linq;
using QuoteHangman.Core.Domain;
using System.IO;
using Newtonsoft.Json;
using System.Net;
namespace QuoteHangman.Core.Services
{
public static class QuoteRetriever
{
public static Quote GetMovieQuote()
{
// 1. Create a HTTP request
var httpRequest = (HttpWebRequest)HttpWebRequest.Create("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies");
// 2. Make this an HTTP POST request. (Remember, GET/POST/UPDATE/DELETE)
httpRequest.Method = "POST";
// 3. Add headers to this HTTP request
httpRequest.Headers.Add("X-Mashape-Key", "<KEY>");
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Accept = "application/json";
// 4. Get our response
var httpResponse = httpRequest.GetResponse();
// 5. Read the response (which is JSON) and turn it into a Quote object.
// 5a. Get the stream from the response
var httpResponseStream = httpResponse.GetResponseStream();
// 5b. Create an object that can read this Stream in an easy way
using (var streamReader = new StreamReader(httpResponseStream))
{
// 5c. Read the JSON
string json = streamReader.ReadToEnd();
// 5d. Deserialize into an object
return JsonConvert.DeserializeObject<Quote>(json);
}
}
public static Quote GetFamousQuote()
{
// 1. Create a HTTP request
var httpRequest = (HttpWebRequest)HttpWebRequest.Create("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous");
// 2. Make this an HTTP POST request. (Remember, GET/POST/UPDATE/DELETE)
httpRequest.Method = "POST";
// 3. Add headers to this HTTP request
httpRequest.Headers.Add("X-Mashape-Key", "<KEY>");
httpRequest.ContentType="application/x-www-form-urlencoded";
httpRequest.Accept = "application/json";
// 4. Get our response
var httpResponse = httpRequest.GetResponse();
// 5. Read the response (which is JSON) and turn it into a Quote object.
// 5a. Get the stream from the response
var httpResponseStream = httpResponse.GetResponseStream();
// 5b. Create an object that can read this Stream in an easy way
using (var streamReader = new StreamReader(httpResponseStream))
{
// 5c. Read the JSON
string json = streamReader.ReadToEnd();
// 5d. Deserialize into an object
return JsonConvert.DeserializeObject<Quote>(json);
}
}
/// Process the quote into a string
}
}
<file_sep>/QuoteHangman/QuoteHangman/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuoteHangman.Core.Services;
namespace QuoteHangman
{
public class Program
{
static int lives = 9;
static string QuoteAnswer = " ";
static string DisplayWord = " ";
static bool gameOver = true;
static List<string> usedLetters = new List<string>();
// Creating the 'stats' needed. Note that the gameOver boolean is reversed. Maybe I should change it to gameOn?
static void ClearData()
{
lives = 9;
QuoteAnswer = " ";
DisplayWord = " ";
gameOver = true;
usedLetters.Clear();
}
// To wipe the slate clean!
static void Main(string[] args)
{
GameStart();
while (lives >= 0)
{
while (gameOver == true)
{
PlayRound();
if (DisplayWord.Equals(QuoteAnswer, StringComparison.OrdinalIgnoreCase))
{
gameOver = false;
if (lives > 0)
{
Console.WriteLine(QuoteAnswer);
Console.WriteLine("Congratulations, you win!");
Console.WriteLine("Would you like to play again? (Y/N)");
string playAgain = Console.ReadLine();
playAgain = playAgain.ToUpper();
bool playAgainChoice = false;
while (playAgainChoice == false)
{
switch (playAgain)
{
case "Y":
playAgainChoice = true;
Console.Clear();
ClearData();
GameStart();
break;
case "N":
playAgainChoice = true;
Console.WriteLine("Cool! Thanks for playing!");
Console.ReadLine();
Environment.Exit(0);
break;
default:
Console.WriteLine("Sorry, that's not a valid answer. Please try again.");
playAgain = Console.ReadLine();
playAgain = playAgain.ToUpper();
break;
}
}
}
}
if (lives == 0)
{
Console.WriteLine("Oh, you are out of lives! That's game over!");
Console.WriteLine("The answer was {0}", QuoteAnswer);
Console.ReadLine();
Console.Clear();
ClearData();
GameStart();
}
}
}
}
public static void GameStart()
{
Console.WriteLine("Hi! Welcome to Hangman!");
Console.WriteLine("This game uses currently uses one of two options to choose a quote to guess! Would you like the quote to be from:");
Console.WriteLine("1. Movies");
Console.WriteLine("2. Someone famous");
string choice = Console.ReadLine();
bool pickedChoice = false;
while (pickedChoice == false)
{
switch (choice)
{
case "1":
/// Movies game
Console.WriteLine("You've chosen a quote from a movie! One moment, please!");
QuoteAnswer = QuoteRetriever.GetMovieQuote().quote.ToLower();
DisplayWord = maskString(QuoteAnswer);
pickedChoice = true;
break;
case "2":
/// Famous
Console.WriteLine("You've chosen someone famous! One moment, please!");
QuoteAnswer = QuoteRetriever.GetFamousQuote().quote.ToLower();
DisplayWord = maskString(QuoteAnswer);
pickedChoice = true;
break;
default:
Console.WriteLine("Not a valid choice. Please select 1 or 2.");
choice = Console.ReadLine();
break;
}
}
return;
}
static string maskString(string input)
{
string[] words = QuoteAnswer.Split(' ');
string DisplayWord = "";
for (int i = 0; i < words.Length; i++)
{
string currentWord = words[i]; // I need to figure out how to auto do the thing for things besides letters.
char[] chars = currentWord.ToCharArray();
for (int j = 0; j < currentWord.Length; j++)
{
if (Char.IsLetter(chars[j])) {
DisplayWord += "-";
}
else
{
DisplayWord += chars[j];
}
}
DisplayWord += " ";
}
DisplayWord = DisplayWord.TrimEnd(); // Or else the two won't look identical at all, due to that one extra space.
return DisplayWord;
}
public static bool PlayRound()
{
Console.WriteLine(DisplayWord);
Console.WriteLine("Enter a letter:");
string letter = Console.ReadLine();
string readletter = letter.ToLower(); // Should I use Ordinal here too?
if (IsThereA(letter))
{
}
else
{
lives--;
Console.WriteLine("Oh no! You've lost a life. You have {0} left.", lives);
}
return false;
}
public static bool IsThereA(string guessLetter) // Credit to DRapp for this
{
if (usedLetters.Contains(guessLetter) == false)
{
int maxlength = QuoteAnswer.Length;
bool anyMatch = false;
for (int i = 0; i < QuoteAnswer.Length; i++)
{
if (QuoteAnswer.Substring(i, 1).Equals(guessLetter))
{
anyMatch = true;
DisplayWord = DisplayWord.Substring(0, i) + guessLetter + DisplayWord.Substring(i + 1);
}
}
usedLetters.Add(guessLetter);
return anyMatch;
}
if (usedLetters.Contains(guessLetter))
{
Console.WriteLine("Oh! You have already used:");
usedLetters.ForEach(item => Console.Write(item + " "));
Console.WriteLine(" ");
}
return true;
}
}
}
|
8f29172af583eab3101e0c96e25ceaa3cf1b6202
|
[
"C#"
] | 3 |
C#
|
AstraKiseki/13a-Hackathon
|
b810c365c2f492080f2cb81b9f94df4f141876a1
|
21d7ea99a677e69d69c4d9a60865504c14969c51
|
refs/heads/main
|
<file_sep># MonumentsApp
In order to install this crud app in ionic/React you should do the following:
1-In the folder api run "npm install" to install all the dependencies.
2-In the root folder run "npm install" to install node modules.
ENJOY :)
<file_sep>const express = require("express");
const formData = require('express-form-data');
const formidable = require('express-formidable');
const cors = require("cors");
const app = express();
//const bodyParser = require("body-parser");
//app.use(bodyParser.urlencoded({ extended: false }))
//app.use(bodyParser.json());
app.use(formData.parse());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
//connect to db
const mysql = require("mysql");
app.use(cors());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mapdb",
});
connection.connect(function (error) {
if (!!error) console.log(error);
else console.log("Database Connected!");
});
//monuments
app.get("/monuments", (req, res) => {
let sql = "SELECT * FROM monument";
let query = connection.query(sql, (err, rows) => {
if (err) throw err;
console.log("made it");
res.send(rows);
});
});
//users
app.get("/users", (req, res) => {
let sql = "SELECT * FROM users";
let query = connection.query(sql, (err, rows) => {
if (err) throw err;
console.log("made it");
res.send(rows);
});
});
app.post("/user/register", (req, res) => {
/* res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
); */
let data = {
nom: req.body.nom,
prenom: req.body.prenom,
email: req.body.email,
numTele: req.body.numTele,
password: <PASSWORD>,
};
res.send(data);
console.log(data);
let sql = "INSERT INTO users SET ?";
let query = connection.query(sql, data, (err, results) => {
console.log(data.nom);
if (err) throw err;
});
});
//Ajout Monument
app.post("/ajout", (req, res) => {
let data = {
nom: req.body.nom,
ville: req.body.ville,
longitude: req.body.longitude,
latitude: req.body.latitude,
};
res.send(data);
console.log(data);
let sql = "INSERT INTO monument SET ?";
let query = connection.query(sql, data, (err, results) => {
console.log(data.nom);
if (err) throw err;
});
});
app.listen(3000, () => {
console.log("Listening at port 3000...");
});
|
4add73841a56725d143ca4c78de06b59fadfacf0
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Soulaymane-BenElArabi/MonumentsApp
|
084d7321f8750236501d39b2746df34cb5feeb5e
|
ce6cbf850e631c0e808e009f70ff084b606a3369
|
refs/heads/master
|
<repo_name>notblisy/SimpleControllersBuild-a-Box<file_sep>/Simple_Controllers_-_Build-a-Box_-_Version_1.0.ino
#include "Nintendo.h"
/* This code uses the Nicohood Library
* Use this code at your own risk
* Code written by Simple Controllers and this code is open source.
* Meaning its free to share, improve on, or anything you like!
* Just remember to mention you used my code!
* Version 2.0 I just suck at github
*/
//This makes the controller bidirection data line on pin number8
CGamecubeConsole GamecubeConsole(8); //Defines a "Gamecube Console" sending data to the console on pin 8
Gamecube_Data_t d = defaultGamecubeData; //Structure for data to be sent to console
//This is needed but you don't need a controller on pin 7
CGamecubeController GamecubeController1(7);
// Ints that will change when the SWITCH push button is pushed and increases a counter for profile switching.
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
//This is the pinout of the controller. Can be changed to your liking. I may have mixed up some of the tilt pins but you can change that physically in your build or through the code. Just do test runs along the way.
const int A = 22;
const int B = 24;
const int X = 26;
const int Y = 30;
const int Z = 35;
const int START = 31;
int R = 34; // This is not a const int anymore because it needs to be overwitten for profile switching.
int L = 36;
int RLIGHT = 28; // This is not a const int anymore because it needs to be overwitten for profile switching.
//This is the value of analog shielding 74 is lightest possible on gamecube. It varies from gamecube to dolphin no idea why.
int RLIGHTv = 74; // This is not a const int anymore because it needs to be overwitten for profile switching.
int LLIGHT = 28;
int LLIGHTv = 74;
const int LEFT = 38;
const int RIGHT = 39;
const int UP = 40;
const int DOWN = 41;
//NEW!! Fixed the mixup of X1 and X2 buttons, they now correspond to the correct buttons.
//If you are updating from 1.0/1.1 you might have to change the internal pins on your box or just swap the pin numbers here.
const int X1 = 44;
const int X2 = 45;
const int Y1 = 46;
const int Y2 = 47;
//This is analog tilt modifiers and can be changed to your liking
const int X1v = 27;
const int X2v = 55;
const int X3v = 73;
int Y1v = 27; // This is not a const int anymore because it needs to be overwitten for profile switching.
int Y2v = 53; // This is not a const int anymore because it needs to be overwitten for profile switching.
const int Y3v = 74;
const int CLEFT = 48;
const int CRIGHT = 49;
const int CUP = 50;
const int CDOWN = 51;
//THIS IS THE SWITCH/BUTTON TO TOGGLE MODIFIERS (X1, X2, Y1, Y2) TO DPAD
const int SWITCH = 12;
void setup()
{
//This is establishing the pin assignments up there to input pins
pinMode(A, INPUT_PULLUP);
pinMode(B, INPUT_PULLUP);
pinMode(X, INPUT_PULLUP);
pinMode(Y, INPUT_PULLUP);
pinMode(Z, INPUT_PULLUP);
pinMode(START, INPUT_PULLUP);
pinMode(R, INPUT_PULLUP);
pinMode(L, INPUT_PULLUP);
pinMode(RLIGHT, INPUT_PULLUP);
pinMode(LLIGHT, INPUT_PULLUP);
pinMode(LEFT, INPUT_PULLUP);
pinMode(RIGHT, INPUT_PULLUP);
pinMode(UP, INPUT_PULLUP);
pinMode(DOWN, INPUT_PULLUP);
pinMode(X1, INPUT_PULLUP);
pinMode(X2, INPUT_PULLUP);
pinMode(Y1, INPUT_PULLUP);
pinMode(Y2, INPUT_PULLUP);
pinMode(CLEFT, INPUT_PULLUP);
pinMode(CRIGHT, INPUT_PULLUP);
pinMode(CUP, INPUT_PULLUP);
pinMode(CDOWN, INPUT_PULLUP);
pinMode(SWITCH, INPUT_PULLUP);
//This is needed to run the code.
GamecubeController1.read();
}
void loop()
{
//This resets and establishes all the values after the controller sends them to the console and helps with initial "zeroing"
int pinA = 0;
int pinB = 0;
int pinX = 0;
int pinY = 0;
int pinZ = 0;
int pinSTART = 0;
int pinR = 0;
int pinL = 0;
int pinRLIGHT = 0;
int pinLLIGHT = 0;
int pinLEFT = 0;
int pinRIGHT = 0;
int pinUP = 0;
int pinDOWN = 0;
int pinX1 = 0;
int pinX2 = 0;
int pinY1 = 0;
int pinY2 = 0;
int pinCLEFT = 0;
int pinCRIGHT = 0;
int pinCUP = 0;
int pinCDOWN = 0;
int pinxAxisC = 128;
int pinyAxisC = 128;
int pinxAxis = 128;
int xmod = 0;
int pinyAxis = 128;
int rightOne = 0;
int leftOne = 0;
int downOne = 0;
int pinSWITCH = 0;
//This reads control stick as neutral when both left/right or up/down is pressed at the same time. Also sets parameters for the diffrent analog tilt modifiers IE: X1+X2 = X3
//UPDATE: NOW CORRESPONDS TO PROPER SMASHBOX ANGLES
if (digitalRead(LEFT) == HIGH && digitalRead(RIGHT) == LOW){
pinxAxis = 128+86;
if (digitalRead(X1) == LOW && digitalRead(X2) == HIGH)pinxAxis = X1v + 128;
if (digitalRead(X1) == HIGH && digitalRead(X2) == LOW)pinxAxis = X2v + 128;
if (digitalRead(X1) == LOW && digitalRead(X2) == LOW)pinxAxis = X3v + 128;
rightOne = 1;
}
if (digitalRead(LEFT) == LOW && digitalRead(RIGHT) == HIGH){
pinxAxis = 128-86;
if (digitalRead(X1) == LOW && digitalRead(X2) == HIGH)pinxAxis = 128 - X1v;
if (digitalRead(X1) == HIGH && digitalRead(X2) == LOW)pinxAxis = 128 - X2v;
if (digitalRead(X1) == LOW && digitalRead(X2) == LOW)pinxAxis = 128 - X3v;
leftOne = 1;
}
if (digitalRead(DOWN) == HIGH && digitalRead(UP) == LOW){
pinyAxis = 128+86;
if (digitalRead(Y1) == LOW && digitalRead(Y2) == HIGH)pinyAxis = 128 + Y1v;
if (digitalRead(Y1) == HIGH && digitalRead(Y2) == LOW)pinyAxis = 128 + Y2v;
if (digitalRead(Y1) == LOW && digitalRead(Y2) == LOW)pinyAxis = 128 + Y3v;
}
if (digitalRead(DOWN) == LOW && digitalRead(UP) == HIGH){
pinyAxis = 128-86;
if (digitalRead(Y1) == LOW && digitalRead(Y2) == HIGH)pinyAxis = 128 - Y1v;
if (digitalRead(Y1) == HIGH && digitalRead(Y2) == LOW)pinyAxis = 128 - Y2v;
if (digitalRead(Y1) == LOW && digitalRead(Y2) == LOW)pinyAxis = 128 - Y3v;
downOne = 1;
}
//NEW: Axe Shield Drops
if (digitalRead(X1) == HIGH && digitalRead(X2) == HIGH && digitalRead(Y1) == HIGH && digitalRead(Y2) == HIGH && downOne == 1 && leftOne == 1){
pinxAxis = 128-80;
pinyAxis = 128-78;
}
if (digitalRead(X1) == HIGH && digitalRead(X2) == HIGH && digitalRead(Y1) == HIGH && digitalRead(Y2) == HIGH && downOne == 1 && rightOne == 1){
pinxAxis = 128+80;
pinyAxis = 128-78;
}
//Reads CStick pins, same logic as controlstick values.
if (digitalRead(CLEFT) == HIGH && digitalRead(CRIGHT) == LOW)pinxAxisC = 255;
if (digitalRead(CLEFT) == LOW && digitalRead(CRIGHT) == HIGH)pinxAxisC = 0;
if (digitalRead(CDOWN) == HIGH && digitalRead(CUP) == LOW)pinyAxisC = 255;
if (digitalRead(CDOWN) == LOW && digitalRead(CUP) == HIGH)pinyAxisC = 0;
if (digitalRead(A) == LOW)pinA = 1;
if (digitalRead(B) == LOW)pinB = 1;
if (digitalRead(X) == LOW)pinX = 1;
if (digitalRead(Y) == LOW)pinY = 1;
if (digitalRead(Z) == LOW)pinZ = 1;
if (digitalRead(START) == LOW)pinSTART = 1;
//This is for analog shield
if (digitalRead(RLIGHT) == LOW)pinRLIGHT = RLIGHTv;
if (digitalRead(LLIGHT) == LOW)pinLLIGHT = LLIGHTv;
//This is for digital shield
if (digitalRead(R) == LOW)pinR = 1;
if (digitalRead(L) == LOW)pinL = 1;
if (digitalRead(SWITCH) == LOW)pinSWITCH = 1;
d.report.dup = 0;
d.report.dright = 0;
d.report.ddown = 0;
d.report.dleft = 0;
// This code causes the values of Y1v, Y2v, RLIGHT, R, and RLIGHTv to switch based on a buttonstate counter.
// Essentially, if SWITCH is pushed, it increments buttonPushCounter by 1, and if it's a multiple of 3 it switches to
// Y1v and Y2v have appropriate angles for Project M shield drop and utilt. If it's a multiple of 4 it switches
// Y1v and Y2v for uptilt purposes in Smash Ult, then it switches R and RLIGHTs position on the pinout, because
// Smash ultimate cannot read hard press shield. Then, it sets RLIGHTv to 255, which is the hardest light shield press
// So you can get a normal shield. More profiles can be added by doing more multiples.
buttonState = digitalRead(SWITCH);
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
//This is the Project M profile I have set up.
if (buttonPushCounter % 3 == 0) {
Y2v = 70;
Y1v = 53;
//This is the smash Ultimate profile I have setup.
} else if(buttonPushCounter % 4 == 0){
Y2v = 70;
Y1v = 43;
RLIGHT = 34;
R = 28;
RLIGHTv = 255;
LLIGHT = 36;
L = 28;
LLIGHTv = 255;
}//This is the monster hunter / steam generic controller. It can't read the hard press and I have enabled to dpad since most modern games require it.
else if(buttonPushCounter % 5 == 0){
Y2v = 70;
Y1v = 43;
RLIGHT = 34;
R = 28;
RLIGHTv = 255;
LLIGHT = 36;
L = 28;
LLIGHTv = 255;
if(digitalRead(Y2) == LOW)d.report.dleft = 1;
if(digitalRead(X2) == LOW)d.report.ddown = 1;
if(digitalRead(Y1) == LOW)d.report.dup = 1;
if(digitalRead(X1) == LOW)d.report.dright = 1;
} else {
//This is the melee profile, it is both the default and if you're on a mod that's not 3/4/5 then it'll be melee.
Y2v = 53;
Y1v = 27;
RLIGHT = 28;
R = 34;
RLIGHTv = 74;
LLIGHT = 28;
LLIGHTv = 74;
L = 36;
}
// These are commented out because it conflicts with how I have set up the profile switcher.
// Considering making the taunt button the light shield button and making modifier button cause light shield.
// if (digitalRead(SWITCH) == LOW)pinSWITCH = 1;
// d.report.dup = 0;
// d.report.dright = 0;
// d.report.ddown = 0;
// d.report.dleft = 0;
//NEW WHEN SWITCH/BUTTON ON PIN 12 IS PRESSED/ACTIVATED SWAPS X1,X2,Y1,Y2 TO DPAD
//if (pinSWITCH == 1){
// if(digitalRead(X1) == LOW)d.report.dleft = 1;
// if(digitalRead(X2) == LOW)d.report.ddown = 1;
//if(digitalRead(Y1) == LOW)d.report.dup = 1;
// if(digitalRead(Y2) == LOW)d.report.dright = 1;
// }
//reports data
d.report.a = pinA;
d.report.b = pinB;
d.report.x = pinX;
d.report.y = pinY;
d.report.z = pinZ;
d.report.start = pinSTART;
d.report.r = pinR;
d.report.l = pinL;
d.report.left = pinRLIGHT;
d.report.right = pinLLIGHT;
d.report.xAxis = pinxAxis;
d.report.yAxis = pinyAxis;
d.report.cxAxis = pinxAxisC;
d.report.cyAxis = pinyAxisC;
//sends the complied data to console when console polls for the input
GamecubeConsole.write(d);
}
<file_sep>/README.md
Fork of Simple Controllers build-a-box that has a push button to switch between four profiles and have the button layout to match Haxxs B0XX.
Instructions: Press 2 times for project M, 3 times for Brawl/Smash4/Ult, and 4 for Steam generic.
One for melee, one for PM, one for Brawl/4/Ult, and the final is for steam generic controller and I use it for monster hunter world.
This is because Melee and PM use different shield drop values / up tilt values, Brawl onwards games can't read the hard press of the GC controller and different uptilt values, and finally for steam generic I have a mode where the dpad is always enabled and the angle modifiers are removed because many modern games require the dpad.
This code utilizes the Nicohood Library.
See tutorial at: https://docs.google.com/document/d/1ndV4E_w2ThAv9LpbjEzRDWwMj0uBWB9YqbvkHV35X5w/edit?usp=sharing
Demo Video at: https://www.youtube.com/watch?v=5h7IPojhzTc
Reddit Link: https://www.reddit.com/r/SSBM/comments/5mebc5/how_to_make_your_own_smash_box/

|
1b5c6a5eaec242969597dc91644d9ee226f55cd5
|
[
"Markdown",
"C++"
] | 2 |
C++
|
notblisy/SimpleControllersBuild-a-Box
|
80f018c2e1a79c8e765bf2dd6bacd6479ee29602
|
9697401b1c1ee601b72ab3775780fff248c538c9
|
refs/heads/master
|
<repo_name>adfmadis/Monopoly<file_sep>/Game_Files/13 - printmonopolyboard.cpp
//
// printmonopolyboard.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "13 - printmonopolyboard.h"
#include "2 - square.h"
#include "14 - player.h"
using namespace std;
PrintMonopolyBoard *PrintMonopolyBoard::instance=0;
PrintMonopolyBoard *PrintMonopolyBoard::getInstance() {
if (!instance) {
instance = new PrintMonopolyBoard;
atexit(removePrintMonopolyBoard);
}
return instance;
}
void PrintMonopolyBoard::removePrintMonopolyBoard() {
delete instance;
}
PrintMonopolyBoard::PrintMonopolyBoard() {}
void PrintMonopolyBoard::update(vector<Square*> squares, vector<Player*> players, int numPlayers) {
for (int i = 0; i < 40; i++) {
Squares.push_back(squares[i]);
}
for (int i = 0; i < numPlayers; i++) {
Players.push_back(players[i]);
}
for (int i = numPlayers; i < 8; i++) {
Players.push_back(NULL);
}
this->numPlayers = numPlayers;
}
int PrintMonopolyBoard::getNumPlayers() {
return numPlayers;
}
void PrintMonopolyBoard::printHouseHotel(int squareNum) {
int housesNum = Squares[squareNum]->getNumHouses();
int hotelsNum = Squares[squareNum]->getNumHotels();
if (housesNum == 0 && hotelsNum == 0) {
cout << " |";
}
else if (housesNum == 1) {
cout << " h |";
}
else if (housesNum == 2) {
cout << " h h |";
}
else if (housesNum == 3) {
cout << " h h h |";
}
else if (housesNum == 4) {
cout << " h h h h |";
}
else if (hotelsNum == 1) {
cout << " H |";
}
}
void PrintMonopolyBoard::printPlayersOnSquare1(int squareNum) {
cout << " ";
int numPOS = Squares[squareNum]->getNumPlayers(); // (numPOS = number of players on square)
for (int i = 0; i < min(4,numPOS); i++) {
cout << Squares[squareNum]->getNthPlayerPiece(i) << " ";
}
int numSpaces = 4 - numPOS;
for (int i = 0; i < numSpaces; i++) {
cout << " ";
}
cout << " |";
}
void PrintMonopolyBoard::printPlayersOnSquare2(int squareNum) {
cout << " ";
int numPOS = Squares[squareNum]->getNumPlayers(); // (numPOS = number of players on square)
for (int i = 4; i < numPOS; i++) {
cout << Squares[squareNum]->getNthPlayerPiece(i) << " ";
}
int numSpaces = 8 - numPOS;
for (int i = 0; i < min(4,numSpaces); i++) {
cout << " ";
}
cout << " |";
}
void PrintMonopolyBoard::printPlayersInJail1() {
cout << " ";
int numPOS = Squares[10]->getNumPlayers(); // (numPOS = number of players on square)
int playerNum;
int printNum = 0;
for (int i = 0; i < min(4,numPOS); i++) {
string piece = Squares[10]->getNthPlayerPiece(i);
for (int i = 0; i < numPlayers; i++) {
if (Players[i]->getBoardPiece() == piece) {
playerNum = i;
break;
}
}
if (Players[playerNum]->getInJail()) {
printNum++;
cout << Squares[10]->getNthPlayerPiece(i) << " ";
}
}
int numSpaces = 4 - printNum;
for (int i = 0; i < numSpaces; i++) {
cout << " ";
}
cout << " |";
}
void PrintMonopolyBoard::printPlayersInJail2() {
cout << " ";
int numPOS = Squares[10]->getNumPlayers(); // (numPOS = number of players on square)
int playerNum;
int printNum = 0;
for (int i = 4; i < numPOS; i++) {
string piece = Squares[10]->getNthPlayerPiece(i);
for (int i = 0; i < numPlayers; i++) {
if (Players[i]->getBoardPiece() == piece) {
playerNum = i;
break;
}
}
if (Players[playerNum]->getInJail()) {
printNum++;
cout << Squares[10]->getNthPlayerPiece(i) << " ";
}
}
int numSpaces = 8 - printNum;
for (int i = 0; i < min(4,numSpaces); i++) {
cout << " ";
}
cout << " |";
}
void PrintMonopolyBoard::printPlayersJustVisiting1() {
cout << " ";
int numPOS = Squares[10]->getNumPlayers(); // (numPOS = number of players on square)
int playerNum;
int printNum = 0;
for (int i = 0; i < min(4,numPOS); i++) {
string piece = Squares[10]->getNthPlayerPiece(i);
for (int i = 0; i < numPlayers; i++) {
if (Players[i]->getBoardPiece() == piece) {
playerNum = i;
break;
}
}
if (!Players[playerNum]->getInJail()) {
printNum++;
cout << Squares[10]->getNthPlayerPiece(i) << " ";
}
}
int numSpaces = 4 - printNum;
for (int i = 0; i < numSpaces; i++) {
cout << " ";
}
cout << " |";
}
void PrintMonopolyBoard::printPlayersJustVisiting2() {
cout << " ";
int numPOS = Squares[10]->getNumPlayers(); // (numPOS = number of players on square)
int playerNum;
int printNum = 0;
for (int i = 4; i < numPOS; i++) {
string piece = Squares[10]->getNthPlayerPiece(i);
for (int i = 0; i < numPlayers; i++) {
if (Players[i]->getBoardPiece() == piece) {
playerNum = i;
break;
}
}
if (!Players[playerNum]->getInJail()) {
printNum++;
cout << Squares[10]->getNthPlayerPiece(i) << " ";
}
}
int numSpaces = 8 - printNum;
for (int i = 0; i < min(4,numSpaces); i++) {
cout << " ";
}
cout << " |";
}
void PrintMonopolyBoard::print() {
cout << "______________________________________________________________________________________________________________________________________________________________________" << endl;
cout << "|FREE PARKING |"; printHouseHotel(31);
cout << "CHANCE |"; printHouseHotel(33); printHouseHotel(34);
cout << "B. & O. |"; printHouseHotel(36); printHouseHotel(37);
cout << "WATER WORKS |"; printHouseHotel(39);
cout << "GO TO JAIL |" << endl;
cout << "| |______________| |______________|______________|RAILROAD |______________|______________| |______________| |" << endl;
cout << "| |KENTUCKY | |INDIANA AVENUE|ILLINOIS | |ATLANTIC |VERMONT AVENUE| |MARVINS | |" << endl;
cout << "| |AVENUE | | |AVENUE | |AVENUE | | |GARDENS | |" << endl << "|";
printPlayersOnSquare1(21); printPlayersOnSquare1(22); printPlayersOnSquare1(23); printPlayersOnSquare1(24); printPlayersOnSquare1(25);
printPlayersOnSquare1(26); printPlayersOnSquare1(27); printPlayersOnSquare1(28); printPlayersOnSquare1(29); printPlayersOnSquare1(30);
printPlayersOnSquare1(31);
cout << endl << "|";
printPlayersOnSquare2(21); printPlayersOnSquare2(22); printPlayersOnSquare2(23); printPlayersOnSquare2(24); printPlayersOnSquare2(25);
printPlayersOnSquare2(26); printPlayersOnSquare2(27); printPlayersOnSquare2(28); printPlayersOnSquare2(29); printPlayersOnSquare2(30);
printPlayersOnSquare2(31);
cout << endl;
cout << "| | $220 | | $220 | $240 | $200 | $260 | $260 | $150 | $280 | |" << endl;
cout << "|______________|______________|______________|______________|______________|______________|______________|______________|______________|______________|______________|" << endl;
cout << "|"; printHouseHotel(19);
cout << " ";
cout << "|"; printHouseHotel(31);
cout << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|NEW YORK |";
cout << " ";
cout << "|PACIFIC AVENUE|" << endl;
cout << "|AVENUE |";
cout << " ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(19);
cout << " ";
cout << "|"; printPlayersOnSquare1(31);
cout << endl;
cout << "|"; printPlayersOnSquare2(19);
cout << " ";
cout << "|"; printPlayersOnSquare2(31);
cout << endl;
cout << "| $200 |";
cout << " ";
cout << "| $300 |" << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|"; printHouseHotel(18);
cout << " _________________________________ ";
cout << "|"; printHouseHotel(32);
cout << endl;
cout << "|______________|";
cout << " | | ";
cout << "|______________|" << endl;
cout << "|TENNESSEE |";
cout << " | | ";
cout << "|NORTH CAROLINA|" << endl;
cout << "|AVENUE |";
cout << " | | ";
cout << "|AVENUE |" << endl;
cout << "|"; printPlayersOnSquare1(18);
cout << " | COMMUNITY CHEST | ";
cout << "|"; printPlayersOnSquare1(32);
cout << endl;
cout << "|"; printPlayersOnSquare2(18);
cout << " | | ";
cout << "|"; printPlayersOnSquare2(32);
cout << endl;
cout << "| $180 |";
cout << " | | ";
cout << "| $300 |";
cout << endl;
cout << "|______________|";
cout << " |_________________________________| ";
cout << "|______________|" << endl;
cout << "|COMMUNITY |";
cout << " ";
cout << "|COMMUNITY |" << endl;
cout << "|CHEST |";
cout << " ";
cout << "|CHEST |" << endl;
cout << "| |";
cout << " ";
cout << "| |" << endl;
cout << "| |";
cout << " ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(17);
cout << " ";
cout << "|"; printPlayersOnSquare1(33);
cout << endl;
cout << "|"; printPlayersOnSquare2(17);
cout << " ";
cout << "|"; printPlayersOnSquare2(33);
cout << endl;
cout << "| |";
cout << " ";
cout << "| |" << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|"; printHouseHotel(16);
cout << " ";
cout << "|"; printHouseHotel(34); cout << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|<NAME> |";
cout << " ";
cout << "|PENNSYLVANIA |" << endl;
cout << "|PLACE |";
cout << " ";
cout << "|AVENUE |" << endl;
cout << "|"; printPlayersOnSquare1(16);
cout << " ";
cout << "|"; printPlayersOnSquare1(34);
cout << endl;
cout << "|"; printPlayersOnSquare2(16);
cout << " ____ ____ __________ ___ ___ __________ ________ __________ ___ ____ ____ ";
cout << "|"; printPlayersOnSquare2(34);
cout << endl;
cout << "| $180 |";
cout << " | \\/ | | | | \\ | | | | | \\ | | | | \\ \\ / / ";
cout << "| $320 |";
cout << endl;
cout << "|______________|";
cout << " | | | | | \\ | | | | | ___ \\ | | | | \\ \\/ / ";
cout << "|______________|" << endl;
cout << "|PENNSYLVANIA |";
cout << " | | | __ | | \\| | | __ | | | | | | __ | | | \\ / ";
cout << "|SHORT |" << endl;
cout << "|RAILROAD |";
cout << " | | | | | | | | | | | | | |___| | | | | | | | \\ / ";
cout << "|LINE |" << endl;
cout << "| |";
cout << " | |\\/| | | | | | | | | | | | | / | | | | | | \\ / ";
cout << "| |" << endl;
cout << "| |";
cout << " | | | | | | | | | | | | | | | _____/ | | | | | | | | ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(15);
cout << " | | | | | | | | | | | | | | | | | | | | | | | | ";
cout << "|"; printPlayersOnSquare1(35);// cout << "CHANCE |" << endl;
cout << endl;
cout << "|"; printPlayersOnSquare2(15);
cout << " | | | | | | | | | | | | | | | | | | | | | | | | ";
cout << "|"; printPlayersOnSquare2(35);
cout << endl;
cout << "| $200 |";
cout << " | | | | | |__| | | | | |__| | | | | |__| | | | | | ";
cout << "| $200 |" << endl;
cout << "|______________|";
cout << " | | | | | | | |\\ | | | | | | | | |______ | | ";
cout << "|______________|" << endl;
cout << "|"; printHouseHotel(14);
cout << " | | | | | | | | \\ | | | | | | | | | | | ";
cout << "|CHANCE |" << endl;
cout << "|______________|";
cout << " |___| |___| |__________| |___| \\___| |__________| |___| |__________| |__________| |__| ";
cout << "| |" << endl;
cout << "|VIRGINIA |";
cout << " ";
cout << "| |" << endl;
cout << "|AVENUE |";
cout << " ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(14);
cout << " ";
cout << "|"; printPlayersOnSquare1(36);
cout << endl;
cout << "|"; printPlayersOnSquare2(14);
cout << " ";
cout << "|"; printPlayersOnSquare2(36);
cout << endl;
cout << "| $160 |";
cout << " ";
cout << "| |" << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|"; printHouseHotel(13);
cout << " ";
cout << "|"; printHouseHotel(37);
cout << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|STATES AVENUE |";
cout << " ";
cout << "|PARK PLACE |" << endl;
cout << "| |";
cout << " ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(13);
cout << " ";
cout << "|"; printPlayersOnSquare1(37);
cout << endl;
cout << "|"; printPlayersOnSquare2(13);
cout << " ";
cout << "|"; printPlayersOnSquare2(37);
cout << endl;
cout << "| $140 |";
cout << " ";
cout << "| $350 |" << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|ELECTRIC |";
cout << " _________________________________ ";
cout << "|LUXURY TAX |" << endl;
cout << "|COMPANY |";
cout << " | | ";
cout << "| |" << endl;
cout << "| |";
cout << " | | ";
cout << "| |" << endl;
cout << "| |";
cout << " | | ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(12);
cout << " | CHANCE | ";
cout << "|"; printPlayersOnSquare1(38);
cout << endl;
cout << "|"; printPlayersOnSquare2(12);
cout << " | | ";
cout << "|"; printPlayersOnSquare2(38);
cout << endl;
cout << "| $150 |";
cout << " | | ";
cout << "| PAY $100 |" << endl;
cout << "|______________|";
cout << " |_________________________________| ";
cout << "|______________|" << endl;
cout << "|"; printHouseHotel(11);
cout << " ";
cout << "|"; printHouseHotel(39);
cout << endl;
cout << "|______________|";
cout << " ";
cout << "|______________|" << endl;
cout << "|<NAME> |";
cout << " ";
cout << "|BOARDWALK |" << endl;
cout << "|PLACE |";
cout << " ";
cout << "| |" << endl;
cout << "|"; printPlayersOnSquare1(11);
cout << " ";
cout << "|"; printPlayersOnSquare1(39);
cout << endl;
cout << "|"; printPlayersOnSquare2(11);
cout << " ";
cout << "|"; printPlayersOnSquare2(39);
cout << endl;
cout << "| $140 |";
cout << " ";
cout << "| $400 |" << endl;
cout << "|______________|";
cout << "______________________________________________________________________________________________________________________________________";
cout << "|______________|" << endl;
cout << "| IN JAIL |";
printHouseHotel(9); printHouseHotel(8);
cout << "CHANCE |";
printHouseHotel(6);
cout << "READING |INCOME TAX |";
printHouseHotel(3);
cout << "COMMUNITY |";
printHouseHotel(1);
cout << "COLLECT $200 |" << endl;
cout << "|"; printPlayersInJail1();
cout << "______________|______________| |______________|RAILROAD | |______________|CHEST |______________|SALARY AS YOU |" << endl;
cout << "|"; printPlayersInJail2();
cout << "CONNECTICUT |VERMONT AVENUE| |ORIENTAL | | |BALTIC AVENUE | |MEDITERANEAN |PASS GO |" << endl;
cout << "|______________|AVENUE | | |AVENUE | | | | |AVENUE | |" << endl;
cout << "|JUST VISITING |";
printPlayersOnSquare1(9); printPlayersOnSquare1(8); printPlayersOnSquare1(7); printPlayersOnSquare1(6);
printPlayersOnSquare1(5); printPlayersOnSquare1(4); printPlayersOnSquare1(3); printPlayersOnSquare1(2); printPlayersOnSquare1(1);
printPlayersOnSquare1(0);
cout << endl << "|";
printPlayersJustVisiting1(); printPlayersOnSquare2(9); printPlayersOnSquare2(8); printPlayersOnSquare2(7); printPlayersOnSquare2(6);
printPlayersOnSquare2(5); printPlayersOnSquare2(4); printPlayersOnSquare2(3); printPlayersOnSquare2(2); printPlayersOnSquare2(1);
printPlayersOnSquare2(0);
cout << endl;
cout << "|"; printPlayersJustVisiting2();
cout << " $120 | $100 | | $100 | $200 | PAY $200 | $60 | | $60 | |" << endl;
cout << "|______________|______________|______________|______________|______________|______________|______________|______________|______________|______________|______________|" << endl;
}<file_sep>/Game_Files/11 - runmonopolygame.cpp
//
// runmonopolygame.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "11 - runmonopolygame.h"
#include "2 - square.h"
#include "3 - ownablesquare.h"
#include "4 - unownablesquare.h"
#include "5 - streetsquare.h"
#include "6 - railroadsquare.h"
#include "7 - utilitysquare.h"
//#include "8 - cardsquare.h"
//#include "9 - cornersquare.h"
//#include "10 - taxsquare.h"
#include "12 - monopolyboard.h"
#include "13 - printmonopolyboard.h"
#include "14 - player.h"
using namespace std;
/* ---------------------------------------------------------------------------------------
int stringToInt()
purpose: translates a string containing a number into an int, and returns that int
--------------------------------------------------------------------------------------- */
int stringToInt(string s) {
istringstream si(s);
int i;
si >> i;
return i;
}
/* ---------------------------------------------------------------------------------------
bool isValidNum(string s)
purpose: returns a boolean, true if the string s only contains a number, false otherwise
--------------------------------------------------------------------------------------- */
bool isValidNum(string s) {
int length = s.length();
for (int i = 0; i < length; i++) {
if (s[i] > 57 || s[i] < 48) {
cout << "Number of players input is invalid." << endl;
return false;
}
}
int i = stringToInt(s);
if (i >= 2 && i <= 8) {
return true;
}
else {
cout << "Number of players input is not between 2 and 8." << endl;
return false;
}
}
/* ---------------------------------------------------------------------------------------
string nthWord(string s, int n)
purpose: returns the nth word
--------------------------------------------------------------------------------------- */
string nthWord(string s, int n) {
int spacePosn;
for (int i = 1; i < n; i++) {
int length = s.length();
while(s[spacePosn] != ' ') {
spacePosn++;
}
s = s.substr(spacePosn,length-1);
spacePosn=0;
}
while (s[spacePosn] != ' ') {
spacePosn++;
}
s = s.substr(0,spacePosn);
return s;
}
/* ---------------------------------------------------------------------------------------
Player* ownersPlayerClass()
purpose: returns the player class for the owner of the square
--------------------------------------------------------------------------------------- */
Player* ownersPlayerClass(string owner, vector<Player*> players, int numPlayers) {
if (owner == "BANK") {
return NULL;
}
for (int i = 0; i < numPlayers; i++) {
if (owner == players[i]->getBoardPiece()) {
return players[i];
}
}
return NULL;
}
RunMonopolyGame::RunMonopolyGame(MonopolyBoard* mb, PrintMonopolyBoard* pmb): MB(mb), PMB(pmb) {}
void RunMonopolyGame::setRMG() {
MB->setRMG(this);
}
void RunMonopolyGame::setupBoard(vector<Player*> players, vector<Square*> squares, int numPlayers) {
for (int i = 0; i < numPlayers; i++) {
int posn = players[i]->getPosn();
squares[posn]->addPlayer(players[i]->getBoardPiece());
}
MB->setup(squares,players,numPlayers);
}
bool RunMonopolyGame::readInSquares(istream& stringIn, vector<Player*> players, int numPlayers) { //ADD INPUT TESTING, SO THAT INVALID DATA CANT BE INPUT
vector<Square*> squares;
Square* square = new UnownableSquare("Collect Go");
squares.push_back(square);
string owner;
int numberOfHouses;
int numberOfHotels;
bool monopoly = false;
string monopolyOwner;
Player* currentPlayer;
// read in info on Mediterranean Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Mediterranean Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Community Chest");
squares.push_back(square);
// read in info on Baltic Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Baltic Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Income Tax");
squares.push_back(square);
// read in info on Reading Railroad
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new RailroadSquare("Reading Railroad",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Oriental Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Oriental Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Chance");
squares.push_back(square);
// read in info on Vermont Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Vermont Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Connecticut Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Connecticut Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("In Jail");
squares.push_back(square);
// read in info on St. Charles Place
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("St. Charles Place",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Electric Company
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new UtilitySquare("Electric Company",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on States Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("States Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Virginia Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Virginia Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Pennsylvania Railroad
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new RailroadSquare("Pennsylvania Railroad",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on St. James Place
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("St. James Place",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Community Chest");
squares.push_back(square);
// read in info on Tennessee Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Tennessee Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on New York Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("New York Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Free Parking");
squares.push_back(square);
// read in info on Kentucky Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Kentucky Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Chance");
squares.push_back(square);
// read in info on Indiana Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Indiana Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Illionois Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Illinois Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on B. & O. Railroad
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new RailroadSquare("B. & O. Railroad",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Atlantic Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Atlantic Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Vermont Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Vermont Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Water Works
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new UtilitySquare("Water Works",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on <NAME>
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("<NAME>",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Go To Jail");
squares.push_back(square);
// read in info on Pacific Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Pacific Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on North Carolina Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("North Carolina Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Community Chest");
squares.push_back(square);
// read in info on Pennsylvania Avenue
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Pennsylvania Avenue",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
// read in info on Short Line
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new RailroadSquare("Short Line",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Chance");
squares.push_back(square);
// read in info on Park Place
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Park Place",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
square = new UnownableSquare("Luxury Tax");
squares.push_back(square);
// read in info on Boardwalk
stringIn >> owner;
stringIn >> numberOfHouses;
stringIn >> numberOfHotels;
currentPlayer = ownersPlayerClass(owner,players,numPlayers);
square = new StreetSquare("Boardwalk",currentPlayer,numberOfHouses,numberOfHotels);
squares.push_back(square);
setupBoard(players,squares,numPlayers);
return true;
}
/* ---------------------------------------------------------------------------------------
bool loadSetup(istream& stringIn)
purpose: returns true if the setup process is finished without an error, and false otherwise. The function reads in the amount of players and each player's information using stringIn, to allow for reading in from either the keyboard or a file. If any of the player information read in is invalid then a false is returned. Square information is also read in through a helper function readInSquares.
--------------------------------------------------------------------------------------- */
bool RunMonopolyGame::loadSetup(istream& stringIn) {
string s;
stringIn >> s;
vector<Player*> P;
string playersName;
string boardPiece;
int money;
int posn;
int numPlayers;
bool inJail = false;
int turnsInJail = 0;
if (isValidNum(s)) {
numPlayers = stringToInt(s);
for (int i = 0; i < numPlayers; i++) { //reads in information on each of the players, alerts user if any of the inputs are invalid.
stringIn >> playersName;
stringIn >> boardPiece;
stringIn >> money;
if (cin.fail() || money < 0) {
cout << "Invalid money input for " << playersName << "." << endl;
return true;
}
stringIn >> posn;
if (cin.fail() || posn >= 40 || posn < 0) {
cout << "Invalid board position input for " << playersName << "." << endl;
return true;
}
if (posn == 10) {
stringIn >> inJail;
if (cin.fail()) {
cout << "Invalid in-jail input for " << playersName << "." << endl;
return true;
}
if (inJail) {
stringIn >> turnsInJail;
if (cin.fail() || turnsInJail < 0 || turnsInJail > 2) {
cout << "Invalid turns-in-jail input for " << playersName << "." << endl;
return true;
}
}
}
Player* p = new Player(playersName, boardPiece, money, posn, inJail, turnsInJail);
P.push_back(p);
}
bool squaresRead = readInSquares(stringIn,P,numPlayers);
if (!squaresRead) {
return false;
}
return true;
}
else {
return false;
}
}
void RunMonopolyGame::normalSetup() {
string names[40] = {"Collect Go", "Mediterranean Avenue", "Community Chest", "Baltic Avenue", "Income Tax", "Reading Railroad", "Oriental Avenue", "Chance", "Vermont Avenue", "Connecticut Avenue", "In Jail", "St. Charles Place", "Electric Company", "States Avenue", "Virginia Avenue", "Pennsylvania Railroad", "St. James Place", "Community Chest", "Tennessee Avenue", "New York Avenue", "Free Parking", "Kentucky Avenue", "Chance", "Indiana Avenue", "Illinois Avenue", "B. & O. Railroad", "Atlantic Avenue", "Vermont Avenue", "Water Works", "Marvins Gardens", "Go To Jail", "Pacific Avenue", "North Carolina Avenue", "Community Chest", "Pennsylvania Avenue", "Short Line", "Chance", "Park Place", "Luxury Tax", "Boardwalk"};
vector<Square*> squares;
for (int i = 0; i < 40; i++) { // add the 40 default squares to the game
Square* square;
string name = names[i];
if (name == "Chance" || name == "Community Chest" || name == "Collect Go" || name == "In Jail" || name == "Go To Jail" || name == "Free Parking" || name == "Income Tax" || name == "Luxury Tax") {
square = new UnownableSquare(name);
}
else if (name == "Reading Railroad" || name == "Pennsylvania Railroad" || name == "B. & O. Railroad" || name == "Short Line") {
square = new RailroadSquare(name);
}
else if (name == "Electric Company" || name == "Water Works") {
square = new UtilitySquare(name);
}
else {
square = new StreetSquare(name);
}
squares.push_back(square);
//ADD SQUARE
}
string boardPiece;
string playersName;
vector<Player*> P;
string pieces[8] = {"","","","","","","",""};
int numPlayers;
cout << "How many players will play the game? (2-8)" << endl;
cin >> numPlayers;
while (cin.fail() || ((numPlayers >= 2 && numPlayers <= 8) == false)) { // repeat reading in for the total of players until a valid integer is given
cin.clear();
cin.ignore();
cout << "Not an integer between 2 and 8, input another number." << endl;
cin >> numPlayers;
}
for (int i = 0; i < numPlayers; i++) { // read in all of the player's boardPieces
cout << "What is Player " << i+1 <<"'s Name?" << endl;
cin >> playersName;
cout << "What will " << playersName << "'s board piece/character be?" << endl;
cout << "Pick from W (Wheelbarrow), B (Battleship), R (Racecar), T (Thimble), O (Old-style shoe), S (Scottie dog), H (Top hat), or C (Cat)." << endl;
while (cin >> boardPiece) { // repeat reading in for a boardPiece until a valid character is given
if (cin.fail() || ((boardPiece == "W" || boardPiece == "B" || boardPiece == "R" || boardPiece == "T" || boardPiece == "O" || boardPiece == "S" || boardPiece == "H" || boardPiece == "C") == false)) { // evaluate boardPiece for invalid input
cout << "Not a valid character. Input one of 'W', 'B', 'R', 'T', 'O', 'S', 'H', or 'C'." << endl;
if (cin.fail()) {
cin.clear();
cin.ignore();
}
}
else if (find(pieces,pieces+8,boardPiece) != pieces+8) {
cout << "This board piece has already been chosen by a previous player. Please pick a different piece." << endl;
}
else if (boardPiece == "W" || boardPiece == "B" || boardPiece == "R" || boardPiece == "T" || boardPiece == "O" || boardPiece == "S" || boardPiece == "H" || boardPiece == "C") { // valid input
pieces[i] = boardPiece;
break;
}
}
// initialize player with just name/piece, will automatically to be set to "Collect Go" square, with 1500$, add to array
Player* p = new Player(playersName, boardPiece);
P.push_back(p);
// add each player to the "Collect Go" square
}
for (int i = 0; i < numPlayers; i++) {
squares[0]->addPlayer(P[i]->getBoardPiece());
}
MB->setup(squares,P,numPlayers);
}
void RunMonopolyGame::updatePrintBoard() { //can make more efficient by not updating every square/playe r, every time
PMB->update(MB->getSquaresVector(),MB->getPlayersVector(),MB->getNumPlayers());
}
void RunMonopolyGame::printBoard() {
PMB->print();
}
void RunMonopolyGame::playGame() {
int playerX = 0;
int q = 0;
int* quit = &q;
int numPlayers = MB->getNumPlayers();
while (!*quit && !cin.eof()) { //game ends when quit = 1
cout << "playerX = " << playerX << endl;
MB->playersTurn(playerX,quit);
PMB->print();
if (MB->getNumPlayers() != numPlayers) { //updates numPlayers when a player has been removed from game
numPlayers = MB->getNumPlayers();
}
if (playerX == numPlayers-1) {
playerX = 0;
}
else {
playerX++;
}
}
// GB->clearSquares();
// GB->clearPlayers();
}
<file_sep>/Game_Files/6 - railroadsquare.h
//
// railroadsquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____railroadsquare__
#define ____railroadsquare__
#include <stdio.h>
#include <string>
#include "3 - ownablesquare.h"
#include <iostream>
class RailroadSquare: public OwnableSquare {
public:
RailroadSquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~RailroadSquare();
// returns a boolean representing if the square has been mortgaged or not
bool isMortgaged();
/* ---------------------------------------------------------------------------------------
int getPaymentCost()
purpose: returns an int for how much rent costs when you land on a railroad square. rent cost is taken from the rentcost array, and the position in the array is selected by how many total railroad squares are owned by the owner of the current railroad square
--------------------------------------------------------------------------------------- */
int getPaymentCost();
/* ---------------------------------------------------------------------------------------
void mortgage()
purpose: sets the square to mortgaged, and transfers the amount of the mortgageCost variable to the owner
--------------------------------------------------------------------------------------- */
void mortgage();
/* ---------------------------------------------------------------------------------------
void unmortgage()
purpose: sets the square to unmortgaged, and transfers the amount of the mortgageCost variable away from the owner
--------------------------------------------------------------------------------------- */
void unmortgage();
};
#endif /* defined(____railroadsquare__) */
<file_sep>/Game_Files/11 - runmonopolygame.h
//
// runmonopolygame.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____runmonopolygame__
#define ____runmonopolygame__
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
class MonopolyBoard;
class PrintMonopolyBoard;
class Player;
class Square;
class RunMonopolyGame {
MonopolyBoard* MB;
PrintMonopolyBoard* PMB;
bool isTestingMode;
public:
RunMonopolyGame(MonopolyBoard* mb, PrintMonopolyBoard* pmb);
/* ---------------------------------------------------------------------------------------
void setRMG()
purpose: calls the function in runMonopolyGame which updates the runMonopolyGame with current board data
--------------------------------------------------------------------------------------- */
void setRMG();
/* ---------------------------------------------------------------------------------------
void readInSquares(istream& stringIn, vector<Player*> players, int numPlayers)
purpose: returns a boolean representing whether the process of reading in the squares information has been completed or not. The function reads in information for 28 squares: 22 street squares, 4 railroad squares, and 2 utility squares. All readins use stringIn, as this gies us the capability to read in from either a file or from the keyboard. The players vector is used every time the owner of the square is read in and it is not equal to 'bank', as we find the player's object by searching matching it's board piece piece to the one that we read in. We then use that class in the square's initialization.
--------------------------------------------------------------------------------------- */
bool readInSquares(std::istream& stringIn, std::vector<Player*> players, int numPlayers);
/* ---------------------------------------------------------------------------------------
bool loadSetup(istream& stringIn)
purpose: returns true if the setup process is finished without an error, and false otherwise. The function reads in the amount of players and each player's information using stringIn, to allow for reading in from either the keyboard or a file. If any of the player information read in is invalid then a false is returned. Square information is also read in through a helper function readInSquares.
--------------------------------------------------------------------------------------- */
bool loadSetup(std::istream& stringIn);
/* ---------------------------------------------------------------------------------------
void normalSetup()
purpose: Sets up each of the 40 squares into their default position that is expected at the start of a normal game. Also reads in information from the keyboard on how many player's there will be and reads in information from the keyboard on the necessary information for each of the players
--------------------------------------------------------------------------------------- */
void normalSetup();
/* ---------------------------------------------------------------------------------------
void updatePrintBoard()
purpose: updates the view class to contain the necessary information from the model class
--------------------------------------------------------------------------------------- */
void updatePrintBoard();
/* ---------------------------------------------------------------------------------------
void printBoard()
purpose: prints the board out through the view class
--------------------------------------------------------------------------------------- */
void printBoard();
/* ---------------------------------------------------------------------------------------
void setupBoard(vector<Player*> players, vector<Square*> squares, int numPlayers)
purpose: adds each player to the board of which it's board piece lies, and then calls the set up in the monopolyboard class
--------------------------------------------------------------------------------------- */
void setupBoard(std::vector<Player*> players, std::vector<Square*> squares, int numPlayers);
/* ---------------------------------------------------------------------------------------
void playGame()
purpose: playGame loops through each player in the player vector, where each player plays their turn. The vector is adjusted when players go bankrupt, going down in size by 1. The game is over when the *quit variable = true. This occurs when there is only 1 valid player left (the game is over), or when the user manually inputs 'quit' as a command.
--------------------------------------------------------------------------------------- */
void playGame();
};
#endif /* defined(____runmonopolygame__) */
<file_sep>/Game_Files/10 - taxsquare.cpp
//
// taxsquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "10 - taxsquare.h"
using namespace std;
TaxSquare::TaxSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): UnownableSquare(name,owner,numberOfHouses,numberOfHotels) {}
TaxSquare::~TaxSquare() {}
<file_sep>/Game_Files/9 - cornersquare.cpp
//
// cornersquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "9 - cornersquare.h"
using namespace std;
CornerSquare::CornerSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): UnownableSquare(name,owner,numberOfHouses,numberOfHotels) {}
CornerSquare::~CornerSquare() {}
<file_sep>/Game_Files/5 - streetsquare.cpp
//
// streetsquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "5 - streetsquare.h"
#include "14 - player.h"
using namespace std;
std::string monopoly;
int numberOfHouses;
int numberOfHotels;
bool mortgaged=false;
int purchaseCost;
int rentCost[6];
void StreetSquare::setRentCost(int rc[6]) {
for (int i = 0; i < 6; i++) {
rentCost[i] = rc[i];
}
}
StreetSquare::StreetSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): OwnableSquare(name,owner,numberOfHouses,numberOfHotels) {
/* sets up initial information for each of the 22 street squares. streetsquare is a subclass of ownablesquare which is a subclass of square (square -> ownablesquare -> streetsquare), where streetsquare represents 22 of the 40 squares on the board */
if (name == "Mediterranean Avenue") {
group = "purple";
code = "mediterraneanavenue";
purchaseCost = 60;
mortgageCost = 30;
houseCost = 50;
int rc[6] = {2,10,30,90,160,250};
setRentCost(rc);
}
else if (name == "Baltic Avenue") {
group = "purple";
code = "balticavenue";
purchaseCost = 60;
mortgageCost = 30;
houseCost = 50;
int rc[6] = {4,20,60,180,320,450};
setRentCost(rc);
}
else if (name == "Oriental Avenue") {
group = "light green";
code = "orientalavenue";
purchaseCost = 100;
mortgageCost = 50;
houseCost = 50;
int rc[6] = {6,30,90,270,400,550};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "light green";
code = "vermontavenue";
purchaseCost = 100;
mortgageCost = 50;
houseCost = 50;
int rc[6] = {6,30,90,270,400,550};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "light green";
code = "connecticutavenue";
purchaseCost = 120;
mortgageCost = 60;
houseCost = 50;
int rc[6] = {8,40,100,300,450,600};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "violet";
code = "stcharlesplace";
purchaseCost = 140;
mortgageCost = 70;
houseCost = 100;
int rc[6] = {10,50,150,450,625,750};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "violet";
code = "statesavenue";
purchaseCost = 140;
mortgageCost = 70;
houseCost = 100;
int rc[6] = {10,50,150,450,625,750};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "violet";
code = "virginiaavenue";
purchaseCost = 160;
mortgageCost = 80;
houseCost = 100;
int rc[6] = {12,60,180,500,700,900};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "orange";
code = "stjamesplace";
purchaseCost = 180;
mortgageCost = 90;
houseCost = 100;
int rc[6] = {14,70,200,550,750,950};
setRentCost(rc);
}
else if (name == "T<NAME>venue") {
group = "orange";
code = "tennesseeavenue";
purchaseCost = 180;
mortgageCost = 90;
houseCost = 100;
int rc[6] = {14,70,200,550,750,950};
setRentCost(rc);
}
else if (name == "New York Avenue") {
group = "orange";
code = "newyorkavenue";
purchaseCost = 200;
mortgageCost = 100;
houseCost = 100;
int rc[6] = {16,80,220,600,800,1000};
setRentCost(rc);
}
else if (name == "Kentucky Avenue") {
group = "red";
code = "kentuckyavenue";
purchaseCost = 220;
mortgageCost = 110;
houseCost = 150;
int rc[6] = {18,90,250,700,875,1050};
setRentCost(rc);
}
else if (name == "Indiana Avenue") {
group = "red";
code = "indianaavenue";
purchaseCost = 220;
mortgageCost = 110;
houseCost = 150;
int rc[6] = {18,90,250,700,875,1050};
setRentCost(rc);
}
else if (name == "Illinois Avenue") {
group = "red";
code = "illinoisavenue";
purchaseCost = 240;
mortgageCost = 120;
houseCost = 150;
int rc[6] = {20,100,300,750,925,1100};
setRentCost(rc);
}
else if (name == "Atlantic Avenue") {
group = "yellow";
code = "atlanticavenue";
purchaseCost = 260;
mortgageCost = 130;
houseCost = 150;
int rc[6] = {22,110,330,800,975,1150};
setRentCost(rc);
}
else if (name == "Vermont Avenue") {
group = "yellow";
code = "vermontavenue";
purchaseCost = 260;
mortgageCost = 130;
houseCost = 150;
int rc[6] = {22,110,330,800,975,1150};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "yellow";
code = "marvinsgardens";
purchaseCost = 280;
mortgageCost = 140;
houseCost = 150;
int rc[6] = {24,120,360,850,1025,1200};
setRentCost(rc);
}
else if (name == "Pacific Avenue") {
group = "dark green";
code = "pacificavenue";
purchaseCost = 300;
mortgageCost = 150;
houseCost = 200;
int rc[6] = {26,130,390,900,1100,1275};
setRentCost(rc);
}
else if (name == "North Carolina Avenue") {
group = "dark green";
code = "northcarolinaavenue";
purchaseCost = 300;
mortgageCost = 150;
houseCost = 200;
int rc[6] = {26,130,390,900,1100,1275};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "dark green";
code = "pennsylvaniaavenue";
purchaseCost = 320;
mortgageCost = 160;
houseCost = 200;
int rc[6] = {28,150,450,1000,1200,1400};
setRentCost(rc);
}
else if (name == "<NAME>") {
group = "dark blue";
code = "parkplace";
purchaseCost = 350;
mortgageCost = 175;
houseCost = 200;
int rc[6] = {35,175,500,1100,1300,1500};
setRentCost(rc);
}
else if (name == "Boardwalk") {
group = "dark blue";
code = "boardwalk";
purchaseCost = 400;
mortgageCost = 200;
houseCost = 200;
int rc[6] = {50,200,600,1400,1700,2000};
setRentCost(rc);
}
}
StreetSquare::~StreetSquare() {}
bool StreetSquare::isMortgaged() {
return mortgaged;
}
int StreetSquare::getPaymentCost() {
if (numberOfHotels == 1) {
return rentCost[5];
}
else {
return rentCost[numberOfHouses];
}
}
void StreetSquare::mortgage() {
if (mortgaged == true) {
cout << "This square has already been mortgaged." << endl;
}
else {
mortgaged = true;
owner->changeMoney(mortgageCost);
owner->changeValue(-mortgageCost);
}
}
void StreetSquare::unmortgage() {
if (mortgaged == false) {
cout << "This square is not mortgaged so you cannot unmortgage it." << endl;
}
else if (owner->getMoney() < mortgageCost) {
cout << "You do not have enough money to unmortgage this property. Try again when you have more than $" << mortgageCost << "." << endl;
}
else {
mortgaged = false;
owner->changeMoney(-mortgageCost);
owner->changeValue(mortgageCost);
}
}
<file_sep>/Game_Files/6 - railroadsquare.cpp
//
// railroadsquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "6 - railroadsquare.h"
#include "14 - player.h"
using namespace std;
RailroadSquare::RailroadSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): OwnableSquare(name,owner,numberOfHouses,numberOfHotels) {
/* sets up initial information for each of the 4 railroad squares. railroadsquare is a subclass of ownablesquare which is a subclass of square (square -> ownablesquare -> railroadsquare), where railroadsquare represents 4 of the 40 squares on the board */
purchaseCost = 200;
mortgageCost = 100;
rentCost[0] = 25;
rentCost[1] = 50;
rentCost[2] = 100;
rentCost[4] = 200;
if (name == "Reading Railroad") {
code = "readingrailroad";
}
else if (name == "Pennsylvania Railroad") {
code = "pennsylvaniarailroad";
}
else if (name == "B. & O. Railroad") {
code = "b&orailroad";
}
else if (name == "Short Line") {
code = "shortline";
}
}
RailroadSquare::~RailroadSquare() {}
bool RailroadSquare::isMortgaged() {
return mortgaged;
}
int RailroadSquare::getPaymentCost() {
return rentCost[owner->getRailroadsOwned()-1];
}
void RailroadSquare::mortgage() {
if (mortgaged == true) {
cout << "This square has already been mortgaged." << endl;
}
else {
mortgaged = true;
owner->changeMoney(mortgageCost);
owner->changeValue(-mortgageCost);
}
}
void RailroadSquare::unmortgage() {
if (mortgaged == false) {
cout << "This square is not mortgaged so you cannot unmortgage it." << endl;
}
else if (owner->getMoney() < mortgageCost) {
cout << "You do not have enough money to unmortgage this property. Try again when you have more than $" << mortgageCost << "." << endl;
}
else {
mortgaged = false;
owner->changeMoney(-mortgageCost);
owner->changeValue(mortgageCost);
}
}
<file_sep>/Game_Files/1 - main.cpp
//
// main.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include "12 - monopolyboard.h"
#include "13 - printmonopolyboard.h"
#include "11 - runmonopolygame.h"
using namespace std;
int main(int argc, char *argv[]) {
/*
in main, we allow for 2 command line variables to be input in the original execute call. They are "-load x" and "-testing".
'-load x': reads in information on players and squares from file x, where x is a text file in the folder containing the all of the .cpp and .h files. See readme for further info on the file 'x'.
'-testing': allows for the user to dictate how many squares a player moves in their turn. See readme for info on how to use in-game.
*/
bool invalidCmmdLine = false;
bool testing = false;
bool issetupcomplete = true;
// sets up model (MonopolyBoard) , controller (RunMonopolyGame) , and view (PrintMonopolyBoard) classes for the MVC scheme
MonopolyBoard *mb = MonopolyBoard::getInstance();
PrintMonopolyBoard *pmb = PrintMonopolyBoard::getInstance();
RunMonopolyGame monopoly(mb,pmb);
monopoly.setRMG();
ifstream userInput("cin");
if (argc == 1) { // setup when there are no extra command line variables
monopoly.normalSetup();
}
else if (argc == 2) { //setup when there is 1 extra command line variable
string cmmdLineVar1(argv[1]);
if (cmmdLineVar1 == "-load") {
issetupcomplete = monopoly.loadSetup(cin);
}
else if (cmmdLineVar1 == "-testing") {
monopoly.normalSetup();
testing = true;
}
}
else if (argc == 3) { //setup when there are 2 extra command line variables
string cmmdLineVar1(argv[1]);
string cmmdLineVar2(argv[2]);
if ((cmmdLineVar1 == "-load" && cmmdLineVar2 == "-testing") || (cmmdLineVar1 == "-testing" || cmmdLineVar2 == "-load")) {
issetupcomplete = monopoly.loadSetup(cin);
testing = true;
}
else if (cmmdLineVar1 == "-load") {
cout << "file check..." << endl;
cout << cmmdLineVar2 << endl;
ifstream fileCheck(cmmdLineVar2); //used to check if the given filename represents a valid file
cout << fileCheck << endl;
if (!fileCheck) {
//game won't start if the given filename isn't a valid file
invalidCmmdLine = true;
}
else {
issetupcomplete = monopoly.loadSetup(fileCheck);
}
}
}
else if (argc == 4) { //setup when there are 3 extra command line variables ("-load x -testing" OR "-testing -load x")
string cmmdLineVar1(argv[1]);
string cmmdLineVar2(argv[2]);
string cmmdLineVar3(argv[3]);
if (cmmdLineVar1 == "-load" && cmmdLineVar3 == "-testing") {
ifstream fileCheck(cmmdLineVar2); //used to check if the given filename represents a valid file
if (!fileCheck) {
//game won't start if the given filename isn't a valid file
invalidCmmdLine = true;
}
else {
issetupcomplete = monopoly.loadSetup(fileCheck);
}
}
else if (cmmdLineVar1 == "-testing" && cmmdLineVar2 == "-load") {
ifstream fileCheck(cmmdLineVar3); //used to check if the given filename represents a valid file
if (!fileCheck) {
//game won't start if the given filename isn't a valid file
invalidCmmdLine = true;
}
else {
issetupcomplete = monopoly.loadSetup(fileCheck);
}
}
testing = true;
}
if (invalidCmmdLine) {
cout << "The line given through the command line is invalid for this program. Feel free to try again." << endl;
}
if (issetupcomplete) { // play game if no failure occurs in the setup process
mb->setIsTestingMode(testing);
monopoly.updatePrintBoard();
monopoly.printBoard();
monopoly.playGame();
}
return 0;
}<file_sep>/README.md
# Monopoly
Monopoly game in C++, playable through the command line
**Start Game**
Download all .cpp and .h files and put them in 1 folder, navigate to that folder in terminal and then call **g++ *.cpp** followed by **./a.out**
**Game Moves**
- ‘roll’: if the player can roll, the player rolls two dice, moves the sum of the two dice and takes action on the square they landed on.
- ‘next’: if the player cannot roll, gives control to the next player.
- ‘trade *name* *give* *receive*’: offers a trade to *name* (can either be another player’s name or boardPiece) with the current player offering give and requesting receive, where give and receive are either amounts of money or a property name. Responses are accept and reject. There are 3 types of trades: money for square, square for money, square for square.
Example trade calls:
- ‘trade B 500 balticavenue’
- ‘trade B balticavenue 500’
- ‘trade B balticavenue b&orailroad’
- ‘improve buy/sell *property*’: attempts to buy or sell a house/hotel for property.
(after buying 4 houses on 1 squre, if you complete another buy, the square now has a hotel)
- ‘mortgage *property*’: attempts to mortgage property.
- ‘unmortgage *property*’: attempts to unmortgage property.
- ‘bankrupt’: player declares bankruptcy. This command is only available when a player must pay more money then they currently have.
- assets’: displays the assets of the current player. Does not work if the player is deciding how to pay Tuition.
*property* or *give*/*receive* when they are properties are represented by a squares code, where each squares code is it’s name with no capitalization, spaces, or punctuation. Baltic Avenue = ‘balticavenue’, B. & O. Railroad = ‘b&orailroad’, Water Works = ‘waterworks’, etc.
**Command Line Options**
**‘-load file’**
reads in from ‘file’ (if file variable doesn’t exist then you read in from command line) in this format:
*"numPlayers
player1 boardPiece money position
player2 boardPiece money position
……
owner houses hotels
owner houses hotels
……"* (‘owner houses hotels’ repeats 26 times, in order of all ownable squares on the board)
(SEE EXAMPLE LOAD FILE)
After reading in all the variables, play resumes with the player who’s info was input first
**‘-testing’**
The only difference is an adaptation of roll. This roll will now call **roll die1 die2** OR **roll movetotal**. The player will either move the sum of *die1* and *die2*, where each is between 1 and 6, inclusive or move the amount of *movetotal* where it can be any number 0 or greater.
<file_sep>/Game_Files/7 - utilitysquare.cpp
//
// utilitysquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "7 - utilitysquare.h"
#include "14 - player.h"
using namespace std;
UtilitySquare::UtilitySquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): OwnableSquare(name,owner,numberOfHouses,numberOfHotels) {
/* sets up initial information for each of the 2 utility squares. utilitysquare is a subclass of ownablesquare which is a subclass of square (square -> ownablesquare -> utilitysquare), where railroadsquare represents 2 of the 40 squares on the board */
purchaseCost = 150;
if (name == "Electric Company") {
code = "electriccompany";
}
else if (name == "Water Works") {
code = "waterworks";
}
}
UtilitySquare::~UtilitySquare() {}
bool UtilitySquare::isMortgaged() {
return false;
}
void UtilitySquare::printDice(int d) {
if (d == 1) { cout << "_______" << endl; cout << "| |" << endl; cout << "| * |" << endl; cout << "|_____|" << endl; }
else if (d == 2) { cout << "_______" << endl; cout << "| * |" << endl; cout << "| |" << endl; cout << "|___*_|" << endl; }
else if (d == 3) { cout << "_______" << endl; cout << "| * |" << endl; cout << "| * |" << endl; cout << "|___*_|" << endl; }
else if (d == 4) { cout << "_______" << endl; cout << "|* *|" << endl; cout << "| |" << endl; cout << "|*___*|" << endl; }
else if (d == 5) { cout << "_______" << endl; cout << "|* *|" << endl; cout << "| * |" << endl; cout << "|*___*|" << endl; }
else if (d == 6) { cout << "_______" << endl; cout << "|* *|" << endl; cout << "|* *|" << endl; cout << "|*___*|" << endl; }
}
int UtilitySquare::getPaymentCost() {
int utilitiesOwned = owner->getUtilitiesOwned();
int times;
if (utilitiesOwned == 1) {
times = 4;
}
else if (utilitiesOwned == 2) {
times = 10;
}
int d1;
int d2;
int rollTotal;
int seed = 0;
if (!seed) {
srand(time(NULL));
}
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
printDice(d1);
printDice(d2);
rollTotal = d1 + d2;
return rollTotal*times;
}
void UtilitySquare::mortgage() {
cout << "Can't mortgage a utility property." << endl;
}
void UtilitySquare::unmortgage() {
cout << "Can't unmortgage a utility property." << endl;
}
<file_sep>/Game_Files/2 - square.h
//
// square.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____square__
#define ____square__
#include <stdio.h>
#include <string>
#include "14 - player.h"
class Player;
class Square {
protected:
std::string name;
std::string code;
int numPlayers;
std::string Players[8];
Player* currentPlayer;
Player* owner;
std::string group;
int numberOfHouses;
int numberOfHotels;
bool mortgaged;
int purchaseCost;
int rentCost[6];
int houseCost;
int mortgageCost;
public:
Square(std::string name, Player* owner, int numberOfHouses, int numberOfHotels);
virtual ~Square();
/* ---------------------------------------------------------------------------------------
void addPlayer(string boardPiece)
purpose: adds a player's board piece to a square when it lands on that square
--------------------------------------------------------------------------------------- */
void addPlayer(std::string boardPiece);
/* ---------------------------------------------------------------------------------------
void removePlayer(string boardPiece)
purpose: removes a player's board piece from the square when it leaves that square to move to a new square
--------------------------------------------------------------------------------------- */
void removePlayer(std::string boardPiece);
//returns int for the number of players that are currently on the square
int getNumPlayers();
//returns string for the board piece of the (n-1)th player on the square
std::string getNthPlayerPiece(int n);
//returns string for the name of the square
std::string getSquareName();
//returns string for the code for the square (usually the name without caps or spaces)
std::string getCode();
//returns int for the amount of houses on the square
int getNumHouses();
//returns int for the amount of hotels on the square
int getNumHotels();
//returns the price of a house on the square
int getHouseCost();
/* ---------------------------------------------------------------------------------------
void addHouse()
purpose: removes a player's board piece from the square when it leaves that square to move to a new square
--------------------------------------------------------------------------------------- */
void addHouse();
/* ---------------------------------------------------------------------------------------
void removeHouse()
purpose: removes a player's board piece from the square when it leaves that square to move to a new square
--------------------------------------------------------------------------------------- */
void removeHouse();
//returns string for the board piece of the player who owns the square
std::string getOwnerBoardPiece();
//returns int for the cost of buying the square
int getPurchaseCost();
//returns int for the amount given in cash for mortgaging the square if you own it
int getMortgageCost();
//returns string for the group (colour) of which the square is a part of
std::string getGroup();
virtual bool isOwnable()=0;
virtual bool isBought()=0;
virtual bool isMortgaged()=0;
virtual int getPaymentCost()=0;
virtual void mortgage()=0;
virtual void unmortgage()=0;
virtual void setOwner(Player* newOwner)=0;
//virtual void payOwner()=0;
};
#endif /* defined(____square__) */
<file_sep>/Game_Files/8 - cardsquare.h
//
// cardsquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____cardsquare__
#define ____cardsquare__
#include <stdio.h>
#include <string>
#include "4 - unownablesquare.h"
class CardSquare: public UnownableSquare {
public:
CardSquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~CardSquare();
};
#endif /* defined(____cardsquare__) */
<file_sep>/Game_Files/4 - unownablesquare.cpp
//
// unownablesquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "4 - unownablesquare.h"
using namespace std;
UnownableSquare::UnownableSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): Square(name,owner,numberOfHouses,numberOfHotels) {}
UnownableSquare::~UnownableSquare() {}
bool UnownableSquare::isOwnable() {
return false;
}
bool UnownableSquare::isBought() {
return false;
}
bool UnownableSquare::isMortgaged() {
return false;
}
int UnownableSquare::getPaymentCost() {
return 0;
}
void UnownableSquare::mortgage() {
cout << "Can't mortgage an unownable property." << endl;
}
void UnownableSquare::unmortgage() {
cout << "Can't unmortgage an unownable property." << endl;
}
void UnownableSquare::setOwner(Player* newOwner) {}<file_sep>/Game_Files/4 - unownablesquare.h
//
// unownablesquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____unownablesquare__
#define ____unownablesquare__
#include <stdio.h>
#include "2 - square.h"
#include <string>
#include <iostream>
class UnownableSquare: public Square {
public:
UnownableSquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~UnownableSquare();
//returns a boolean representing if the square is allowed to be owned or not
bool isOwnable();
//returns false, this function is only for ownable squares
bool isBought();
//returns false, this function is only for ownable squares
bool isMortgaged();
// returns 0, this function is only for ownable squares
int getPaymentCost();
// doesn't do anything, this function is only for street/railroad squares
void mortgage();
// doesn't do anything, this function is only for street/railroad squares
void unmortgage();
// doesn't do anything, this function is only for ownable squares
void setOwner(Player* newOwner);
};
#endif /* defined(____unownablesquare__) */
<file_sep>/Game_Files/9 - cornersquare.h
//
// cornersquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____cornersquare__
#define ____cornersquare__
#include <stdio.h>
#include <string>
#include "4 - unownablesquare.h"
class CornerSquare: public UnownableSquare {
public:
CornerSquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~CornerSquare();
};
#endif /* defined(____cornersquare__) */
<file_sep>/Game_Files/7 - utilitysquare.h
//
// utilitysquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____utilitysquare__
#define ____utilitysquare__
#include <stdio.h>
#include <string>
#include "3 - ownablesquare.h"
#include <iostream>
class UtilitySquare: public OwnableSquare {
public:
UtilitySquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~UtilitySquare();
// returns a boolean representing if the square has been mortgaged or not
bool isMortgaged();
/* ---------------------------------------------------------------------------------------
void printDice(int d)
purpose: prints a visual representation of 1 dice, where the dice shows a value of d
--------------------------------------------------------------------------------------- */
void printDice(int d);
/* ---------------------------------------------------------------------------------------
int getPaymentCost()
purpose: returns an int for how much rent costs when you land on a utility square. rent cost is decided by rolling the dice and paying x-times the total roll amount, where x is based on how many of the utilities, the current utility owner owns
--------------------------------------------------------------------------------------- */
int getPaymentCost();
// doesn't do anything, this function is only for street/railroad squares
void mortgage();
// doesn't do anything, this function is only for street/railroad squares
void unmortgage();
};
#endif /* defined(____utilitysquare__) */
<file_sep>/Game_Files/14 - player.h
//
// player.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____player__
#define ____player__
#include <stdio.h>
#include <string>
class Player {
std::string playerName;
std::string boardPiece; string
int posn;
int money;
int value;
bool inJail;
int turnsInJail;
int getOutOfJailFreeCard;
int railroadsOwned;
int utilitiesOwned;
int propertiesOwned;
int purple;
int lightgreen;
int violet;
int orange;
int red;
int yellow;
int darkgreen;
int darkblue;
public:
Player(std::string playerName, std::string boardPiece, int money=1500, int posn=0, bool inJail=false, int turnsInJail=0);
// returns string (of length 1) for the board piece of the current player
std::string getBoardPiece();
// returns string for the name of the current player
std::string getPlayerName();
// returns bool where true if the player is in jail, false otherwise
bool getInJail();
// return int for the position on the board for which the current player lies
int getPosn();
// returns int for the amount of money owned by the current player
int getMoney();
// changes the money variable (positively or negatively) for the current player
void changeMoney(int amount);
// returns int for the amount of money the current player could collect from mortgaging properties, selling houses/hotels, etc
int getValue();
// changes the value variable (positively or negatively) for the current player
void changeValue(int amount);
// changes the players position to equal the value of the variable p
void setPosn(int p);
// returns int for the amount of consecutive player-turns the current player has been in jail
int getTurnsInJail();
// adds 1 to the amount of consecutive player-turns the current player has been in jail
void addTurnInJail();
// adds 1 to the amount of get out of jail free cards are owned by the current player
void addGetOutOfJailFreeCard();
// uses 1 get out of jail free card (subtracts 1 to the amount of get out of jail free cards are owned by the current player)
void useGetOutOfJailFreeCard();
// returns int for the amount of get out of jail free cards are owned by the current player
int getGetOutOfJailFreeCard();
// sets inJail variable to true
void goToJail();
// removes player from jail, sets inJail variable to false
void leaveJail();
// returns int for the amount of railroad properties are owned for the current player
int getRailroadsOwned();
// adds 1 to the amount of railroad properties are owned by the current player
void addRailroadsOwned();
// removes 1 to the amount of railroad properties are owned by the current player
void subtractRailroadsOwned();
// returns int for the amount of properties that are owned by the current player
int getPropertiesOwned();
// adds 1 to the amount of properties owned for the current player, and adds 1 to the amount of properties owned for the specific group of which the property that has just been bought is a part of
void addPropertiesOwned(std::string group);
// removes 1 from the amount of properties owned for the current player, and removes 1 to the amount of properties owned for the specific group of which the property that has just been bought is a part of
void subtractPropertiesOwned(std::string group);
// returns int for the amount of utilities are owned by the current player
int getUtilitiesOwned();
// adds 1 to the amount of utilities are owned by the current player
void addUtilitiesOwned();
// returns 1 from the amount of utilities are owned by the current player
void subtractUtilitiesOwned();
// Returns true if for the group variable, where group = "purple", "light green", "violet", "orange", "red", "yellow", "dark green", or "dark blue", all properties of that group are owned by the current player. Returns false otherwise.
bool ownsGroup(std::string group);
};
#endif /* defined(____player__) */
<file_sep>/Game_Files/3 - ownablesquare.h
//
// ownablesquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____ownablesquare__
#define ____ownablesquare__
#include <stdio.h>
#include <string>
#include "2 - square.h"
class OwnableSquare: public Square {
public:
OwnableSquare(std::string name, Player* owner, int numberOfHouses, int numberOfHotels);
~OwnableSquare();
//returns a boolean representing if the square is allowed to be owned or not
bool isOwnable();
// returns a boolean representing if the square has been bought or not
bool isBought();
/* ---------------------------------------------------------------------------------------
void setOwner(Player* newOwner)
purpose: set the owner player variable in the square class to newOwner
--------------------------------------------------------------------------------------- */
void setOwner(Player* newOwner);
virtual bool isMortgaged()=0;
virtual int getPaymentCost()=0;
virtual void mortgage()=0;
virtual void unmortgage()=0;
};
#endif /* defined(____ownablesquare__) */
<file_sep>/Game_Files/14 - player.cpp
//
// player.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "14 - player.h"
using namespace std;
Player::Player(string playerName, string boardPiece, int money, int posn, bool inJail, int turnsInJail): playerName(playerName), boardPiece(boardPiece), posn(posn), money(money), inJail(inJail), turnsInJail(turnsInJail) {}
string Player::getBoardPiece() {
return boardPiece;
}
string Player::getPlayerName() {
return playerName;
}
bool Player::getInJail() {
return inJail;
}
int Player::getPosn() {
return posn;
}
int Player::getMoney() {
return money;
}
int Player::getValue() {
return value;
}
void Player::changeMoney(int amount) {
money += amount;
}
void Player::changeValue(int amount) {
value += amount;
}
void Player::setPosn(int p) {
posn = p;
}
int Player::getTurnsInJail() {
return turnsInJail;
}
void Player::addTurnInJail() {
turnsInJail++;
}
void Player::addGetOutOfJailFreeCard() {
getOutOfJailFreeCard++;
}
void Player::useGetOutOfJailFreeCard() {
getOutOfJailFreeCard--;
}
int Player::getGetOutOfJailFreeCard() {
return getOutOfJailFreeCard;
}
void Player::goToJail() {
inJail = true;
}
void Player::leaveJail() {
inJail = false;
turnsInJail = 0;
}
int Player::getRailroadsOwned() {
return railroadsOwned;
}
void Player::addRailroadsOwned() {
railroadsOwned++;
}
void Player::subtractRailroadsOwned() {
railroadsOwned--;
}
int Player::getPropertiesOwned() {
return propertiesOwned;
}
void Player::addPropertiesOwned(string group) {
propertiesOwned++;
if (group == "purple") {
purple++;
}
else if (group == "light green") {
lightgreen++;
}
else if (group == "violet") {
violet++;
}
else if (group == "orange") {
orange++;
}
else if (group == "red") {
red++;
}
else if (group == "yellow") {
yellow++;
}
else if (group == "dark green") {
darkgreen++;
}
else if (group == "dark blue") {
darkblue++;
}
}
bool Player::ownsGroup(std::string group) {
if ((group == "purple" && purple == 2) || (group == "light green" && lightgreen == 3) || (group == "violet" && violet == 3) || (group == "orange" && orange == 3) || (group == "red" && red == 3) || (group == "yellow" && yellow == 3) || (group == "dark green" && darkgreen == 3) || (group == "dark blue" && darkblue == 2)) {
return true;
}
else {
return false;
}
}
void Player::subtractPropertiesOwned(string group) {
propertiesOwned--;
if (group == "purple") {
purple--;
}
else if (group == "light green") {
lightgreen--;
}
else if (group == "violet") {
violet--;
}
else if (group == "orange") {
orange--;
}
else if (group == "red") {
red--;
}
else if (group == "yellow") {
yellow--;
}
else if (group == "dark green") {
darkgreen--;
}
else if (group == "dark blue") {
darkblue--;
}
}
int Player::getUtilitiesOwned() {
return utilitiesOwned;
}
void Player::addUtilitiesOwned() {
utilitiesOwned++;
}
void Player::subtractUtilitiesOwned() {
utilitiesOwned--;
}
<file_sep>/Game_Files/10 - taxsquare.h
//
// taxsquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____taxsquare__
#define ____taxsquare__
#include <stdio.h>
#include <string>
#include "4 - unownablesquare.h"
class TaxSquare: public UnownableSquare {
public:
TaxSquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~TaxSquare();
};
#endif /* defined(____taxsquare__) */
<file_sep>/Game_Files/15 - event.h
//
// event.h
//
//
// Created by <NAME> on 2015-10-09.
//
//
#ifndef _5___event_h
#define _5___event_h
#include <stdio.h>
#include <iostream>
#include <sstream>
class MonopolyBoard;
class Player;
class Square;
class Event {
int playerX;
int numPlayers;
MonopolyBoard* MB;
int doubles;
Player* p; //represents current player
int position;
Square* square;
public:
Event(MonopolyBoard* mb);
/* ---------------------------------------------------------------------------------------
int stringToInt()
purpose: translates a string containing a number into an int, and returns that int
--------------------------------------------------------------------------------------- */
int stringToInt(std::string s);
/* ---------------------------------------------------------------------------------------
void printDice(int d)
purpose: prints a visual representation of 1 dice, where the dice shows a value of d
--------------------------------------------------------------------------------------- */
void printDice(int d);
/* ---------------------------------------------------------------------------------------
int transferFunds(int amountNeeded)
purpose: Players execute transactions to transfer value to money, (execute transactions such as improve-sell/mortgage/trade etc), and true is returned if after completing these transactions, the player has more than amountNeeded in money. false is returned otherwise.
--------------------------------------------------------------------------------------- */
bool transferFunds(int amountNeeded);
/* ---------------------------------------------------------------------------------------
int paySomeone(string payee, int amount)
purpose: money is transfered from the player who is set as the p variable in the event class, to payee, where payee represents another player's board piece or "BANK" if the payment is not to any specific player. The payment has the value of the amount variable
--------------------------------------------------------------------------------------- */
void paySomeone(std::string payee, int amount);
/* ---------------------------------------------------------------------------------------
int executeMandatoryPayment(string payee, int amount)
purpose: money is payed from the player who is set as the p variable in the event class, to payee, where payee represents another player's board piece or "BANK". This payment is a mandatory payment and if it can't be completed, then the player of the p variable is forced to go bankrupt
--------------------------------------------------------------------------------------- */
void executeMandatoryPayment(std::string payee, int amount);
/* ---------------------------------------------------------------------------------------
int executePayment(string payee, int amount)
purpose: money is payed from the player who is set as the p variable in the event class, to payee, where payee represents another player's board piece or "BANK". This payment is not a mandatary payment, so if the player does not have enough money readily available, they are able to opt out of the payment
--------------------------------------------------------------------------------------- */
bool executePayment(std::string payee, int amount);
/* ---------------------------------------------------------------------------------------
void sendToJail()
purpose: sends player p to jail, where player p is inJail and not just visiting
--------------------------------------------------------------------------------------- */
void sendToJail();
/* ---------------------------------------------------------------------------------------
void executeRoll()
purpose: executes the roll process, allowing for 1 or 2 numbers to be input if in testing mode in the form "roll x" or "roll x y" if necessary
--------------------------------------------------------------------------------------- */
bool executeRoll();
/* ---------------------------------------------------------------------------------------
void printPlayers()
purpose: prints board piece for each of the players that are still alive in the game
--------------------------------------------------------------------------------------- */
void printPlayers();
/* ---------------------------------------------------------------------------------------
void executeMovePlayer()
purpose: sends player p to the square they are to move to after rolling the dice
--------------------------------------------------------------------------------------- */
void executeMovePlayer();
/* ---------------------------------------------------------------------------------------
int bid(int posn, int highBid)
purpose: executes act of 1 player's bid in an auction, where posn represents the player's position of the player's vector from the model class, and highBid is the bar of which the player can raise the bid if they so choose. bid(x,y) returns the value of the newest highBid or 0, depending on what the player decides
--------------------------------------------------------------------------------------- */
int bid(int posn, int highBid);
/* ---------------------------------------------------------------------------------------
int executeAuction(int posn, int highBid)
purpose: executes act of auctioning off a property, if the player who lands on it decides not to purchase it. It loops through each of the other players in the game (other than the one who originally landed on the property), and they have the option to raise the bid or withdraw. When there is only one player left the property is awarded to him. If nobody bids then the property stays un-bought.
--------------------------------------------------------------------------------------- */
void executeAuction();
/* ---------------------------------------------------------------------------------------
bool trade(Player* p1, string item1, string item2, string item1Type, string item2Type)
purpose: executes the process of transferring item1 to p1, and item2 to p (from event class), where item1's type is item1Type and item2's type is item2Type
--------------------------------------------------------------------------------------- */
bool trade(Player* p1, std::string item1, std::string item2, std::string item1Type, std::string item2Type);
/* ---------------------------------------------------------------------------------------
void executeTrade()
purpose: executes the process of reading in the name or board piece of the player who will player p will be requesting to trade with, and then reads in the 2 trade items (property or money). The player who is offered the trade is able to reject or accept it, and if accepted trade(...) is called
--------------------------------------------------------------------------------------- */
void executeTrade();
/* ---------------------------------------------------------------------------------------
Square* findSquare()
purpose: reads in a string which is matched with 1 squares squarecode, and then that square is returned
--------------------------------------------------------------------------------------- */
Square* findSquare();
/* ---------------------------------------------------------------------------------------
void executeMortgage()
purpose: executes the process of mortgaging a property if it is owned by the current player, the player is given the amount of mortgageCost for the square (half of the cost of originally buying the square)
--------------------------------------------------------------------------------------- */
void executeMortgage();
/* ---------------------------------------------------------------------------------------
void executeUnmortgage()
purpose: executes the process of unmortgaging a property if it is owned by the current player, the player gives back the amount of mortgageCost for the square (half of the cost of originally buying the square)
--------------------------------------------------------------------------------------- */
void executeUnmortgage();
/* ---------------------------------------------------------------------------------------
void executeImprove()
purpose: executes the process of buying or selling an improvement(house/hotel) depending on reading in the type of transaction ("buy" or "sell"). improvement is only added if the player owns all members of the square's group
--------------------------------------------------------------------------------------- */
void executeImprove();
/* ---------------------------------------------------------------------------------------
void executeChance()
purpose: Executed when a player lands on a chance square, where the card dictates the player what to do. The card chosen is 1 of 16, and is selected on random
--------------------------------------------------------------------------------------- */
void executeChance();
/* ---------------------------------------------------------------------------------------
void executeCommunityChest()
purpose: This function decides whether to call executeOnOwnableSquare() or executeOnUnownableSquare() based on what square player p has landed on
--------------------------------------------------------------------------------------- */
void executeCommunityChest();
/* ---------------------------------------------------------------------------------------
void executeOnOwnableSquare()
purpose: Executes the process of landing on an ownable square. If the square is unowned, then the player is allowed to purchase the property if they have the adequate amount of money, and if the square is owned, a mandatory rent amount must be payed from player p to the owner of the square of which p has landed on
--------------------------------------------------------------------------------------- */
void executeOnOwnableSquare();
/* ---------------------------------------------------------------------------------------
void executeOnUnownableSquare()
purpose: Execute either executeChance() or executeCommunityChest() if on a card square, nothing if on 1 of the first 3 corner squares. If on one of the 2 tax squares, pay the mandatory payment, and if on the last corner, get sent to jail
--------------------------------------------------------------------------------------- */
void executeOnUnownableSquare();
/* ---------------------------------------------------------------------------------------
void executeOnUnownableSquare()
purpose: Execute either executeOnOwnableSquare() or executeOnUnownableSquare(), depending on if the square of which p landed on is ownable or not
--------------------------------------------------------------------------------------- */
void executeOnSquare();
/* ---------------------------------------------------------------------------------------
void executeInJail()
purpose: Executes the process of what occurs in a player's turn when they are locked in jail. The player has 3 options in a regular situation: trying to roll a double (max of 3 tries), paying 50$ bay, or using a get out of jail free card (if they have one)
--------------------------------------------------------------------------------------- */
void executeInJail();
/* ---------------------------------------------------------------------------------------
void executePrintProperties()
purpose: prints all the squares that are owned by a certain player, where each line printed out represents a property. Each line contains the square name, and the amount of houses and hotels that lie on that square
--------------------------------------------------------------------------------------- */
void executePrintProperties();
/* ---------------------------------------------------------------------------------------
void executeAssets()
purpose: prints information on player p's assets. This function prints out p's name, board piece, amount of money, amount of value, amount of get out of jail free cards, position on the board, amount of properties own, and information on each property.
--------------------------------------------------------------------------------------- */
void executeAssets();
/* ---------------------------------------------------------------------------------------
void printPlayers()
purpose: sets player p to bankrupt
--------------------------------------------------------------------------------------- */
void executeBankrupt();
/* ---------------------------------------------------------------------------------------
void executeEvent()
purpose: This function sets p, based on playerX, where p = Players[playerX] from the players vector in the model class, and sets other variables for p's turn. Then the original action is executed based on the event string variable, which must equal one of the following strings: "roll", "moveplayer", "onsquare", "injail", "assets", "mortgage", "unmortgage", "improve", "trade", "bankrupt"
--------------------------------------------------------------------------------------- */
bool executeEvent(std::string event, int playerX);
};
#endif /* _5___event_h */
<file_sep>/Game_Files/13 - printmonopolyboard.h
//
// printmonopolyboard.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____printmonopolyboard__
#define ____printmonopolyboard__
#include <stdio.h>
#include <vector>
#include <cstdlib>
#include <iostream>
class Square;
class Player;
class PrintMonopolyBoard {
static PrintMonopolyBoard* instance;
PrintMonopolyBoard();
std::vector<Square*> Squares;
std::vector<Player*> Players;
int numPlayers;
static void removePrintMonopolyBoard();
public:
static PrintMonopolyBoard *getInstance();
/* ---------------------------------------------------------------------------------------
void update(vector<Square*> squares, vector<Player*> players, int numPlayers)
purpose: The print-board is made up of squares and players, where the amount of players in the game is the value of the numPlayers variable. This function uses squares and players variables to update the view class to hold the current board information
--------------------------------------------------------------------------------------- */
void update(std::vector<Square*> squares, std::vector<Player*> players, int numPlayers);
// returns int for the amount of players in the game
int getNumPlayers();
/* ---------------------------------------------------------------------------------------
void printHouseHotel(int squareNum)
purpose: Prints the visual for the top portion of a square, where this portion of the square shows the amount of houses/hotels that are currently placed on the square, where the current square is Squares[squareNum] in the vector containing all 40 squares.
--------------------------------------------------------------------------------------- */
void printHouseHotel(int squareNum);
/* ---------------------------------------------------------------------------------------
void printPlayersOnSquare1(int squareNum)
purpose: Prints the visual that shows the board pieces for the first 4 players on the current square, where the current square is Squares[squareNum] in the vector containing all 40 squares.
--------------------------------------------------------------------------------------- */
void printPlayersOnSquare1(int squareNum);
/* ---------------------------------------------------------------------------------------
void printPlayersOnSquare1(int squareNum)
purpose: Prints the visual that shows the board pieces for the first remaining players on the current square, after the first 4 have been printed (after printPlayersInJail1() has been executed). The current square is Squares[squareNum] in the vector containing all 40 squares.
--------------------------------------------------------------------------------------- */
void printPlayersOnSquare2(int squareNum);
/* ---------------------------------------------------------------------------------------
void printPlayersInJail1()
purpose: Prints the visual that shows the board pieces for the first 4 players that are locked in jail.
--------------------------------------------------------------------------------------- */
void printPlayersInJail1();
/* ---------------------------------------------------------------------------------------
void printPlayersInJail2()
purpose: Prints the visual that shows the board pieces for the remaining players locked in jail, after the first 4 have been printed (after printPlayersInJail1() has been executed).
--------------------------------------------------------------------------------------- */
void printPlayersInJail2();
/* ---------------------------------------------------------------------------------------
void printPlayersJustVisiting1()
purpose: Prints the visual that shows the board pieces for the first 4 players that are just visiting jail.
--------------------------------------------------------------------------------------- */
void printPlayersJustVisiting1();
/* ---------------------------------------------------------------------------------------
void printPlayersJustVisiting2()
purpose: Prints the visual that shows the board pieces for the remaining players just visiting jail, after the first 4 have been printed (after printPlayersInJail1() has been executed).
--------------------------------------------------------------------------------------- */
void printPlayersJustVisiting2();
/* ---------------------------------------------------------------------------------------
void print()
purpose: Prints the visual of the full monopoly board.
--------------------------------------------------------------------------------------- */
void print();
};
#endif /* defined(____printmonopolyboard__) */
<file_sep>/Game_Files/12 - monopolyboard.cpp
//
// monopolyboard.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "12 - monopolyboard.h"
#include "2 - square.h"
#include "3 - ownablesquare.h"
#include "4 - unownablesquare.h"
#include "5 - streetsquare.h"
#include "6 - railroadsquare.h"
#include "7 - utilitysquare.h"
#include "8 - cardsquare.h"
#include "9 - cornersquare.h"
#include "10 - taxsquare.h"
#include "14 - player.h"
#include "15 - event.h"
#include "11 - runmonopolygame.h"
#include <iostream>
using namespace std;
MonopolyBoard *MonopolyBoard::instance=0;
MonopolyBoard::MonopolyBoard(): EventsClass(Event(this)) {}
void MonopolyBoard::removeMonopolyBoard() {
delete instance;
}
MonopolyBoard *MonopolyBoard::getInstance() {
if (!instance) {
instance = new MonopolyBoard;
atexit(removeMonopolyBoard);
}
return instance;
}
void MonopolyBoard::setup(vector<Square*> squares, vector<Player*> players, int numPlayers) {
for (int i = 0; i < 40; i++) {
Squares.push_back(squares[i]);
}
for (int i = 0; i < numPlayers; i++) {
Players.push_back(players[i]);
}
this->numPlayers = numPlayers;
}
void MonopolyBoard::setRMG(RunMonopolyGame* rmg) {
RMG = rmg;
}
std::vector<Square*> MonopolyBoard::getSquaresVector() {
return Squares;
}
std::vector<Player*> MonopolyBoard::getPlayersVector() {
return Players;
}
int MonopolyBoard::getNumPlayers() {
return numPlayers;
}
void MonopolyBoard::setDiceTotal(int total) {
diceTotal = total;
}
int MonopolyBoard::getDiceTotal() {
return diceTotal;
}
void MonopolyBoard::setIsTestingMode(bool b) {
isTestingMode = b;
}
bool MonopolyBoard::getIsTestingMode() {
return isTestingMode;
}
void MonopolyBoard::removePlayer() {
numPlayers--;
bankrupt = true;
}
void MonopolyBoard::playersTurn(int playerX, int* quit) {
bankrupt = false;
bool next = false;
bool invalid = false;
bool inJail = Players[playerX]->getInJail();
bool q = false; // q for quit
int rollTotal;
int dice1;
int dice2;
int consecutiveDoubles = 0;
string input;
while (1 == 1) {
if (numPlayers == 1) { //game is over when there is only 1 player left standing
cout << "Congratulations " << Players[0]->getPlayerName() << ", you have won the game!" << endl;
cout << "Game is over now, " << Players[0]->getPlayerName() << " is the winner!" << endl;
*quit = 1;
break;
}
if (invalid) { //if the previous run through the loop was invalid in any way this will be executed
cout << "Invalid input" << endl;
invalid = false;
}
if (Players[playerX]->getInJail()) { //if in jail, no initial input, injail handles 1 loop of the players turn
EventsClass.executeEvent("injail",playerX);
next = true;
}
else if (!next) { // alerts user that they haven't executed the roll/move part of their turn
cout << Players[playerX]->getPlayerName() << "'s turn, can roll (must roll before next player's turn)" << endl;
}
else { // alerts user that they've executed the roll/move part of their turn
if (playerX == numPlayers-1) {
cout << Players[0]->getPlayerName() << "'s turn now, type next." << endl;
}
else {
cout << Players[playerX+1]->getPlayerName() << "'s turn now, type next." << endl;
}
}
cin >> input;
if (input == "roll") { //executes player's roll/move part of their turn
cout << "roll 1" << endl;
if (next == false) {
cout << "roll 2" << endl;
next = EventsClass.executeEvent("roll",playerX);
}
else {
cout << "Unable to roll." << endl;
string s;
getline(cin,s);
}
}
else if (input == "bankrupt") {
EventsClass.executeEvent("bankrupt",playerX);
}
else if (input == "mortgage") {
EventsClass.executeEvent("mortgage",playerX);
}
else if (input == "unmortgage") {
EventsClass.executeEvent("unmortgage",playerX);
}
else if (input == "trade") {
EventsClass.executeEvent("trade",playerX);
}
else if (input == "improve") {
EventsClass.executeEvent("improve",playerX);
}
else if (input == "assets") {
EventsClass.executeEvent("assets",playerX);
}
else if (input == "print") {
RMG->printBoard();
}
else if (input == "next") { //signals the end of the player's turn
if (!next) {
cout << "Must roll. Unable to go to the next player." << endl;
}
else {
break;
}
}
else if (input == "quit") { //signals the end of the game
*quit = 1;
RMG->printBoard();
break;
}
else {
invalid = true;
}
if (bankrupt) {
next = true;
bankrupt = false;
}
if (Players[playerX]->getInJail()) {
cout << "Type next." << endl;
cin >> input;
while (input != "next") {
cout << "Invalid input, type next." << endl;
cin >> input;
}
break;
}
}
}
<file_sep>/Game_Files/12 - monopolyboard.h
//
// monopolyboard.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____monopolyboard__
#define ____monopolyboard__
#include <stdio.h>
#include <vector>
#include <cstdlib>
#include "15 - event.h"
class Square;
class Player;
class RunMonopolyGame;
class MonopolyBoard {
static MonopolyBoard *instance;
MonopolyBoard();
bool isTestingMode;
std::vector<Square*> Squares;
std::vector<Player*> Players;
Event EventsClass;
RunMonopolyGame* RMG;
int numPlayers;
int diceTotal;
static void removeMonopolyBoard();
bool bankrupt;
public:
static MonopolyBoard *getInstance();
/* ---------------------------------------------------------------------------------------
vector<Square*> getSquaresVector()
purpose: returns the vector containing all 40 of the squares on the board
--------------------------------------------------------------------------------------- */
std::vector<Square*> getSquaresVector();
/* ---------------------------------------------------------------------------------------
vector<Square*> getPlayersVector()
purpose: returns the vector containing all of the players in the game
--------------------------------------------------------------------------------------- */
std::vector<Player*> getPlayersVector();
// returns the amount of players in the game
int getNumPlayers();
// sets diceTotal in the model to the total variable
void setDiceTotal(int total);
// returns int for the diceTotal from the model
int getDiceTotal();
// sets isTestingMode to true if "-testing" was a part of the original command call, false otherwise
void setIsTestingMode(bool b);
// returns true if the game is in testing mode, false otherwise
bool getIsTestingMode();
/* ---------------------------------------------------------------------------------------
void setRMG()
purpose: Updates the runMonopolyGame (controller) with current board data
--------------------------------------------------------------------------------------- */
void setRMG(RunMonopolyGame* rmg);
/* ---------------------------------------------------------------------------------------
void setup(vector<Square*> squares, vector<Player*> players, int numPlayers)
purpose: The monopoly board is made up of squares and players, where the amount of players in the game is the value of the numPlayers variable. This function uses squares and players variables to setup the board before the game action begins.
--------------------------------------------------------------------------------------- */
void setup(std::vector<Square*> squares, std::vector<Player*> players, int numPlayers);
/* ---------------------------------------------------------------------------------------
void playersTurn(int playerX, int* quit)
purpose: this function executes a players full turn, where the player in action is Players[playerX] from the players vector. If quit is executed as a command, or the game finishes as 1 player wins, then the value of the quit variable changes to 1.
--------------------------------------------------------------------------------------- */
void playersTurn(int playerX, int* quit);
// removes 1 from the numPlayers total (when a player goes bankrupt)
void removePlayer();
};
#endif /* defined(____monopolyboard__) */
<file_sep>/Game_Files/8 - cardsquare.cpp
//
// cardsquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "8 - cardsquare.h"
using namespace std;
CardSquare::CardSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): UnownableSquare(name,owner,numberOfHouses,numberOfHotels) {}
CardSquare::~CardSquare() {}
<file_sep>/Game_Files/2 - square.cpp
//
// square.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "2 - square.h"
#include "14 - player.h"
using namespace std;
Square::Square(string name, Player* owner, int numberOfHouses, int numberOfHotels): name(name), owner(owner), numPlayers(0), currentPlayer(NULL) {}
Square::~Square() {}
void Square::addPlayer(string boardPiece) {
Players[numPlayers] = boardPiece;
numPlayers++;
}
void Square::removePlayer(string boardPiece) {
for (int i = 0; i < numPlayers; i++) {
if (Players[i] == boardPiece) {
for (int j = i; j < numPlayers-1; j++) {
Players[j] = Players[j+1];
}
Players[numPlayers] = '\0';
numPlayers--;
break;
}
}
}
int Square::getNumPlayers() {
return numPlayers;
}
string Square::getNthPlayerPiece(int n) {
return Players[n];
}
string Square::getSquareName() {
return name;
}
string Square::getCode() {
return code;
}
int Square::getNumHouses() {
return numberOfHouses;
}
int Square::getNumHotels() {
return numberOfHotels;
}
void Square::addHouse() {
if (numberOfHouses == 4) {
numberOfHotels = 1;
numberOfHouses = 0;
}
else {
numberOfHouses++;
}
}
void Square::removeHouse() {
if (numberOfHotels == 1) {
numberOfHotels = 0;
numberOfHouses = 4;
}
else {
numberOfHouses--;
}
}
int Square::getHouseCost() {
return houseCost;
}
string Square::getOwnerBoardPiece() {
if (owner == NULL) {
return "null";
}
else {
return owner->getBoardPiece();
}
}
int Square::getPurchaseCost() {
return purchaseCost;
}
int Square::getMortgageCost() {
return mortgageCost;
}
string Square::getGroup() {
return group;
}
<file_sep>/Game_Files/3 - ownablesquare.cpp
//
// ownablesquare.cpp
//
//
// Created by <NAME> on 2015-08-15.
//
//
#include "3 - ownablesquare.h"
using namespace std;
OwnableSquare::OwnableSquare(string name, Player* owner, int numberOfHouses, int numberOfHotels): Square(name,owner,numberOfHouses,numberOfHotels) {
mortgaged = false;
}
OwnableSquare::~OwnableSquare() {}
bool OwnableSquare::isOwnable() {
return true;
}
bool OwnableSquare::isBought() {
if (owner == NULL) {
return false;
}
else {
return true;
}
}
void OwnableSquare::setOwner(Player* newOwner) {
if (owner != NULL) {
owner->subtractPropertiesOwned(group);
}
owner=newOwner;
owner->addPropertiesOwned(group);
}<file_sep>/Game_Files/5 - streetsquare.h
//
// streetsquare.h
//
//
// Created by <NAME> on 2015-08-15.
//
//
#ifndef ____streetsquare__
#define ____streetsquare__
#include <stdio.h>
#include <string>
#include "3 - ownablesquare.h"
#include <iostream>
class StreetSquare: public OwnableSquare {
public:
StreetSquare(std::string name, Player* owner=NULL, int numberOfHouses=0, int numberOfHotels=0);
~StreetSquare();
/* ---------------------------------------------------------------------------------------
void setRentCost(int rc[6])
purpose: set each of the 6 fields in the rentcost in the streetsquare class, where each position in array rc lines up to the same position in rentcost
--------------------------------------------------------------------------------------- */
void setRentCost(int rc[6]);
// returns a boolean representing if the square has been mortgaged or not
bool isMortgaged();
/* ---------------------------------------------------------------------------------------
int getPaymentCost()
purpose: returns an int for how much rent costs when you land on a street square. rent cost is taken from the rentcost array, and the position in the array is selected by how many houses/hotels are on the square
--------------------------------------------------------------------------------------- */
int getPaymentCost();
/* ---------------------------------------------------------------------------------------
void mortgage()
purpose: sets the square to mortgaged, and transfers the amount of the mortgageCost variable to the owner
--------------------------------------------------------------------------------------- */
void mortgage();
/* ---------------------------------------------------------------------------------------
void unmortgage()
purpose: sets the square to unmortgaged, and transfers the amount of the mortgageCost variable away from the owner
--------------------------------------------------------------------------------------- */
void unmortgage();
};
#endif /* defined(____streetsquare__) */
<file_sep>/Game_Files/15 - event.cpp
//
// event.cpp
//
//
// Created by <NAME> on 2015-10-09.
//
//
#include "14 - player.h"
#include "2 - square.h"
#include "12 - monopolyboard.h"
#include "15 - event.h"
#include <string>
#include <sstream>
using namespace std;
Event::Event(MonopolyBoard* mb): MB(mb) {}
void Event::printDice(int d) {
if (d == 1) { cout << "_______" << endl; cout << "| |" << endl; cout << "| * |" << endl; cout << "|_____|" << endl; }
else if (d == 2) { cout << "_______" << endl; cout << "| * |" << endl; cout << "| |" << endl; cout << "|___*_|" << endl; }
else if (d == 3) { cout << "_______" << endl; cout << "| * |" << endl; cout << "| * |" << endl; cout << "|___*_|" << endl; }
else if (d == 4) { cout << "_______" << endl; cout << "|* *|" << endl; cout << "| |" << endl; cout << "|*___*|" << endl; }
else if (d == 5) { cout << "_______" << endl; cout << "|* *|" << endl; cout << "| * |" << endl; cout << "|*___*|" << endl; }
else if (d == 6) { cout << "_______" << endl; cout << "|* *|" << endl; cout << "|* *|" << endl; cout << "|*___*|" << endl; }
}
bool isStringNum(string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] < 48 || s[i] > 57) {
return false;
}
}
return true;
}
bool Event::transferFunds(int amountNeeded) {
//loop
if ((p->getValue() + p->getMoney()) >= amountNeeded) {
return true;
}
else {
return false;
}
}
//Payee must either equal "Bank"/"BANK"/"bank" or one of the board pieces that are in play
void Event::paySomeone(std::string payee, int amount) {
Player* p2;
bool isp2 = false;
for (int i = 0; i < numPlayers; i++) {
if (payee == MB->getPlayersVector()[i]->getBoardPiece()) {
p2 = MB->getPlayersVector()[i];
isp2 = true;
break;
}
}
p->changeMoney(-amount);
if (isp2) {
p2->changeMoney(amount);
}
cout << "end paysomeone" << endl;
}
void Event::executeMandatoryPayment(string payee, int amount) {
bool transfer = true;
if (p->getMoney() >= amount) {
paySomeone(payee,amount);
}
else { //when the player p does not have enough money readily available for the payment they must earn some through trade/mortgage etc
cout << "You need to transfer funds (mortgage/trade) to earn the mandatory " << amount << "$. If you can't pay this you will go bankrupt." << endl;
//transferFunds(amount);
while (p->getMoney() < amount && transfer) {
if (transfer == true) {
transfer = transferFunds(amount);
if (p->getMoney() < amount) {
cout << "Try again." << endl;
}
}
else { //if transfer = false, then
cout << "You do not own enough value to pay the mandatory payment. You must now go bankrupt. Type bankrupt." << endl;
string input;
while (cin >> input) {
if (input == "bankrupt") {
executeBankrupt();
}
else {
cout << "Try again." << endl;
}
}
}
}
if (transfer == true) {
paySomeone(payee,amount);
}
}
}
bool Event::executePayment(std::string payee, int amount) {
cout << "start executepayment" << endl;
string input;
if (p->getMoney() < amount) { //when the player p has less money than they are expected to pay
cout << "You do not have enough money to pay the " << amount << "$. Woud you like to transfer funds? (Y/N)" << endl;
while (cin >> input) {
if (input == "Y") {
transferFunds(amount);
if (p->getMoney() >= amount) {
break;
}
}
else if (input == "N" ) {
cout << "Continue." << endl;
break;
}
else {
cout << "Invalid input." << endl;
}
cout << "You do not have enough money to pay the " << amount << "$. Woud you like to transfer funds? (Y/N)" << endl;
}
}
if (p->getMoney() >= amount) { //when the player p has adequate money to pay amount
cout << "Paying " << amount << "$ now." << endl;
paySomeone(payee,amount);
cout << "PAYMENT" << endl;
return true;
}
else {
return false;
}
}
void Event::sendToJail() {
cout << p->getPlayerName() << ", You are being sent to Jail. Go directly to Jail. Do not pass Go. Do not collect $200." << endl;
string playerBoardPiece = p->getBoardPiece();
MB->getSquaresVector()[position]->removePlayer(playerBoardPiece);
p->setPosn(10);
p->goToJail();
MB->getSquaresVector()[10]->addPlayer(playerBoardPiece);
//next = true;
}
bool Event::executeRoll() {
cout << "roll 3" << endl;
string input;
int rollTotal;
int d1;
int d2;
bool executeNormalRoll = true;
bool d1d2 = true;
bool next = false;
if (p->getInJail()) {
cout << "At this time you are unable to leave jail." << endl;
}
else {
if (MB->getIsTestingMode()) { //executes roll when in testing mode
getline(cin,input);
while (input[0] == ' ') {
input = input.substr(1);
}
if (input != "") {
executeNormalRoll = false;
}
if (input.length() == 3 && input[0] > 48 && input[0] < 55 && input[1] == ' ' && input[2] > 48 && input[2] < 55) {
string num1 = input.substr(0,1);
string num2 = input.substr(2,3);
istringstream(num1) >> d1; //turn first input number to d1
istringstream(num2) >> d2; //turn second input number to d2
}
else if (input != "" && isStringNum(input)) {
istringstream(input) >> rollTotal; //turn input string to number to move player forward by
d1d2 = false;
}
else if (input != "") {
cout << "Input is invalid." << endl;
return false;
}
}
if (executeNormalRoll) { //executes the normal act of rolling
cout << "roll 4" << endl;
int seed = 0;
if (!seed) {
srand(time(NULL));
}
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
}
if (d1d2) { //executes act of adding up 2 dice totals and printing the visuals for the dice
//cout << "roll 5" <<endl;
rollTotal = d1+d2;
printDice(d1);
printDice(d2);
if (d1 == d2) {
cout << "DOUBLE" << endl;
doubles++;
}
else {
doubles = 0;
}
}
if (doubles == 3) { //sends player to jail if doubles are rolled 3 times in a row
sendToJail();
next = true;
}
}
if (doubles != 3) { //executes acts that proceed rolling dice: moving the player and reacting to the square of which the player has landed on
MB->setDiceTotal(rollTotal);
cout << "ROLL POSN = " << p->getPosn() + rollTotal << endl;
cout << "ROLL TOTAL = " << rollTotal << endl;
int timesPassingGo = (p->getPosn() + rollTotal)/40;
cout << "timespassinggo = " << timesPassingGo << endl;
if (timesPassingGo == 1 && (rollTotal > 0 && rollTotal <= 12)) {
p->changeMoney(200);
cout << "Collect $200 salary as you pass GO." << endl;
}
executeEvent("moveplayer",playerX);
executeEvent("onsquare",playerX);
}
//updateprintboard
if ((!executeNormalRoll || (d1 != d2 && d1 != 6 && d2 != 6)) && doubles != 3) {
next = true;
}
if (doubles == 3) {
doubles = 0;
}
return next;
}
void Event::executeMovePlayer() {
string playerBoardPiece = p->getBoardPiece();
int posn = p->getPosn();
MB->getSquaresVector()[posn]->removePlayer(playerBoardPiece);
int diceTotal = MB->getDiceTotal();
int newPosn = ((posn + diceTotal) % 40);
p->setPosn(newPosn);
MB->getSquaresVector()[newPosn]->addPlayer(playerBoardPiece);
}
int Event::bid(int posn, int highBid) {
cout << MB->getPlayersVector()[posn]->getBoardPiece() << ", would you like to raise the current bid or withdraw? Input the amount you wish to pay for the property, (higher than " << highBid << ", or 0 if you wish to withdraw." << endl;
int tempBid = 0;
bool valid = false;
cin >> tempBid;
while (1 == 1) {
if (tempBid <= highBid && tempBid != 0) {
cout << "Your bid is lower than or equal to the current high bid. Try again." << endl;
}
else if (tempBid > MB->getPlayersVector()[posn]->getMoney()) {
string input;
if (p->getMoney() < tempBid) { //if player bids a value higher than they have in money, allows the player chance to transfer funds
cout << "You do not have enough money to bid the " << tempBid << "$. Woud you like to transfer funds? (Y/N)" << endl;
while (cin >> input) {
if (input == "Y") {
transferFunds(tempBid);
if (p->getMoney() >= tempBid) {
cout << MB->getPlayersVector()[posn]->getBoardPiece() << " has bid " << tempBid << "$." << endl;
return tempBid;
}
}
else if (input == "N" ) {
cout << "Continue." << endl;
break;
}
else {
cout << "Invalid input." << endl;
}
cout << "You do not have enough money to bid the " << tempBid << "$. Woud you like to transfer funds? (Y/N)" << endl;
}
}
}
else {
break;
}
cout << "Input the amount you wish to pay for the property, or 0 if you wish to withdraw." << endl;
cin >> tempBid;
}
return tempBid;
}
void Event::executeAuction() {
cout << "The property is now up for auction." << endl;
int highBid = square->getPurchaseCost();
cout << "The current price of the property is " << highBid << "." << endl;
bool inAuction[numPlayers];
for (int i = 0; i < numPlayers; i++) {
if (MB->getPlayersVector()[i]->getBoardPiece() == p->getBoardPiece()) {
inAuction[i] = false;
}
else {
inAuction[i] = true;
}
}
int counter = numPlayers-1;
int bidn = 0;
int bidVal;
char decision;
cout << "numPlayers = " << numPlayers << endl;
while (counter > 1) {
cout << "start loop 1" << endl;
for (int i = 0; i < numPlayers; i++) {
if (counter == 1) {
break;
}
if (inAuction[i]) {
cout << "start bid" << endl;
bidVal = bid(i,highBid);
if (bidVal != 0) {
bidn = 1;
}
cout << "end bid" << endl;
if (bidVal == 0) {
inAuction[i] = false;
counter--;
cout << MB->getPlayersVector()[i]->getBoardPiece() << " has withdrawn from the auction." << endl;
}
else {
highBid = bidVal;
}
}
}
}
int posn;
for (int i = 0; i < numPlayers; i++) {
if (inAuction[i]) {
posn = i;
break;
}
}
p = MB->getPlayersVector()[posn];
bool bought = true;
if (numPlayers == 2 || bidn == 0) {
cout << p->getBoardPiece() << ", Would you like to 'win the auction' purchase the property for $" << highBid << "? (Y/N)" << endl;
string decision;
while (cin >> decision) {
if (decision == "Y") {
break;
}
else if (decision == "N") {
bought = false;
break;
}
else {
cout << "Invalid input. Try again." << endl;
}
}
}
else if (counter == 0) {
bought = false;
}
if (bought) {
bought = executePayment("BANK",highBid);
}
if (!bought) {
cout << "There is no winner in this auction. The property will stay un-bought" << endl;
}
else {
cout << p->getBoardPiece() << " has won the auction and now owns the property." << endl;
p->changeValue(square->getMortgageCost());
square->setOwner(p);
}
p = MB->getPlayersVector()[playerX];
}
/* ---------------------------------------------------------------------------------------
bool isNum(string s)
purpose: returns a boolean, true if the string s only contains a number, false otherwise
--------------------------------------------------------------------------------------- */
bool isNum(string s) {
int length = s.length();
for (int i = 0; i < length; i++) {
if (s[i] < 48 || s[i] > 57) {
return false;
}
}
return true;
}
int Event::stringToInt(string s) {
istringstream si(s);
int i;
si >> i;
return i;
}
bool Event::trade(Player* p1, string item1, string item2, string item1Type, string item2Type) {
Square* square1;
Square* square2;
int price;
if (item1Type == "property" && item2Type == "property") {
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getCode() == item1) {
square1 = MB->getSquaresVector()[i];
}
if (MB->getSquaresVector()[i]->getCode() == item2) {
square2 = MB->getSquaresVector()[i];
}
}
if (square1->getOwnerBoardPiece() == p->getBoardPiece() && square2->getOwnerBoardPiece() == p1->getBoardPiece()) {
// swap properties
int diff = square1->getMortgageCost()-square2->getMortgageCost();
square1->setOwner(p1);
square2->setOwner(p);
p->changeValue(-diff);
p1->changeValue(diff);
return true;
}
else {
cout << "One of the 2 properties is not a valid trade component." << endl;
return false;
}
}
else if (item1Type == "property" && item2Type == "money") {
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getCode() == item1) {
square1 = MB->getSquaresVector()[i];
break;
}
}
price = stringToInt(item2);
if (square1->getOwnerBoardPiece() == p->getBoardPiece() && p1->getMoney() >= price) {
// swap property/money
cout << "move 1" << endl;
square1->setOwner(p1);
p->changeValue(-square1->getMortgageCost());
p1->changeValue(square1->getMortgageCost());
Player* temp = p;
p = p1;
executePayment(temp->getBoardPiece(),price);
p = temp;
free(temp);
return true;
}
else if (square1->getOwnerBoardPiece() != p->getBoardPiece()) {
cout << "The property being traded is not a valid trade component." << endl;
return false;
}
else { //if (p1->getMoney() < price) {
cout << "move 2" << endl;
Player* temp = p;
p = p1;
bool paid = executePayment(temp->getBoardPiece(),price);
p = temp;
//free(temp);
if (paid) {
square1->setOwner(p1);
p->changeValue(-square1->getMortgageCost());
p1->changeValue(square1->getMortgageCost());
return true;
}
else {
return false;
}
}
}
else if (item1Type == "money" && item2Type == "property") {
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getCode() == item2) {
square1 = MB->getSquaresVector()[i];
break;
}
}
price = stringToInt(item1);
if (square1->getOwnerBoardPiece() == p1->getBoardPiece() && p->getMoney() >= price) {
// swap property/money
square1->setOwner(p);
p1->changeValue(-square1->getMortgageCost());
p->changeValue(square1->getMortgageCost());
executePayment(p1->getBoardPiece(),price);
return true;
}
else if (square1->getOwnerBoardPiece() != p1->getBoardPiece()) {
cout << "The property being traded is not a valid trade component." << endl;
return false;
}
else { // (p->getMoney() < price) {
bool paid = executePayment(p1->getBoardPiece(),price);
if (paid) {
square1->setOwner(p);
p1->changeValue(-square1->getMortgageCost());
p->changeValue(square1->getMortgageCost());
return true;
}
else {
return false;
}
}
}
else {
return false;
}
}
void Event::executeTrade() {
string other;
string item1;
string item2;
string item1Name;
string item2Name;
string item1Type;
string item2Type;
string response;
cin >> other;
cin >> item1;
cin >> item2;
if (isNum(item1)) { //sets type for the first item to money
item1Name = item1 + "$";
item1Type = "money";
}
else { //sets type for the first item to property
item1Type = "property";
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getCode() == item1) {
item1Name = MB->getSquaresVector()[i]->getSquareName();
}
}
}
if (isNum(item2)) { //sets type for the 2nd item to money
item2Name = item2 + "$";
item2Type = "money";
}
else { //sets type for the 2nd item to property
item2Type = "property";
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getCode() == item1) {
item1Name = MB->getSquaresVector()[i]->getSquareName();
}
}
}
Player* p1;
for (int i = 0; i < numPlayers; i++) { //finds player class for the player who is getting offered the trade
if (MB->getPlayersVector()[i]->getPlayerName() == other || MB->getPlayersVector()[i]->getBoardPiece() == other) {
p1 = MB->getPlayersVector()[i];
}
}
cout << p1->getBoardPiece() << ", would you like to accept the following trade? (Y/N)" << endl;
cout << p->getBoardPiece() << " gives you: " << item1Name << endl;
cout << "You give " << p->getBoardPiece() << ": " << item2Name << endl;
while (cin >> response) {
if (response == "Y") { //trade is accepted
bool tradeComplete = trade(p1,item1,item2,item1Type,item2Type);
if (tradeComplete) {
cout << "The trade has been completed." << endl;
}
else {
cout << "The trade did not go through." << endl;
}
break;
}
else if (response == "N") { //trade is declined
cout << p1->getBoardPiece() << " has declined the trade." << endl;
break;
}
else {
cout << "Invalid. Respond 'Y' or 'N'." << endl;
}
}
}
Square* Event::findSquare() {
string squarestr;
cin >> squarestr;
int posn;
for (int i = 0; i < 40; i++) {
if (squarestr == MB->getSquaresVector()[i]->getCode()) {
posn = i;
break;
}
}
return MB->getSquaresVector()[posn];
}
void Event::executeMortgage() {
Square* mortgageSquare = findSquare();
if (mortgageSquare->getNumHouses() || mortgageSquare->getNumHotels()) {
cout << "Cannot mortgage a property that contains improvements." << endl;
}
else {
mortgageSquare->mortgage();
}
}
void Event::executeUnmortgage() {
Square* unmortgageSquare = findSquare();
unmortgageSquare->unmortgage();
}
void Event::executeImprove() {
string type;
cin >> type;
Square* improvementSquare = findSquare();
int cost = improvementSquare->getHouseCost();
if (type == "buy") {
if (improvementSquare->isMortgaged()) { //if the transaction is a purchase
cout << "Cannot buy or sell an improvement on a property that is mortgaged." << endl;
}
else {
if (improvementSquare->getNumHotels() == 1) {
cout << "You already have the maximum amount of houses/hotels allowed on this square." << endl;
}
else if (p->getMoney() < cost) {
cout << "You currently do not have enough $ to add a house. House cost is $" << cost << "." << endl;
}
else if (p->ownsGroup(improvementSquare->getGroup())) {
paySomeone("BANK",cost);
p->changeValue(cost/2);
improvementSquare->addHouse();
}
else {
cout << "All members of the " << improvementSquare->getGroup() << " group are not owned. So improvements cannot be made." << endl;
}
}
}
else if (type == "sell") { //if the transaction is a sale
if (improvementSquare->isMortgaged()) {
cout << "Cannot buy or sell an improvement on a property that is mortgaged." << endl;
}
else {
if (improvementSquare->getNumHouses() == 0 && improvementSquare->getNumHotels() == 0) {
cout << "You don't have any houses on this square to sell." << endl;
}
else if (p->ownsGroup(improvementSquare->getGroup())) {
p->changeMoney(cost/2);
p->changeValue(-cost/2);
improvementSquare->removeHouse();
}
else {
cout << "All members of the " << improvementSquare->getGroup() << " group are not owned. So improvements cannot be made." << endl;
}
}
}
}
void Event::executeInJail() {
cout << "You are locked in jail." << endl;
cout << "Would you like to try to roll a double (R), pay 50$ bail (P), or use a get out of jail free card (G)?" << endl;
string decision;
bool transfer = true;
string input;
while (cin >> decision) {
if (decision == "R") {
p->addTurnInJail();
int seed = 0;
if (!seed) {
srand(time(NULL));
}
int d1 = rand() % 6 + 1;
int d2 = rand() % 6 + 1;
printDice(d1);
printDice(d2);
if (d1 == d2) {
p->leaveJail();
}
else if (p->getTurnsInJail() == 3) {
cout << "You must pay 50$ now." << endl;
executeMandatoryPayment("BANK",50);
}
break;
}
else if (decision == "P") {
bool paid = executePayment("BANK",50);
if (paid) {
break;
}
}
else if (decision == "G") {
if (p->getGetOutOfJailFreeCard() > 0) {
p->useGetOutOfJailFreeCard();
p->leaveJail();
break;
}
else {
cout << "You do not own a get out of jail free card. Try again." << endl;
}
}
cout << "Would you like to try to roll a double (R), pay 50$ bail (P), or use a get out of jail free card (G)?" << endl;
}
}
void Event::executeOnOwnableSquare() {
char decision;
string ownerBoardPiece = square->getOwnerBoardPiece();
if (square->isBought() && (ownerBoardPiece != p->getBoardPiece()) && !square->isMortgaged()) { //when someone else owns the property
int price = square->getPaymentCost();
cout << "You must pay " << price << "$ rent to " << square->getOwnerBoardPiece() << "." << endl;
executeMandatoryPayment(ownerBoardPiece,price);
}
else if (ownerBoardPiece == p->getBoardPiece()) { //when player p owns the property
cout << "You have landed on a square that you already own. Continue playing." << endl;
}
else if (square->isMortgaged()) { //when someone else owns the property but the property is mortgaged
cout << "This square is owned by another owner, but it has been mortgaged out, so you do not have to pay any money." << endl;
}
else { //when the property is unowned
string answer;
cout << "This property currently has no owner. Would you like to buy the property for " << square->getPurchaseCost() << "$? (Y/N)" << endl;
while (cin >> answer) {
if (answer == "Y") {
cout << "START PAYMENT" << endl;
bool bought = executePayment("BANK",square->getPurchaseCost());
if (bought) {
cout << "1" << endl;
p->changeValue(square->getMortgageCost());
cout << "2" << endl;
square->setOwner(p);
}
else {
cout << "You didn't buy the property." << endl;
executeAuction();
}
cout << "END PAYMENT" << endl;
break;
}
else if (answer == "N") { //execute auction if player p doesn't buy the property
cout << "We are now entering an auction." << endl;
executeAuction();
break;
}
else {
cout << "Invalid Input. ";
}
cout << "This property currently has no owner. Would you like to buy the property for " << square->getPurchaseCost() << "$? (Y/N)" << endl;
}
}
}
void Event::executeChance() {
int cardNum;
int seed = 0;
// randomize cardNum
if (!seed) {
srand(time(NULL));
}
cardNum = rand() % 16 + 1;
if (cardNum == 1) {
cout << "You have won a crossword competition - Collect $100" << endl;
p->changeMoney(100);
}
else if (cardNum == 2) {
cout << "Advance to Go (Collect $200)" << endl;
MB->setDiceTotal(40 - position);
executeMovePlayer();
p->changeMoney(200);
}
else if (cardNum == 3) {
cout << "Advance to Illinois Ave. - If you pass Go, collect $200" << endl;
if (position < 23) {
MB->setDiceTotal(24 - position);
}
else {
MB->setDiceTotal(28);
cout << "Collected 200." << endl;
p->changeMoney(200);
}
executeMovePlayer();
executeOnSquare();
}
else if (cardNum == 4) {
cout << "Advance to St. Charles Place – If you pass Go, collect $200" << endl;
if (position < 10) {
MB->setDiceTotal(11 - position);
}
else {
MB->setDiceTotal((40 - position) + 11);
cout << "Collected 200." << endl;
p->changeMoney(200);
}
executeMovePlayer();
executeOnSquare();
}
else if (cardNum == 5) {
cout << "Advance token to nearest Utility. If unowned, you may buy it from the Bank. If owned, throw dice and pay owner a total ten times the amount thrown." << endl;
if (position < 10) { //chance card position 1
MB->setDiceTotal(5);
}
else if (position < 25) { //chance card position 2
MB->setDiceTotal(6);
}
else { //chance card position 3
MB->setDiceTotal(16);
}
executeMovePlayer();
if (square->getOwnerBoardPiece() != "null" && square->getOwnerBoardPiece() != p->getBoardPiece()) {
int d1; int d2;
int seed = 0;
if (!seed) {
srand(time(NULL));
}
d1 = rand() % 6 + 1;
d2 = rand() % 6 + 1;
printDice(d1); printDice(d2);
cout << "You must pay " << square->getOwnerBoardPiece() << " 10 x roll total = " << (d1+d2) << " = $" << (10*(d1+d2)) << "." << endl;
executeMandatoryPayment(square->getOwnerBoardPiece(),10*(d1+d2));
}
}
else if (cardNum == 6) {
cout << "Advance token to the nearest Railroad and pay owner twice the rental to which he/she is otherwise entitled. If Railroad is unowned, you may buy it from the Bank." << endl;
if (position < 10) { //chance position 1
MB->setDiceTotal(8);
}
else if (position < 25) { //chance position 2
MB->setDiceTotal(3);
}
else { //chance position 3
MB->setDiceTotal(11);
cout << "Collected 200." << endl;
p->changeMoney(200);
}
executeMovePlayer();
if (square->getOwnerBoardPiece() != "null" && square->getOwnerBoardPiece() != p->getBoardPiece()) {
cout << "You must pay " << square->getOwnerBoardPiece() << " $" << square->getPaymentCost()*2 << "." << endl;
executeMandatoryPayment(square->getOwnerBoardPiece(),square->getPaymentCost()*2);
}
else {
executeOnSquare();
}
}
else if (cardNum == 7) {
cout << "Bank pays you dividend of $50" << endl;
p->changeMoney(50);
}
else if (cardNum == 8) {
cout << "Get out of Jail Free card – This card may be kept until needed"/*, or traded/sold"*/ << endl;
p->addGetOutOfJailFreeCard();
}
else if (cardNum == 9) {
cout << "Go Back 3 Spaces" << endl;
MB->setDiceTotal(37);
executeMovePlayer();
executeOnSquare();
}
else if (cardNum == 10) { //D0
cout << "Go to Jail – Go directly to Jail – Do not pass Go, do not collect $200" << endl;
sendToJail();
}
else if (cardNum == 11) {
cout << "Make general repairs on all your property – For each house pay $25 – For each hotel $100" << endl;
int amountHouses;
int amountHotels;
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getOwnerBoardPiece() == p->getBoardPiece()) {
amountHouses += MB->getSquaresVector()[i]->getNumHouses();
amountHotels += MB->getSquaresVector()[i]->getNumHotels();
}
}
int amountPay = (25*amountHouses)+(100*amountHotels);
cout << "Must pay for " << amountHouses << " houses and " << amountHotels << " hotels = $" << amountPay << "." << endl;
executeMandatoryPayment("BANK",amountPay);
}
else if (cardNum == 12) {
cout << "Pay poor tax of $15" << endl;
executeMandatoryPayment("BANK",15);
}
else if (cardNum == 13) {
cout << "Take a trip to Reading Railroad - If you pass Go, collect $200" << endl;
MB->setDiceTotal(40-position+5);
executeMovePlayer();
cout << "Collected 200." << endl;
p->changeMoney(200);
executeOnSquare();
}
else if (cardNum == 14) {
cout << "Take a walk on the Boardwalk – Advance token to Boardwalk" << endl;
MB->setDiceTotal(39 - position);
executeMovePlayer();
executeOnSquare();
}
else if (cardNum == 15) {
cout << "You have been elected Chairman of the Board – Pay each player $50" << endl;
for (int i = 0; i < numPlayers; i++) {
paySomeone(MB->getPlayersVector()[i]->getBoardPiece(),50);
}
}
else if (cardNum == 16) {
cout << "Your building {and} loan matures – Collect $150" << endl;
p->changeMoney(150);
}
}
void Event::executeCommunityChest() {
int cardNum;
int seed = 0;
//randomize cardNum
if (!seed) {
srand(time(NULL));
}
cardNum = rand() % 17 + 1;
if (cardNum == 1) {
cout << "Advance to Go (Collect $200)" << endl;
MB->setDiceTotal(40 - position);
executeMovePlayer();
p->changeMoney(200);
}
else if (cardNum == 2) {
cout << "Bank error in your favor - Collect $200" << endl;
p->changeMoney(200);
}
else if (cardNum == 3) {
cout << "Doctor's fees - Pay $50" << endl;
executeMandatoryPayment("BANK",50);
}
else if (cardNum == 4) {
cout << "From sale of stock you get $50" << endl;
p->changeMoney(50);
}
else if (cardNum == 5) {
cout << "Get out of Jail Free card – This card may be kept until needed"/*, or traded/sold"*/ << endl;
p->addGetOutOfJailFreeCard();
}
else if (cardNum == 6) {
cout << "Go to Jail – Go directly to Jail – Do not pass Go, do not collect $200" << endl;
sendToJail();
}
else if (cardNum == 7) {
cout << "Grand Opera Night - Collect $50 from every player for opening night seats" << endl;
Player* temp = p;
for (int i = 0; i < numPlayers; i++) {
p = MB->getPlayersVector()[i];
executeMandatoryPayment(temp->getBoardPiece(),50);
}
p = temp;
free(temp);
}
else if (cardNum == 8) {
cout << "Holiday Fund matures - Receive $100" << endl;
p->changeMoney(100);
}
else if (cardNum == 9) {
cout << "Income Tax refund - Collect $20" << endl;
p->changeMoney(20);
}
else if (cardNum == 10) {
cout << "It is your birthday - Collect $10 from each player" << endl;
Player* temp = p;
for (int i = 0; i < numPlayers; i++) {
p = MB->getPlayersVector()[i];
executeMandatoryPayment(temp->getBoardPiece(),10);
}
p = temp;
free(temp);
}
else if (cardNum == 11) {
cout << "Life insurance maturs - Collect $100" << endl;
p->changeMoney(100);
}
else if (cardNum == 12) {
cout << "Pay hospital fees of $100" << endl;
executeMandatoryPayment("BANK",100);
}
else if (cardNum == 13) {
cout << "Pay school fees of $150" << endl;
executeMandatoryPayment("BANK",150);
}
else if (cardNum == 14) {
cout << "Receive $25 consultancy fee" << endl;
p->changeMoney(25);
}
else if (cardNum == 15) { //DO
cout << "You are assessed for street repairs - $40 per house - $115 per hotel" << endl;
int amountHouses;
int amountHotels;
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getOwnerBoardPiece() == p->getBoardPiece()) {
amountHouses += MB->getSquaresVector()[i]->getNumHouses();
amountHotels += MB->getSquaresVector()[i]->getNumHotels();
}
}
int amountPay = (40*amountHouses)+(115*amountHotels);
cout << "Must pay for " << amountHouses << " houses and " << amountHotels << " hotels = $" << amountPay << "." << endl;
executeMandatoryPayment("BANK",amountPay);
}
else if (cardNum == 16) {
cout << "You have won second prize in a beauty contest - Collect $10" << endl;
p->changeMoney(10);
}
else if (cardNum == 17) {
cout << "You inherit $100" << endl;
p->changeMoney(100);
}
}
void Event::executeOnUnownableSquare() {
if (position == 7 || position == 21 || position == 36) { //chance square
executeChance();
}
else if (position == 2 || position == 17 || position == 33) { //community chest square
executeCommunityChest();
}
else if (position == 0 || position == 10 || position == 20) { //collect go, just visiting jail, free parking square
}
else if (position == 4) { //income tax square
cout << "You have landed on the Income Tax square. You must pay $200." << endl;
executeMandatoryPayment("BANK",200);
}
else if (position == 38) { //luxury tax square
cout << "You have landed on the Luxury Tax square. You must pay $100." << endl;
executeMandatoryPayment("BANK",100);
}
else { //go to jail square
sendToJail();
}
}
void Event::executeOnSquare() {
Square* square = MB->getSquaresVector()[p->getPosn()];
cout << "You have landed on " << square->getSquareName() << "." << endl;
if (square->isOwnable()) {
executeOnOwnableSquare();
}
else {
executeOnUnownableSquare();
}
}
void Event::executePrintProperties() {
for (int i = 0; i < 40; i++) {
if (MB->getSquaresVector()[i]->getOwnerBoardPiece() == p->getBoardPiece()) {
cout << MB->getSquaresVector()[i]->getSquareName();
if (MB->getSquaresVector()[i]->getNumHouses() > 0) {
cout << " - " << MB->getSquaresVector()[i]->getNumHouses() << " houses" << endl;
}
else if (MB->getSquaresVector()[i]->getNumHotels() > 0) {
cout << " - " << MB->getSquaresVector()[i]->getNumHotels() << " hotel" << endl;
}
else {
cout << endl;
}
}
}
}
void Event::executeAssets() {
cout << "Player's name: " << p->getPlayerName() << endl;
cout << "Player's board piece: " << p->getBoardPiece() << endl;
cout << "Money: " << p->getMoney() << endl;
cout << "Value: " << p->getValue() << endl;
cout << "Get out of jail free cards: " << p->getGetOutOfJailFreeCard() << endl;
cout << "Position: " << MB->getSquaresVector()[p->getPosn()]->getSquareName() << endl;
cout << "Amount of properties owned: " << p->getPropertiesOwned() << endl;
cout << "Properties owned: " << endl;
executePrintProperties();
}
void Event::printPlayers() {
cout << "numPlayers = " << numPlayers << endl;
for (int i = 0; i < numPlayers; i++) {
cout << i << ") " << MB->getPlayersVector()[i]->getBoardPiece() << endl;
}
}
void Event::executeBankrupt() {
square->removePlayer(p->getBoardPiece());
//delete Players[posn];
delete MB->getPlayersVector()[playerX];
for (int i = playerX; i < numPlayers-1; i++) {
MB->getPlayersVector()[i] = MB->getPlayersVector()[i+1];
}
numPlayers--;
MB->removePlayer();
printPlayers();
cout << "BANKRUPT EVENT" << endl;
}
bool Event::executeEvent(string event, int playerX) {
p = MB->getPlayersVector()[playerX];
position = p->getPosn();
square = MB->getSquaresVector()[position];
numPlayers = MB->getNumPlayers();
this->playerX = playerX;
if (event == "roll") {
return executeRoll();
}
else if (event == "moveplayer") {
executeMovePlayer();
}
else if (event == "onsquare") {
executeOnSquare();
}
else if (event == "injail") {
executeInJail();
}
else if (event == "assets") {
executeAssets();
}
else if (event == "mortgage") {
executeMortgage();
}
else if (event == "unmortgage") {
executeUnmortgage();
}
else if (event == "improve") {
executeImprove();
}
else if (event == "trade") {
executeTrade();
}
else if (event == "bankrupt") {
executeBankrupt();
}
cout << "EVENT OUT" << endl;
return true;
}
|
d2bcb89032623af22db45635251ac0e26f5b1f24
|
[
"Markdown",
"C++"
] | 30 |
C++
|
adfmadis/Monopoly
|
813e91cc4479f5f636dbf7369884036e403763eb
|
ed8f5069cf3694fa73ec6e8c36c024f0efd5bcff
|
refs/heads/master
|
<file_sep>
public class Application {
public static void main(String[] args) {
boolean isHotOutside = true ;
boolean isWeekDay = false ;
boolean hasMoneyInPocket = true ;
int costOfMilk = 3 ;
double moneyInWallet = 15.50 ;
int thirstLevel = 7 ;
System.out.println(isHotOutside);
System.out.println(isWeekDay);
System.out.println(hasMoneyInPocket);
System.out.println(costOfMilk);
System.out.println(moneyInWallet);
System.out.println(thirstLevel);
if (isHotOutside == true && hasMoneyInPocket == true) {
System.out.println("I should buy icecream");
}else {
System.out.println("I will not buy icecream");
}
if (isHotOutside == true && isWeekDay == false) {
System.out.println("I will go swimming");
}else {
System.out.println("I will not go swimming");
}
if (isHotOutside == true && hasMoneyInPocket == true && isWeekDay == false) {
System.out.println("It is a good day");
}else {
System.out.println("It is not a good day");
}
if (isHotOutside == true && thirstLevel >= 3 && moneyInWallet >= 6) {
System.out.println("I will buy milk");
}else {
System.out.println("I will not buy milk");
}
}
}
|
a614c0d5edce860c56f515a8685d35eb987a6a91
|
[
"Java"
] | 1 |
Java
|
PR-IX/Week-2-
|
fa40ce3f6510d807f3f3cc9430fcdff9d435a298
|
0c5e65e6e5a8525498732b8ad7f3f660b20e2814
|
refs/heads/master
|
<file_sep>package com.sepm.stepdefinitions;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.sepm.config.ReadConfigFile;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class BaseFunctionSEP {
static WebDriver driver;
ReadConfigFile readConfigFile = new ReadConfigFile();
@SuppressWarnings("deprecation")
@Before
// *** Intiate Driver ***//
public void initiateDriver() throws InterruptedException, IOException {
System.out.println("Before Class ");
if ("CHROME".equalsIgnoreCase(readConfigFile.getBrowser())) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\SESA430059\\eclipse-workspace\\OCP-Demo\\Drivers\\geckodriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if ("IE".equalsIgnoreCase(readConfigFile.getBrowser())) {
System.setProperty("webdriver.ie.driver",
"C:\\Users\\SESA430059\\eclipse-workspace\\OCP-Demo\\Drivers\\IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setJavascriptEnabled(true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
@After
// *** Quite the Driver ***//
public void quiteDriver() {
System.out.println("After Class");
//driver.close();
}
}
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>OCP-Demo</groupId>
<artifactId>OCP-Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>OCP-Demo</name>
<description>OCP-Demo</description>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>htmlunit-driver</artifactId>
<version>2.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/gherkin -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>3.11.0</version>
</dependency>
<!-- Apache POI Dependency -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>stax</groupId>
<artifactId>stax-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.2-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<!-- https://mvnrepository.com/artifact/picocontainer/picocontainer -->
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.2-FINAL</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<includes>
<exclude>**/*RunFeatures.java</exclude>
</includes>
</configuration>
</plugin>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-compiler-plugin
</artifactId>
<versionRange>
[3.1,)
</versionRange>
<goals>
<goal>compile</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
|
49406a8f118afbf34e026d610aa602cd80334f16
|
[
"Java",
"Maven POM"
] | 2 |
Java
|
raju02narayan/Demo01
|
ea22a7e874620ba7628c7eff023ee543b377e857
|
792851b105dadad54a3699f3309f5c1ee0063c29
|
refs/heads/master
|
<file_sep>//DEFINIÇÃO DA ESTRUTURA PRINCIPAL DA FILA
struct NODE{
int info;
struct node *prox;
};
typedef struct NODE node;
static int TAM = 0;
void opcao(node *FILA, int op);
void inserir(node *FILA, int info);
void visualizar(node *FILA);
void remover(node *FILA);
<file_sep>#include<stdio.h>
#include <stdlib.h>
#include "filadinamica.h"
int main(){
printf("\n\tED1 - T1__LISTA DUPLAMENTE ENCADEADA\n\n");
//LAÇO PRINCIPAL
int op;
do{
//__fpurge(stdin);
system("clear");
printf("\nESCOLHA UMA OPCAO\n\n");
printf("\t0 - FECHAR\n");
printf("\t1 - INICIALIZAR\n");
printf("\t2 - INSERIR ELEMENTO NA FILA\n");
printf("\t3 - REMOVER ELEMENTO NA FILA\n");
printf("\t4 - VISUALIZAR FILA\n");
printf("\n\tOPCAO: "); scanf("%d", &op);
opcao(op);
}while(op);
}
void *opcao(int op){
int num = 0;
switch(op){
case 0:
//free(FILA);
printf("\n\n\tFILA LIBERADA\n\n");
getchar();
exit(1);
break;
case 1:
//control *HR = (control *) malloc(sizeof(control));
//if(!HR){
// printf("\n\t\tERRO DE ALOCACAO\n");
// exit(1);
//}else{
// HR->head = NULL;
// HR->rear = NULL;
//}
control *HR;
return HR;
break;
case 2:
//remover(FILA);
printf("\n\t\tCASO 2\n");
getchar();
break;
case 3:
//visualizar(FILA);
printf("\n\t\tCASO 3\n");
getchar();
exit(1);
break;
case 4:
//visualizar(FILA);
printf("\n\t\tCASO 4\n");
getchar();
exit(1);
break;
default:
printf("\nOPCAO INVALIDA\n");
getchar();
break;
}
}
node *initFila(){
return NULL;
}
<file_sep>#include<stdio.h>
#include <stdlib.h>
#include "filaDinamica.h"
int main(){
printf("\n\tED1 - FILA DINAMICA\n\n");
//ALOCA UM PONTEIRO TIPO ESTRUTURA
node *FILA = (node *) malloc(sizeof(node));
//TESTE DE ALOCAÇÃO
if(!FILA){
printf("\n\t\tERRO DE ALOCACAO\n");
system("pause");
exit(1);
}else{
FILA->prox = NULL;
FILA->info = NULL;
printf("\n\tFILA INICIALIZADA\n\n");
}
getchar();
//LAÇO PRINCIPAL
int op;
do{
system("clear");
printf("\nESCOLHA UMA OPCAO\n\n");
printf("\t0 - FECHAR\n");
printf("\t1 - INSERIR ELEMENTO NA FILA\n");
printf("\t2 - REMOVER ELEMENTO NA FILA\n");
printf("\t3 - VISUALIZAR FILA\n");
printf("\n\tOPCAO: "); scanf("%d", &op);
opcao(FILA, op);
}while(op);
}
void opcao(node *FILA, int op){
static int num = 0;
switch(op){
case 0:
free(FILA);
printf("\n\n\tFILA LIBERADA\n\n");
getchar();
exit(1);
break;
case 1:
num++;
inserir(FILA, num);
break;
case 2:
remover(FILA);
break;
case 3:
visualizar(FILA);
break;
default:
printf("\nOPCAO INVALIDA\n");
getchar();
break;
}
}
void inserir(node *FILA, int info){
if(FILA->info == NULL){
FILA->info = info;
printf("\n\tALOCADO VALOR %d\n\n", info);
}else{
node *NOVO = (node*) malloc(sizeof(node));
if(!NOVO){
printf("\n\tERRO DE ALOCACAO\n\n");
getchar();
exit(1);
}
printf("\n\tALOCADO VALOR %d\n\n", info);
NOVO->prox = NULL;
if(FILA->prox == NULL){
FILA->prox = NOVO;
}else{
node *AUX = FILA->prox;
while(AUX->prox != NULL)
AUX = AUX->prox;
AUX->prox = NOVO;
}
}
TAM++;
getchar();
}
void visualizar(node *FILA){
if(FILA->info == NULL){
printf("\n\tFILA VAZIA\n\n");
}else{
node *AUX = FILA;
printf("\n\tFILA:");
while(AUX != NULL){
printf("%9d", FILA->info);
AUX = AUX->prox;
}
printf("\n\n");
}
getchar();
}
void remover(node *FILA){
if(FILA->info == NULL){
printf("\n\tFILA NAO CONTEM ELEMENTOS\n\n");
}else if (TAM != 0){
printf("\n\tELEMENTO %d REMOVIDO DA FILA\n\n", FILA->info);
free(FILA->info);
TAM--;
if(TAM == 0){
FILA->info = NULL;
}
}
getchar();
}
<file_sep>//INFORME O TAMANHO DE DOIS VETORES. ALOQUE DOIS VETORES E ATRIBUA VALORES PARA ELES.
//CRIE UM TERCEIRO VETOR QUE SEJA A UNIÃO DOS DOIS PRIMEIROS.
//EX: V1 = {2,3,6,5};
// V2 = {9,58,3,2,0,0,1,5,6};
// V3 = {2,3,6,5,9,58,3,2,0,0,1,5,6};
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int* aloca(int n1, int n2);
int main(){
int i;
int n1 = 0, n2 = 0;
printf("\t\tUNIAO DE VETORES");
printf("\n\nQual o tamanho do primeiro vetor? ");
scanf("%d", &n1);//TAMANHO DO PRIMEIRO VETOR
printf("\n\nQual o tamanho do segundo vetor? ");
scanf("%d", &n2);//TAMANHO DO SEGUNDO VETOR
//----------------------------------------
int *v1 = (int *) calloc(n1, sizeof(int));//ALOCAÇÃO DE V1
if(v1 == NULL){//VERIFICAÇÃO DE ALOCAÇÃO
printf("\nV1 sem espaço suficiente\n");
exit(1);
}
int *v2 = (int *) calloc(n2, sizeof(int));//ALOCAÇÃO DE V2
if(v2 == NULL){//VERIFICAÇÃO DE ALOCAÇÃO
printf("\nV2 sem espaço suficiente\n");
exit(1);
}
int *v3 = (int *) calloc(n1+n2, sizeof(int));//ALOCAÇÃO DE V3
if(v3 == NULL){//VERIFICAÇÃO DE ALOCAÇÃO
printf("\nV3 sem espaço suficiente\n");
exit(1);
}
//----------------------------------------
for (i=0; i<n1; i++){//ATRIBUIÇÃO DE VALORES RANDÔMICOS EM V1
v1[i] = rand()%10;
}
printf("\n\nVetor 1: ");
for (i=0; i<n1; i++){
printf("%d ", v1[i]);
}
//----------------------------------------
for (i=0; i<n2; i++){//ATRIBUIÇÃO DE VALORES RANDÔMICOS EM V1
v2[i] = rand()%10;
}
printf("\n\nVetor 2: ");
for (i=0; i<n2; i++){
printf("%d ", v2[i]);
}
//----------------------------------------
for (i=0; i<n1; i++){//UNIÃO DE V1 E V2
v3[i] = v1[i];
}
for (i=0; i<n2; i++){
v3[i+n1] = v2[i];
}
//----------------------------------------
printf("\n\nVetor 3: ");//MOSTRA UNIÃO
for (i=0; i<n1+n2; i++){
printf("%d ", v3[i]);
}
printf("\n\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
typedef struct _node{
int info;
struct _node *next;
struct _node *prev;
}node;
typedef struct _index{
int id;
node *group;
struct _index *next;
struct _index *prev;
}index;
void view_groups(index *id){
index *aux_id = id;
node *aux_group;
for(aux_id = id; aux_id != NULL; aux_id = aux_id->next){
aux_group = aux_id->group;
printf("\tGRUPO %d: {", aux_id->id);
if(!aux_group->info){
while(aux_group->next != NULL){
printf("%d, ", aux_group->info);
aux_group = aux_group->next;
}
}else{
printf(" VAZIO ");
}
printf("}\n");
}
system("pause");
}
index *delete_group(index *id, int ref){
index *previous = NULL;
index *aux_id = id;
while(aux_id != NULL && aux_id->id != ref){
previous = aux_id;
aux_id = aux_id->next;
}
if (aux_id == NULL){
printf("\n\tGRUPO NAO ALOCADO\n");
system("pause");
return id;
}
if (previous == NULL){
id = aux_id->next;
}else{
previous->next = aux_id->next;
aux_id->prev = previous;
}
free(aux_id);
while(previous->next != NULL){
previous = previous->next;
previous->id--;
}
return id;
}
index *add_gr(index *id){
node *new_gr = (node *)malloc(sizeof(node));
index *new_id = (index *)malloc(sizeof(index));
if(!new_id){
printf("\nERRO DE ALOCACAO\n");
exit(1);
}
new_gr->info = 0;
new_gr->prev = new_id->group;
new_gr->next = NULL;
new_id->group = new_gr;
if(!id){
new_id->id = 1;
new_id->next = NULL;
new_id->prev = NULL;
return new_id;
}else{
index *aux_id = id;
while(aux_id->next != NULL){
aux_id = aux_id->next;
}
aux_id->next = new_id;
new_id->id = aux_id->id;
new_id->id++;
new_id->next = NULL;
new_id->prev = aux_id;
return id;
}
}
index *add_info(index *id, int ref, int info){
index *aux_id = id;
node *aux_group;
node *new = (node *)malloc(sizeof(node));
if(!new){
printf("\nERRO DE ALOCACAO\n");
exit(1);
}
new->info = info;
new->next = NULL;
while(aux_id->id != ref && aux_id->next != NULL){
aux_id = aux_id->next;
}
aux_group = aux_id->group;
while(aux_group->next != NULL){
aux_group = aux_group->next;
}
aux_group->next = new;
new->prev = aux_group;
return id;
}
int main(){
int op, ref, info, num, i;
index *id;
id = NULL;
do{
system("cls");
printf("\n\tTRABALHO NP1 - CONJUNTOS EM ALOCACAO DINAMICA\n\n");
printf("\n\tESCOLHA UMA OPCAO\n\n");
printf("\t0 - FECHAR\n");
printf("\t1 - INSERIR CONJUNTO\n");
printf("\t2 - REMOVER CONJUNTO\n");
printf("\t3 - INSERIR ELEMENTOS NO CONJUNTO\n");
printf("\t4 - REMOVER ELEMENTOS NO CONJUNTO\n");
printf("\t5 - VISUALIZAR CONJUNTOS\n");
//printf("\t5 - INTERSECCAO\n");
//printf("\t6 - UNIAO\n");
//printf("\t7 - DIFERENCA\n\n\t");
scanf("%d", &op);
switch(op){
case 0:
exit(1);
break;
case 1:
id = add_gr(id);
break;
case 2:
printf("\n\tQUAL GRUPO REMOVER? ");
scanf("%d", &ref);
id = delete_group(id, ref);
break;
case 3:
printf("\n\tSELECIONE O GRUPO: ");
scanf("%d", &ref);
printf("\tQUANTIDADE DE VALORES A INSERIR: ");
scanf("%d", &num);
for(i=0; i<num; i++){
scanf("%d", &info);
id = add_info(id, ref, info);
}
break;
case 4:
break;
case 5:
view_groups(id);
break;
case 6:
break;
case 7:
break;
}
}while(op);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
//DEFINIÇÃO DA ESTRUTURA PRINCIPAL DA FILA
struct NODE{
int info;
struct node *prox;
};
typedef struct NODE node;
struct CONTROL{
node *head;
node *rear;
};
typedef struct CONTROL control;
int main(){
control *HR;
HR->head = HR->rear = NULL;
node *FILA = (node *) malloc(sizeof(node));
if(!node){
printf("\n\t\tERRO DE ALOCACAO\n");
exit(1);
}else{
//FILA->prox = NULL;
//HR->head = FILA->info;
//HR->rear = FILA->info;
}
}
<file_sep>
//DEFINIÇÃO DA ESTRUTURA PRINCIPAL DA FILA
struct NODE{
int info;
struct node *prox;
};
typedef struct NODE node;
struct CONTROL{
node *head;
node *rear;
};
typedef struct CONTROL control;
void *opcao(int op);
void inserir(node *FILA, int info);
void visualizar(node *FILA);
void remover(node *FILA);
node *initFila();
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int i, TAM = 5, tecla = 0;
int *p = (int *) calloc(TAM, sizeof(int)); //ALOCA VETOR DE 5 POSIÇÕES
srand((unsigned) time(NULL)); // GERAÇÃO DE NÚMEROS RANDÔMICOS
if(p == NULL){//VERIFICAÇÃO DE ALOCAÇÃO
printf("Sem espaço suficiente\n");
exit(1);
}
for (i=0; i<TAM; i++){//DEFINE NÚMEROS ALEATORIOS PARA O VETOR.
p[i] = rand()%10;
}
do{//LAÇO PARA FICAR REALOCANDO MÉMORIA
printf("Realocar mais 5 inteiros? ENTER OU ESC. Tamanho: %d\n", TAM);
tecla = getch();
if (tecla == 13){
TAM = TAM + 5;
realloc(p, TAM*sizeof(int));//REALOCA PARA MAIS 5 INTEIROS
if(p == NULL){
printf("Sem espaço suficiente\n");//VERIFICA SE REALOCOU CORRETAMENTE
exit(1);
}
for (i=0; i<TAM; i++){
p[i] = rand()%10;//DEFINE NUMEROS ALEATÓRIOS PARA O VETOR REALOCADO
}
}
}while(tecla == 13);
for (i=0; i<TAM; i++){
printf("%d ", p[i]);//IMPRIME VETOR
}
free(p);//LIBERA O ESPAÇO DE MEMÓRIA
}
|
ad5e737269e685cb7b1c1df6f735d9f76d39bfa2
|
[
"C"
] | 8 |
C
|
elciofagundesboin/Estrutura_de_Dados_I_2016-1
|
76d42bc8c0e037d40204c23a1a7f8abdda61b1e4
|
0519eacbc14c289aadd0333b2f9af044a208947b
|
refs/heads/main
|
<file_sep>MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
profit = 0 # to hold the amount of money & machine has empty money in beggining
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
#Check resources sufficient? When the user chooses a drink, the program should check if there are enough resources to make that drink.
# user's current choice ingredient dictionary will be passed over to order ingredients as a input
def is_resource_sufficient(order_ingredients):
"""Returns True when order can be made, False if ingredients are insufficient."""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"Sorry there is not enough {item}.")
return False
return True
#5. Process coins.If there are sufficient resources to make the drink selected, then the program should prompt the user to insert coins.
def process_coins():
"""Return the total calculated from coins inserted"""
print (" Please insert coins ")
# total is the variable that we keep track on & we are gonna return as the output of this func
total = int(input("How many quarters?: ")) * 0.25 # formula of quarters with dollar
total += int(input("How many dimes?: ")) * 0.1 # += for added with current quarters
total = int(input("How many nickles?: ")) * 0.05
total = int(input("How many pennies?: ")) * 0.01
return total
#Check transaction successful? Check that the user has inserted enough money to purchase the drink they selected.
def is_transaction_successful(money_received, drink_cost):
"""Return True when the payment is accepted, or False if money is insufficient."""
if money_received >= drink_cost:
change = round(money_received - drink_cost, 2)
print(f"Here is ${change} in change.")
global profit
profit += drink_cost #initially profit is zero
return True
else:
print("Sorry that's not enough money. Money refunded.")
return False
#Make Coffee
def make_coffee(drink_name, order_ingredients):
"""Deduct the required ingredients from the resources."""
for item in order_ingredients:
resources[item] -= order_ingredients[item] #look inside the resources for that particular item & we are gonna subtract the amount thts in the order_ingredients
print(f"Here is your {drink_name} ☕️. Enjoy!")
#step1: Prompt user by asking “What would you like? (espresso/latte/cappuccino):Check the user’s input to decide what to do next.
is_on = True
#while is_on is true thn keep asking this prompt
while is_on:
choice = input("What would you like? (espresso/latte/cappuccino): ")
if choice == "off": #for maintenance guy bcz after getting the choice from user ask prompt should be off
is_on = False
elif choice == "report": # report gonna print all the value of the resources
print(f"Water: {resources['water']}ml")
print(f"Milk: 5{resources['milk']}ml")
print(f"Coffee:{resources['coffee']}g")
print(f"Money: ${profit}")
else:
drink = MENU[choice]
if is_resource_sufficient(drink["ingredients"]): #order_ingredient will be from the drink & hold the values under the key ingredient
payment = process_coins() #coins will be saved in payments
if is_transaction_successful(payment, drink["cost"] ): #money_recieved is basically the payment tht is calculated by coins
make_coffee(choice, drink["ingredients"]) #drink name is the choice given by user
|
c5f76b6372fb3f50b42e390090dd04a8bf5f6edd
|
[
"Python"
] | 1 |
Python
|
Genius98/Coffee_Machine_Project
|
5741d026c7ad9d14661b160caeafa3e74af92724
|
569d0ed0d77635dd1f478cff8b3f2d964cf1c90f
|
refs/heads/master
|
<repo_name>eimerreis/2wei-wall<file_sep>/packages/app/src/slides/index.ts
import { Home } from "./Home";
import { WelcomeSlide } from "./Welcome";
import { PlayersSlide } from "./Players";
export const Slides = [
{
id: "home",
component: Home,
},
{
id: "welcome",
component: WelcomeSlide
},
{
id: "players",
component: PlayersSlide
}
]<file_sep>/packages/server/src/ConfigurationReader.ts
export interface SamsConfig {
ApiKey: string;
ApiUrl: string;
TeamId: string;
MatchSeriesId: string;
}
interface Config {
Sams: SamsConfig;
}
export class ConfigurationReader {
public static GetConfig = (process: any): Config => {
return {
Sams: {
ApiKey: process.env.SAMS_API_KEY,
ApiUrl: process.env.SAMS_API_BASE_URL,
TeamId: process.env.SAMS_TEAM_ID,
MatchSeriesId: process.env.SAMS_MATCH_SERIES_ID
}
}
}
}<file_sep>/packages/wall-app/src/components/Table.types.ts
// Generated by https://quicktype.io
export interface TableResponse {
rankings: Rankings;
}
export interface Rankings {
matchSeries: MatchSeries;
ranking: Ranking[];
}
export interface MatchSeries {
id: string;
uuid: string;
allSeasonId: string;
name: string;
shortName: string;
type: string;
updated: string;
structureUpdated: string;
resultsUpdated: string;
season: Season;
hierarchy: Hierarchy;
fullHierarchy: FullHierarchy;
association: Association;
}
export interface Association {
name: string;
shortName: string;
}
export interface FullHierarchy {
hierarchy: Hierarchy[];
}
export interface Hierarchy {
id: string;
name: string;
shortName: string;
hierarchyLevel: string;
uuid?: string;
}
export interface Season {
id: string;
uuid: string;
name: string;
}
export interface Ranking {
team: Team;
place: string;
matchesPlayed: string;
wins: string;
losses: string;
points: string;
setPoints: SetPoints;
setWinScore: string;
setLoseScore: string;
setPointDifference: string;
setQuotient: string;
ballPoints: string;
ballWinScore: string;
ballLoseScore: string;
ballPointDifference: string;
ballQuotient: string;
resultTypes: ResultTypes;
}
export interface ResultTypes {
matchResult: MatchResult[];
}
export interface MatchResult {
result: SetPoints;
count: string;
}
export enum SetPoints {
The03 = "0:3",
The13 = "1:3",
The23 = "2:3",
The30 = "3:0",
The31 = "3:1",
The32 = "3:2",
}
export interface Team {
id: string;
uuid: string;
name: string;
shortName: string;
clubCode: string;
club: Club;
}
export interface Club {
name: string;
shortName: ShortName;
}
export interface ShortName {
}
<file_sep>/docs/Concept.md
# Concept for h2wei Video Wall App 2k19 Edition
## App which runs on the Wall
The VideoWall will be connected to a computer, that simply runs a browser window containing the webapp, that renders content.
This App will have the following functions:
1. Receiving WebSocket Events
### Types of Events
**RenderComponent Event**:
```json
{
"payload": "<div style="...">some content here</div>"
}
```
## WebSocket Server
- Get Current Table from SAMS API
- Get H2 Team (use an Azure Storage Account or a simple MongoDb for this maybe?).
- Get Oponnent Team (use SAMS API?)
- Get some Gifs of H2
## App which will send Events
- Retrieves stuff from API and Renders it to a React Component
- React Component will also be rendered as Markup and Sent via Websocket
<file_sep>/packages/wall-app/src/config.ts
export const Config = {
ApiUrl: "http://localhost:3001/api",
SocketUrl: "http://localhost:3001",
}<file_sep>/packages/server/src/sams-api/types/MatchesResponse.ts
// Generated by https://quicktype.io
export interface MatchesResponse {
matches: Matches;
}
export interface Matches {
"-xmlns": string;
"-xmlns:xsi": string;
"-xsi:schemaLocation": string;
match: Match[];
}
export interface Match {
id: string;
uuid: string;
number: string;
date: string;
time: string;
delayPossible: string;
decidingMatch: string;
indefinitelyRescheduled: string;
host: Host;
team: Team[];
matchSeries: MatchSeries;
location: Location;
referees?: Referees;
}
export interface Host {
id: string;
uuid: string;
name: string;
club?: string;
}
export interface Location {
id: string;
name: string;
street: string;
extraField: ExtraField;
postalCode: string;
city: string;
note: ExtraField;
}
export enum ExtraField {
Empty = "-",
}
export interface MatchSeries {
id: string;
uuid: string;
allSeasonId: string;
name: MatchSeriesName;
shortName: MatchSeriesShortName;
type: MatchSeriesType;
updated: string;
structureUpdated: string;
resultsUpdated: string;
season: Host;
hierarchy: Hierarchy;
fullHierarchy: FullHierarchy;
association: Association;
}
export interface Association {
name: AssociationName;
shortName: AssociationShortName;
}
export enum AssociationName {
Bereich2BLSüd = "Bereich 2.BL Süd",
DeutscherVolleyballVerband = "Deutscher Volleyball-Verband",
DritteLiga = "Dritte Liga",
DritteLigaSüd = "Dritte Liga Süd",
}
export enum AssociationShortName {
DLS = "DL S",
}
export interface FullHierarchy {
hierarchy: Hierarchy[];
}
export interface Hierarchy {
id: string;
name: AssociationName;
shortName: HierarchyShortName;
hierarchyLevel: string;
uuid?: string;
}
export enum HierarchyShortName {
DL = "DL",
Dls = "DLS",
Dvv = "DVV",
Süd = "Süd",
}
export enum MatchSeriesName {
DritteLigaSüdMänner = "Dritte Liga Süd Männer",
}
export enum MatchSeriesShortName {
DlsM = "DLS M",
}
export enum MatchSeriesType {
League = "League",
}
export interface Referees {
referee: Referee[];
}
export interface Referee {
type: RefereeType;
id: string;
lastname: string;
firstname: string;
city: string;
sex: Sex;
}
export enum Sex {
Männlich = "männlich",
Weiblich = "weiblich",
}
export enum RefereeType {
Beobachter = "Beobachter",
The1Schiedsrichter = "1. Schiedsrichter",
The2Schiedsrichter = "2. Schiedsrichter",
}
export interface Team {
number: string;
id: string;
uuid: string;
seasonTeamId: string;
name: string;
shortName: string;
clubCode: string;
club: Club;
}
export interface Club {
name: string;
}
<file_sep>/packages/wall-app/src/types/HomeGameResponse.ts
// Generated by https://quicktype.io
export interface HomeGameResponse {
id: string;
uuid: string;
number: string;
date: string;
time: string;
delayPossible: string;
decidingMatch: string;
indefinitelyRescheduled: string;
host: Host;
team: Team[];
matchSeries: MatchSeries;
location: Location;
referees: Referees;
}
export interface Host {
id: string;
uuid: string;
name: string;
club?: string;
}
export interface Location {
id: string;
name: string;
street: string;
extraField: string;
postalCode: string;
city: string;
note: string;
}
export interface MatchSeries {
id: string;
uuid: string;
allSeasonId: string;
name: string;
shortName: string;
type: string;
updated: string;
structureUpdated: string;
resultsUpdated: string;
season: Host;
hierarchy: Hierarchy;
fullHierarchy: FullHierarchy;
association: Association;
}
export interface Association {
name: string;
shortName: string;
}
export interface FullHierarchy {
hierarchy: Hierarchy[];
}
export interface Hierarchy {
id: string;
name: string;
shortName: string;
hierarchyLevel: string;
uuid?: string;
}
export interface Referees {
referee: Referee[];
}
export interface Referee {
type: string;
id: string;
title: Title;
lastname: string;
firstname: string;
city: string;
sex: string;
}
export interface Title {
}
export interface Team {
number: string;
id: string;
uuid: string;
seasonTeamId: string;
name: string;
shortName: string;
clubCode: string;
club: Club;
}
export interface Club {
name: string;
shortName: Title;
}
<file_sep>/Readme.md
# 2wei Wall App
## How to Run locally
### Install and Configure
- Run npm install in `/server` and `wall-app` directory
- Create a .env file in `/server` with the following content
```
SAMS_API_BASE_URL={{SamsApiUrlGoesHere}}
SAMS_API_KEY={{SamsApiSecretGoesHere}}
SAMS_TEAM_ID={{SamsTeamIdGoesHere}
SAMS_MATCH_SERIES_ID={{SamsMatchSeriesIdGoesHere}
```
### Run Server
To run the server locally, execute the following commands
- `cd /server`
- `yarn watch`
### Run Application
To run the app locally, execute the following commands
- `cd /wall-app`
- `npm run start`
## Controlling the Wall App
- navigate to `http://localhost:3000/remote-control`
## Adding new Home Players
- simply extend the `/server/src/tvr-players/players.json` file
## Ideas
- create Hooks for Websocket Connection
- `const { onEvent, send } = useWebhook("onSlideChange");
- could be used inside a WebhookContext.Provider, which set's up connection information etc
- use styled-components + it's server side rendering
- use framer motion for page transitions
- better handling of setTimeout
- error handling ist not there currently
- hosting + ci / cd
<file_sep>/packages/wall-app/src/services/WebsocketService.ts
import { Config } from "./../config";
import io from "socket.io-client";
function timeout(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export class WebsocketService {
private socket: SocketIOClient.Socket;
constructor() {
this.socket = io.connect(Config.SocketUrl);
}
private waitForConnection = async() => {
this.socket.connect();
while (!this.socket.connected) {
await timeout(1);
}
return;
}
ChangeSlide = async (markup: string) => {
await this.waitForConnection();
this.socket.emit("render-component", { markup });
this.socket.disconnect();
};
}
<file_sep>/packages/wall-app/README.md
# 2wei-wall
<file_sep>/packages/server/src/sams-api/SamsApiClient.ts
import { PastMatchesResponse } from './types/PastMatchesResponse';
import { MatchesResponse } from './types/MatchesResponse';
import axios from "axios";
import parser from "xml2json";
import { TableResponse } from './types/TableResponse';
import { SamsConfig } from "../ConfigurationReader";
export class SamsApiClient {
private baseUrl = ""
constructor(private config: SamsConfig) {}
private getJsonResponse = (xmlResponse: string) => {
return JSON.parse(parser.toJson(xmlResponse));
}
GetCurrentTable = async (): Promise<TableResponse> => {
const url = `${this.config.ApiUrl}/rankings.xhtml?apiKey=${this.config.ApiKey}&matchSeriesId=${this.config.MatchSeriesId}`;
const response = await axios.get(url, { responseType: "document"});
return this.getJsonResponse(response.data);
}
GetFutureMatches = async (): Promise<MatchesResponse> => {
const { ApiUrl, ApiKey, TeamId } = this.config;
const url = `${ApiUrl}/matches.xhtml?apiKey=${ApiKey}&future=true&teamId=${TeamId}`;
const response = await axios.get(url, {responseType: "document"});
return this.getJsonResponse(response.data);
}
GetPastMatches = async (): Promise<PastMatchesResponse> => {
const { ApiUrl, ApiKey, TeamId } = this.config;
const url = `${ApiUrl}/matches.xhtml?apiKey=${ApiKey}&past=true&teamId=${TeamId}`;
const response = await axios.get(url, {responseType: "document"});
return this.getJsonResponse(response.data);
}
}<file_sep>/packages/server/Readme.md
# 2wei Wall Backend
## Get Started
```bash
npm install
```
> If running on Windows and npm install fails:
> Run `npm install --global --production windows-build-tools` in a PowerShell Window **with admin permissions**
<file_sep>/packages/server/src/index.ts
import { TvrPlayerService } from './tvr-players/TvrPlayerService';
import { SamsApiClient } from './sams-api/SamsApiClient';
import { ConfigurationReader } from './ConfigurationReader';
import { RenderComponentEvent, RenderComponentPayload } from './../../shared/events/RenderComponentEvent';
import { ChangeSlideEvent, ChangeSlideEventPayload } from '../../shared/events/ChangeSlideEvent';
import express from "express";
import cors from "cors";
import * as http from "http";
import socketio from "socket.io";
const app = express();
app.set("port", process.env.PORT || 3001);
app.use(cors());
const config = ConfigurationReader.GetConfig(process);
const apiClient = new SamsApiClient(config.Sams);
const tvrService = new TvrPlayerService();
app.get("/api/table", async (req, res) => {
res.send(await apiClient.GetCurrentTable());
})
app.get("/api/future-matches", async (req, res) => {
res.send(await apiClient.GetFutureMatches());
})
app.get("/api/past-matches", async (req, res) => {
res.send(await apiClient.GetPastMatches());
})
app.get("/api/next-home-game", async (req, res) => {
const games = await apiClient.GetFutureMatches();
const homeGames = games.matches.match.filter(x => x.host.id === config.Sams.TeamId);
if(homeGames) {
res.send(homeGames[1]);
} else {
res.send("no-home-games-anymore");
}
})
app.get("/api/tvr-players", (req, res) => {
res.send(tvrService.GetPlayers());
});
const httpServer = new http.Server(app);
// set up socket.io and bind it to our
// http server.
const io = socketio(httpServer);
app.get("/", (req: any, res: any) => {
res.send("hallo kleiner bumsi");
});
// whenever a user connects on port 3000 via
// a websocket, log that a user has connected
io.on("connection", function(socket: socketio.Socket) {
console.log("a user connected");
socket.on(ChangeSlideEvent.EventId, (payload: ChangeSlideEventPayload) => {
console.log("change slide event received");
io.emit(ChangeSlideEvent.EventId, payload);
});
socket.on(RenderComponentEvent.EventId, (payload: RenderComponentPayload) => {
console.log("change slide event with payload " + JSON.stringify(payload));
io.emit(RenderComponentEvent.EventId, payload);
})
});
httpServer.listen(process.env.PORT || 3001, () => {
console.log("server is listenning");
});<file_sep>/packages/server/src/tvr-players/TvrPlayerService.ts
import players from "./players.json";
export class TvrPlayerService {
GetPlayers = () => {
return players;
}
}<file_sep>/packages/wall-app/src/automations/AllAutomation.ts
import { HomePlayersAutomation } from './HomePlayers';
import { ResultsAutomation } from './ResultsAutomation';
export const AllAutomation = async () => {
await HomePlayersAutomation();
await ResultsAutomation();
}<file_sep>/packages/shared/events/EventBase.ts
export abstract class EventBase<T> {
abstract validate(payload: T): void;
}<file_sep>/packages/shared/events/RenderComponentEvent.ts
import { EventBase } from "./EventBase";
export interface RenderComponentPayload {
markup: string;
transition: "SlideTop" | "FadeIn"
}
export class RenderComponentEvent extends EventBase<RenderComponentPayload> {
public static EventId = "render-component";
validate(payload: RenderComponentPayload) {
if(!payload.markup) {
throw new Error("Property 'markup' was missing in RenderComponentPayload");
}
}
constructor(public payload: RenderComponentPayload) {
super();
this.validate(payload);
}
}<file_sep>/packages/app/src/assets/Sponsors.ts
export const Sponsors = [
"<NAME>",
"Apotheke am Markt",
"<NAME> e.K.",
"Bien-Zenker GmbH",
"Brillinger GmbH & CO. KG",
"Der Elektromann (<NAME> und <NAME> GbR)",
"DGM Kommunikation",
"Edel GmbH & Co. KG",
"<NAME>",
"<NAME>",
"ETAPART AG ",
"Feral GmbH",
"Fliesenfachgeschäft <NAME>",
"Gauss Ingenieurtechnik GmbH",
"Gebr. Stumpp Bauunternehmung GmbH & Co. KG",
"<NAME> Fuhrunternehmen GmbH",
"H+B Bauprojekte GmbH",
"Hecon Abrechnungssysteme GmbH",
"Immobilen Merz GmbH",
"Zahnarzt <NAME>",
"Kaya Sanitärtechnik",
"Karosserie-Baur GmbH",
"KEMPA - uhlsport GmbH",
"Kreissparkasse Tübingen",
"Krokodil Gastronomiebetriebe GmbH",
"Kronenbrauerei Alfred Schimpf GmbH",
"Liedtke Autowaschcenter",
"Micki Sport Handels GmbH",
"Modehaus Weippert & Co. OHG",
"<NAME>",
"Pizza + Pasta Rottenburg",
"Physio-MED med. Kooperationsgemeinschaft GbR",
"Pulvermüller - Christoph Unger GmbH & Co. KG",
"Rino - Eiscafé by <NAME>",
"Römer-Apotheke",
"RWT REUTLINGER WIRTSCHAFTSTREUHAND GMBH",
"Scheck Bad und Heizung",
"<NAME>",
"Schloss Weitenburg",
"Scirotec GmbH",
"Sportpark 1861 TV Rottenburg",
"Stadtwerke Rottenburg am Neckar GmbH",
"Tierärztliche Hausapotheken GmbH",
"TransPak AG",
"VOELKER & Partner Rechtsanwälte Wirtschaftsprüfer Steuerberater",
"Wachendorfer GbR Glaserei & Fensterbau",
"Winfried Riegger GmbH",
"Winghofer Medicum Klinik GmbH",
"Zahnarzt Dr. Kocher",
"Stuckateur Steger GmbH",
"Volksbank Herrenberg-Nagold-Rottenburg",
"<NAME>",
"Brunnenstube",
"Druckerei Maier GmbH",
"<NAME>",
"<NAME>",
"kesslerundkern",
"<NAME> WOHNKONZEPT GMBH",
"<NAME> Bloemsaat GmbH",
"Wizemann Computerservice",
"Sitzi",
]<file_sep>/packages/wall-app/src/automations/index.ts
import { HomePlayersAutomation } from './HomePlayers';
import { ResultsAutomation } from './ResultsAutomation';
import { AllAutomation } from './AllAutomation';
type AutomationMapping = {
[key in Automations]: () => Promise<any>;
}
export const AutomationMappings: AutomationMapping = {
"HomePlayers": HomePlayersAutomation,
"Results": ResultsAutomation,
"All": AllAutomation,
}
export enum Automations {
All = "All",
HomePlayers = "HomePlayers",
Results = "Results"
} <file_sep>/packages/shared/events/ChangeSlideEvent.ts
import { EventBase } from "./EventBase";
export interface ChangeSlideEventPayload {
id: string;
number?: string;
}
export class ChangeSlideEvent extends EventBase<ChangeSlideEventPayload> {
public static EventId = "change-slide";
validate(payload: ChangeSlideEventPayload) {
if(!payload.id) {
throw new Error("Property 'id' of ChangeSlideEventPayload is missing or invalid");
}
}
constructor(public payload: ChangeSlideEventPayload) {
super();
this.validate(payload);
}
}
|
b2b8e88a75ffb92892a1c3e77e62f72d78fe3c5a
|
[
"Markdown",
"TypeScript"
] | 20 |
TypeScript
|
eimerreis/2wei-wall
|
a3e659dbf535482a4369eb6be75de3ff62eaca03
|
c13f9413dc426cb225a0f17343c17d6ab10daae3
|
refs/heads/master
|
<file_sep>from Model.model import *
from util import *
from evaluation import *
import numpy as np
from glob import glob
import cv2
from time import clock
# net parameter setting
Usage_net = "VGGUnet"
Image_x_size = 384
Image_y_size = 384
Image_channels = 3
Seg_classes = 1
batch_size = 10
if __name__ == '__main__':
# network initialize
VGGUnet = Network(Usage_net, Image_y_size, Image_x_size, Image_channels, Seg_classes)
VGGUnet.restore(model_path = 'ckpt/')
#ground truth preprocess
ground_truth, ground_truth_not_merge = ground_truth_read()
test_file_path = glob('test/*')
total_TP = np.zeros(10)
total_FN = np.zeros(10)
total_FP = np.zeros(10)
total_F2_score = 0
for i in range(len(test_file_path)):
input_image = test_image_open(ground_truth, test_file_path[i], Image_x_size, Image_y_size, batch_size)
file_name = test_file_path[i].split('/')[7]
print('\nfile name:', file_name)
ground_truth_image = ground_truth_open(ground_truth, file_name)
test_result = VGGUnet.predict(input_image)
test_training_result = test_result[0]
test_image = (test_training_result * 255).astype(np.uint8)
test_image_resize = cv2.resize(test_image, (768, 768), interpolation = cv2.INTER_LINEAR)
test_image_resize = test_image_resize.reshape(768, 768, 1)
threshold_test_index = test_image_resize[:,:,:] > 127
threshold_test = np.zeros((768, 768, 1), dtype = np.uint8)
threshold_test[threshold_test_index] = 255
TP, FN, FP = test_image_evaluation(ground_truth_not_merge, file_name, threshold_test)
total_TP = total_TP + TP
total_FN = total_FN + FN
total_FP = total_FP + FP
single_F2_score = F2_score(TP, FN, FP)
total_F2_score = total_F2_score + single_F2_score
print('True Positive :', TP)
print('False Negative :', FN)
print('False Positive :', FP)
print('single F2 score:', single_F2_score)
print('Total F2 score:', total_F2_score / (i + 1))
cv2.namedWindow('original_image', cv2.WINDOW_NORMAL)
cv2.namedWindow('threshold result', cv2.WINDOW_NORMAL)
cv2.namedWindow('ground_truth', cv2.WINDOW_NORMAL)
cv2.imshow('original_image', cv2.imread(test_file_path[i]))
cv2.imshow('threshold result', threshold_test)
cv2.imshow('ground_truth', ground_truth_image)
if cv2.waitKey(0) == 27:
break
<file_sep>from layer import *
from mlxtend.data import loadlocal_mnist
import tensorflow as tf
import numpy as np
import cv2
inputs = tf.placeholder(tf.float32, shape = [None, 28, 28, 1], name = 'input')
ground_truth = tf.placeholder(tf.int32, shape = [None, 28, 28, 1], name = 'ground_truth')
keep_prob = tf.placeholder(tf.float32, name = 'dropout_probability')
conv_1 = conv_layer(inputs, conv_size = 3, output_depth = 64, name = 'layer1')
conv_1 = conv_layer(conv_1, conv_size = 3, output_depth = 64, name = 'layer2')
pool_1 = max_pooling_layer(conv_1, 2)
conv_2 = conv_layer(pool_1, conv_size = 3, output_depth = 128, name = 'layer3')
conv_2 = conv_layer(conv_2, conv_size = 3, output_depth = 128, name = 'layer4')
pool_2 = max_pooling_layer(conv_2, 2)
conv_3 = conv_layer(pool_2, conv_size = 3, output_depth = 256, name = 'layer5')
conv_3 = conv_layer(conv_3, conv_size = 3, output_depth = 256, name = 'layer6')
pool_3 = max_pooling_layer(conv_3, 2)
conv_4 = conv_layer(pool_3, conv_size = 3, output_depth = 512, name = 'layer7')
conv_4 = conv_layer(conv_4, conv_size = 3, output_depth = 512, name = 'layer8')
drop_4 = dropout_layer(conv_4, keep_prob)
pool_4 = max_pooling_layer(drop_4, 2)
conv_5 = conv_layer(pool_4, conv_size = 3, output_depth = 1024, name = 'layer9')
conv_5 = conv_layer(conv_5, conv_size = 3, output_depth = 1024, name = 'layer10')
drop_5 = dropout_layer(conv_5, keep_prob)
deconv_6 = deconv_layer(drop_5, conv_size = 2, output_depth = 512, stride = 2, name = 'layer11')
concat_6 = concat_layer(drop_4, deconv_6)
conv_6 = conv_layer(concat_6, conv_size = 3, output_depth = 512, name = 'layer12')
conv_6 = conv_layer(conv_6, conv_size = 3, output_depth = 512, name = 'layer13')
deconv_7 = deconv_layer(conv_6, conv_size = 2, output_depth = 256, stride = 2, name = 'layer14')
concat_7 = concat_layer(conv_3, deconv_7)
conv_7 = conv_layer(concat_7, conv_size = 3, output_depth = 256, name = 'layer15')
conv_7 = conv_layer(conv_7, conv_size = 3, output_depth = 256, name = 'layer16')
deconv_8 = deconv_layer(conv_7, conv_size = 2, output_depth = 128, stride = 2, name = 'layer17')
concat_8 = concat_layer(conv_2, deconv_8)
conv_8 = conv_layer(concat_8, conv_size = 3, output_depth = 128, name = 'layer18')
conv_8 = conv_layer(conv_8, conv_size = 3, output_depth = 128, name = 'layer19')
deconv_9 = deconv_layer(deconv_8, conv_size = 2, output_depth = 64, stride = 2, name = 'layer20')
concat_9 = concat_layer(conv_1, deconv_9)
conv_9 = conv_layer(concat_9, conv_size = 3, output_depth = 64, name = 'layer21')
conv_9 = conv_layer(conv_9, conv_size = 3, output_depth = 64, name = 'layer22')
conv_10 = conv_layer(conv_9, conv_size = 1, output_depth = 1, name = 'layer23',
activation_function = tf.nn.sigmoid, normalize = False)
loss = image_binary_entropy(conv_6, ground_truth)
optimizer = tf.train.AdamOptimizer(1e-2)
train_step = optimizer.minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
# Initialize variables
sess.run(init)
#load training data
image, label = loadlocal_mnist(
images_path = ('/media/jianjie/cf360de1-1e04-496f-aca5-083f49b831bb/tensorflow_test/'
'mnist dataset/train-images.idx3-ubyte'),
labels_path = ('/media/jianjie/cf360de1-1e04-496f-aca5-083f49b831bb/tensorflow_test/'
'mnist dataset/train-labels.idx1-ubyte'))
#set batch size
batch_size = 100
batch_number = np.array(image.shape[0] / batch_size).astype(np.int32)
# #training
print('Training ------------')
program_end = False
for epoch in range(2):
for batch in range(batch_number):
batch_image = []
for i in range(batch_size):
single_image = image[batch * batch_size + i].reshape([28, 28, 1])
threshold_index = single_image[:, :, :] > 10
single_image[threshold_index] = 255
single_image = single_image / 255
try:
batch_image.append(single_image)
except:
batch_image = single_image
batch_image = np.array(batch_image)
sess.run(train_step, feed_dict = {inputs: batch_image, ground_truth: batch_image, keep_prob: 0.5 })
train_loss = sess.run(loss, feed_dict = {inputs: batch_image, ground_truth: batch_image,
keep_prob: 1})
test = sess.run(conv_6, feed_dict = {inputs: batch_image, keep_prob: 1})
print('epoch:', epoch)
print('batch:', batch)
print('loss:', train_loss)
if epoch == 1:
test_single = (test[0] * 255).astype(np.uint8)
print('image max value:',np.max(test_single))
threshold_test_index = test_single[:,:,:] > 127
threshold_test = np.zeros((28,28,1), dtype = np.uint8)
threshold_test[threshold_test_index] = 255
cv2.imshow('test', test_single)
cv2.imshow('threshold', threshold_test)
cv2.imshow('original', batch_image[0])
if cv2.waitKey(33) == 27:
program_end = True
break
if program_end:
break
# ckpt_name = "ckpt/cnn_model_" + str(epoch + 1) + ".ckpt"
# save_path = saver.save(sess, ckpt_name)
# print("model save path:", save_path)
<file_sep>from util import *
import numpy as np
from glob import glob
import cv2
def test_image_evaluation(ground_truth, file_name, test_image):
label_number, labels = cv2.connectedComponents(test_image)
label_number = label_number - 1
total_single_label = []
total_single_test = []
iou_threshold = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]
TP = np.zeros(len(iou_threshold))
FP = np.zeros(len(iou_threshold))
FN = np.zeros(len(iou_threshold))
# if there have ship
if file_name in ground_truth:
ground_truth_number = len(ground_truth[file_name])
# ground truth single ship image create
for i in range(ground_truth_number):
single_label_flat = np.zeros((768 * 768))
for j in range(int(len(ground_truth[file_name][i]) / 2)):
for k in range(int(ground_truth[file_name][i][j * 2 + 1])):
single_label_flat[int(ground_truth[file_name][i][j * 2]) + k - 1] = 1
single_label = single_label_flat.reshape((768, 768, 1)).swapaxes(1,0)
total_single_label.append(single_label)
# test single image create
for i in range(1, label_number + 1):
single_test = np.zeros((768, 768))
single_test[labels == i] = 1
single_test = single_test.reshape(768, 768, 1)
total_single_test.append(single_test)
# pair ground truth and test
GT_index = np.ones((len(iou_threshold), ground_truth_number))
test_index = np.ones((len(iou_threshold), label_number))
for i in range(ground_truth_number):
for j in range(label_number):
intersection = np.sum(np.multiply(total_single_label[i], total_single_test[j]))
ground_truth_region = np.sum(total_single_label[i])
test_region = np.sum(total_single_test[j])
iou = intersection / (ground_truth_region + test_region - intersection)
for k in range(len(iou_threshold)):
if iou >= iou_threshold[k]:
GT_index[k, i] = 0
test_index[k, j] = 0
TP[k] = TP[k] + 1
FN = np.sum(GT_index, axis = 1)
FP = np.sum(test_index, axis = 1)
return TP, FN, FP
else:
TP = np.zeros(len(iou_threshold))
FP = np.ones(len(iou_threshold)) * label_number
FN = np.zeros(len(iou_threshold))
return TP, FN, FP
def F2_score(TP, FN, FP):
beta = 2
iou_threshold = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]
if np.sum(TP + FN + FP) != 0:
F_beta = (1 + np.power(beta, 2)) * TP / ((1 + np.power(beta, 2)) * TP + np.power(beta, 2) * FN + FP)
score = np.sum(F_beta) / len(iou_threshold)
else:
score = 1
return score<file_sep>from Model.model import *
from util import *
import numpy as np
from glob import glob
import cv2
from time import clock
# net parameter setting
Usage_net = "VGGUnet"
Image_x_size = 384
Image_y_size = 384
Image_channels = 3
Seg_classes = 1
epoches_num = 1
batch_size = 10
if __name__ == '__main__':
# network initialize
VGGUnet = Network(Usage_net, Image_y_size, Image_x_size, Image_channels, Seg_classes, pretrain_path = 'vgg16_weights.npz')
VGGUnet._initialize(learning_rate = 1e-4)
# VGGUnet.restore(model_path = 'ckpt/model_384_4epochs/', epochs = 4)
#ground truth preprocess
ground_truth, ground_truth_not_merge = ground_truth_read()
total_file_name = list(enumerate(ground_truth))
batch_number = int(len(ground_truth) / batch_size)
print("batch_number:", batch_number)
for epoch in range(epoches_num):
print('Epoch %3d/%-3d' %(epoch + 1, epoches_num))
loss_sum = 0
for batch in range(batch_number):
input_image = train_image_data_open(total_file_name, Image_x_size, Image_y_size, batch_size, batch)
input_label = train_GT_data_open(ground_truth, total_file_name, Image_x_size, Image_y_size, batch_size, batch)
training_loss = VGGUnet.train(input_image, input_label)
loss_sum = loss_sum + training_loss
print_state(batch_number * batch_size, batch * batch_size, 'loss', training_loss, batch_size)
print("epoch = " , epoch, "average loss = " ,loss_sum / batch_number)
ckpt_name = "ckpt/" + Usage_net + "_model_" + str(epoch + 1) + ".ckpt"
save_path = VGGUnet.save(ckpt_name)
print("model save path:", save_path)
<file_sep>import numpy as np
from glob import glob
import cv2
import random
def ground_truth_read():
# input image & ground truth load
file_ground_truth = open(('/media/jianjie/cf360de1-1e04-496f-aca5-083f49b831bb/airbus ship/'
'all/train_ship_segmentations_v2.csv'))
ground_truth_data = np.array(file_ground_truth.readlines())
# ground truth label split
# only positive sample
GT_dict_merge = {}
GT_dict_not_merge = {}
positive_file_name = []
print('Ground Truth processing----------')
for i in range(1, len(ground_truth_data)):
file_name = ground_truth_data[i].strip('\n').split(',')[0]
file_data = (ground_truth_data[i].strip('\n').split(',')[1]).split(' ')
file_data_list = np.copy(file_data)
if file_data[0] != '':
if file_name in GT_dict_merge:
GT_dict_merge[file_name].extend(file_data)
GT_dict_not_merge[file_name].extend([file_data_list])
else:
GT_dict_merge[file_name] = file_data
GT_dict_not_merge[file_name] = [file_data_list]
try:
positive_file_name.append(file_name)
except:
positive_file_name = file_name
print_state(len(ground_truth_data), i, 'file name', file_name)
print('Ground Truth processing Done----------')
return GT_dict_merge, GT_dict_not_merge
def test_image_open(ground_truth, test_image_path, Image_x_size, Image_y_size, batch_size):
batch_image = []
total_file_name = list(enumerate(ground_truth))
file_name = test_image_path.split('/')[7]
path_image = ('/media/jianjie/cf360de1-1e04-496f-aca5-083f49b831bb/airbus ship/all/train_v2/' +
file_name)
single_image = cv2.imread(path_image)
single_image_resize = cv2.resize(single_image, (Image_x_size, Image_y_size), interpolation = cv2.INTER_NEAREST)
batch_image.append(single_image_resize)
for i in range(batch_size - 1):
random_number = int(random.random() * len(ground_truth))
file_name = total_file_name[random_number][1]
path_image = ('/media/jianjie/cf360de1-1e04-496f-aca5-083f49b831bb/airbus ship/all/train_v2/' +
file_name)
single_image = cv2.imread(path_image)
single_image_resize = cv2.resize(single_image, (Image_x_size, Image_y_size), interpolation = cv2.INTER_NEAREST)
batch_image.append(single_image_resize)
return np.array(batch_image)
def train_image_data_open(total_file_name, Image_x_size, Image_y_size, batch_size, batch_number):
batch_image = []
start_number = batch_number * batch_size
end_number = start_number + batch_size
for i in range(start_number, end_number):
file_name = total_file_name[i][1]
try:
path_image = ('/media/jianjie/cf360de1-1e04-496f-aca5-083f49b831bb/airbus ship/all/train_v2/' +
file_name)
single_image = cv2.imread(path_image)
except:
print(file_name, end = '')
print('file doesn`t exist')
continue
single_image_resize = cv2.resize(single_image, (Image_x_size, Image_y_size), interpolation = cv2.INTER_LINEAR)
batch_image.append(single_image_resize)
return np.array(batch_image)
def train_GT_data_open(ground_truth, total_file_name, Image_x_size, Image_y_size, batch_size, batch_number):
batch_label = []
start_number = batch_number * batch_size
end_number = start_number + batch_size
for i in range(start_number, end_number):
file_name = total_file_name[i][1]
single_label = ground_truth_open(ground_truth, file_name)
single_label_resize = cv2.resize(single_label, (Image_x_size, Image_y_size), interpolation = cv2.INTER_NEAREST)
single_label_resize = single_label_resize.reshape((Image_x_size, Image_y_size, 1))
batch_label.append(single_label_resize)
return np.array(batch_label)
def ground_truth_open(ground_truth, file_name):
single_label_flat = np.zeros((768 * 768))
try:
for j in range(int(len(ground_truth[file_name]) / 2)):
for k in range(int(ground_truth[file_name][j * 2 + 1])):
single_label_flat[int(ground_truth[file_name][j * 2]) + k - 1] = 1
single_label = single_label_flat.reshape((768, 768, 1)).swapaxes(1,0)
except:
single_label = np.zeros((768,768,1))
return single_label
def print_state(total_state, current_state, variable_name, variable, state_grid = 1):
print('%d/%d'%(current_state + state_grid, total_state), '[', end = '')
for j in range(25):
if ((current_state + state_grid) / total_state) >= ((j + 1) / 25):
print('=', end = '')
else:
print('.', end = '')
print(']', variable_name, ':', variable, end = '\r')
if current_state == total_state - state_grid:
print(end = '\n')
<file_sep># VGGUnet
The VGG pretrain weights:
https://www.cs.toronto.edu/~frossard/post/vgg16/?fbclid=IwAR2xbvKY51E5tZtz2r88c9vcEP1VIBxAu9boBeLoXIFxv3h68lFMa8LrSqU
<file_sep>import tensorflow as tf
import numpy as np
import cv2
import logging
from .layer import *
def Unet(inputs, keep_prob = 1):
conv_1 = conv_layer(inputs, conv_size = 3, output_depth = 64, name = 'layer1')
conv_1 = conv_layer(conv_1, conv_size = 3, output_depth = 64, name = 'layer2')
pool_1 = max_pooling_layer(conv_1, 2)
conv_2 = conv_layer(pool_1, conv_size = 3, output_depth = 128, name = 'layer3')
conv_2 = conv_layer(conv_2, conv_size = 3, output_depth = 128, name = 'layer4')
pool_2 = max_pooling_layer(conv_2, 2)
conv_3 = conv_layer(pool_2, conv_size = 3, output_depth = 256, name = 'layer5')
conv_3 = conv_layer(conv_3, conv_size = 3, output_depth = 256, name = 'layer6')
pool_3 = max_pooling_layer(conv_3, 2)
conv_4 = conv_layer(pool_3, conv_size = 3, output_depth = 512, name = 'layer7')
conv_4 = conv_layer(conv_4, conv_size = 3, output_depth = 512, name = 'layer8')
drop_4 = dropout_layer(conv_4, keep_prob)
pool_4 = max_pooling_layer(drop_4, 2)
conv_5 = conv_layer(pool_4, conv_size = 3, output_depth = 1024, name = 'layer9')
conv_5 = conv_layer(conv_5, conv_size = 3, output_depth = 1024, name = 'layer10')
drop_5 = dropout_layer(conv_5, keep_prob)
deconv_6 = deconv_layer(drop_5, conv_size = 2, output_depth = 512, stride = 2, name = 'layer11')
concat_6 = concat_layer(drop_4, deconv_6)
conv_6 = conv_layer(concat_6, conv_size = 3, output_depth = 512, name = 'layer12')
conv_6 = conv_layer(conv_6, conv_size = 3, output_depth = 512, name = 'layer13')
deconv_7 = deconv_layer(conv_6, conv_size = 2, output_depth = 256, stride = 2, name = 'layer14')
concat_7 = concat_layer(conv_3, deconv_7)
conv_7 = conv_layer(concat_7, conv_size = 3, output_depth = 256, name = 'layer15')
conv_7 = conv_layer(conv_7, conv_size = 3, output_depth = 256, name = 'layer16')
deconv_8 = deconv_layer(conv_7, conv_size = 2, output_depth = 128, stride = 2, name = 'layer17')
concat_8 = concat_layer(conv_2, deconv_8)
conv_8 = conv_layer(concat_8, conv_size = 3, output_depth = 128, name = 'layer18')
conv_8 = conv_layer(conv_8, conv_size = 3, output_depth = 128, name = 'layer19')
deconv_9 = deconv_layer(deconv_8, conv_size = 2, output_depth = 64, stride = 2, name = 'layer20')
concat_9 = concat_layer(conv_1, deconv_9)
conv_9 = conv_layer(concat_9, conv_size = 3, output_depth = 64, name = 'layer21')
conv_9 = conv_layer(conv_9, conv_size = 3, output_depth = 64, name = 'layer22')
conv_10 = conv_layer(conv_9, conv_size = 1, output_depth = 1, name = 'layer23',
activation_function = tf.nn.sigmoid, normalize = False)
return conv_10
def VGGUnet(inputs, keep_prob = 1, parameter = None):
conv_1 = conv_layer(inputs, conv_size = 3, output_depth = 64, name = 'layer1', parameter = parameter)
conv_1 = conv_layer(conv_1, conv_size = 3, output_depth = 64, name = 'layer2', parameter = parameter)
pool_1 = max_pooling_layer(conv_1, 2)
conv_2 = conv_layer(pool_1, conv_size = 3, output_depth = 128, name = 'layer3', parameter = parameter)
conv_2 = conv_layer(conv_2, conv_size = 3, output_depth = 128, name = 'layer4', parameter = parameter)
pool_2 = max_pooling_layer(conv_2, 2)
conv_3 = conv_layer(pool_2, conv_size = 3, output_depth = 256, name = 'layer5', parameter = parameter)
conv_3 = conv_layer(conv_3, conv_size = 3, output_depth = 256, name = 'layer6', parameter = parameter)
conv_3 = conv_layer(conv_3, conv_size = 3, output_depth = 256, name = 'layer7', parameter = parameter)
pool_3 = max_pooling_layer(conv_3, 2)
conv_4 = conv_layer(pool_3, conv_size = 3, output_depth = 512, name = 'layer8', parameter = parameter)
conv_4 = conv_layer(conv_4, conv_size = 3, output_depth = 512, name = 'layer9', parameter = parameter)
conv_4 = conv_layer(conv_4, conv_size = 3, output_depth = 512, name = 'layer10', parameter = parameter)
drop_4 = dropout_layer(conv_4, keep_prob)
pool_4 = max_pooling_layer(drop_4, 2)
conv_5 = conv_layer(pool_4, conv_size = 3, output_depth = 512, name = 'layer11', parameter = parameter)
conv_5 = conv_layer(conv_5, conv_size = 3, output_depth = 512, name = 'layer12', parameter = parameter)
conv_5 = conv_layer(conv_5, conv_size = 3, output_depth = 512, name = 'layer13', parameter = parameter)
drop_5 = dropout_layer(conv_5, keep_prob)
deconv_6 = deconv_layer(drop_5, conv_size = 2, output_depth = 512, stride = 2, name = 'layer14')
concat_6 = concat_layer(drop_4, deconv_6)
conv_6 = conv_layer(concat_6, conv_size = 3, output_depth = 512, name = 'layer15')
conv_6 = conv_layer(conv_6, conv_size = 3, output_depth = 512, name = 'layer16')
deconv_7 = deconv_layer(conv_6, conv_size = 2, output_depth = 256, stride = 2, name = 'layer17')
concat_7 = concat_layer(conv_3, deconv_7)
conv_7 = conv_layer(concat_7, conv_size = 3, output_depth = 256, name = 'layer18')
conv_7 = conv_layer(conv_7, conv_size = 3, output_depth = 256, name = 'layer19')
deconv_8 = deconv_layer(conv_7, conv_size = 2, output_depth = 128, stride = 2, name = 'layer20')
concat_8 = concat_layer(conv_2, deconv_8)
conv_8 = conv_layer(concat_8, conv_size = 3, output_depth = 128, name = 'layer21')
conv_8 = conv_layer(conv_8, conv_size = 3, output_depth = 128, name = 'layer22')
deconv_9 = deconv_layer(deconv_8, conv_size = 2, output_depth = 64, stride = 2, name = 'layer23')
concat_9 = concat_layer(conv_1, deconv_9)
conv_9 = conv_layer(concat_9, conv_size = 3, output_depth = 64, name = 'layer24')
conv_9 = conv_layer(conv_9, conv_size = 3, output_depth = 64, name = 'layer25')
conv_10 = conv_layer(conv_9, conv_size = 1, output_depth = 1, name = 'layer26',
activation_function = tf.nn.sigmoid, normalize = False)
return conv_10
def fault_Unet(inputs, keep_prob = 1):
conv_1 = conv_layer(inputs, conv_size = 3, output_depth = 64, name = 'layer1')
conv_1 = conv_layer(conv_1, conv_size = 3, output_depth = 64, name = 'layer2')
pool_1 = max_pooling_layer(conv_1, 2)
conv_2 = conv_layer(pool_1, conv_size = 3, output_depth = 128, name = 'layer3')
conv_2 = conv_layer(conv_2, conv_size = 3, output_depth = 128, name = 'layer4')
pool_2 = max_pooling_layer(conv_2, 2)
conv_3 = conv_layer(pool_2, conv_size = 3, output_depth = 256, name = 'layer5')
conv_3 = conv_layer(conv_3, conv_size = 3, output_depth = 256, name = 'layer6')
pool_3 = max_pooling_layer(conv_3, 2)
conv_4 = conv_layer(pool_3, conv_size = 3, output_depth = 512, name = 'layer7')
conv_4 = conv_layer(conv_4, conv_size = 3, output_depth = 512, name = 'layer8')
drop_4 = dropout_layer(conv_4, keep_prob)
pool_4 = max_pooling_layer(drop_4, 2)
conv_5 = conv_layer(pool_4, conv_size = 3, output_depth = 1024, name = 'layer9')
conv_5 = conv_layer(conv_5, conv_size = 3, output_depth = 1024, name = 'layer10')
drop_5 = dropout_layer(conv_5, keep_prob)
uppool_6 = unpooling_layer(drop_5, 2)
concat_6 = concat_layer(drop_4, uppool_6)
deconv_6 = deconv_layer(concat_6, conv_size = 3, output_depth = 512, name = 'layer11')
deconv_6 = deconv_layer(deconv_6, conv_size = 3, output_depth = 512, name = 'layer12')
uppool_7 = unpooling_layer(deconv_6, 2)
concat_7 = concat_layer(conv_3, uppool_7)
deconv_7 = deconv_layer(concat_7, conv_size = 3, output_depth = 256, name = 'layer13')
deconv_7 = deconv_layer(deconv_7, conv_size = 3, output_depth = 256, name = 'layer14')
uppool_8 = unpooling_layer(deconv_7, 2)
concat_8 = concat_layer(conv_2, uppool_8)
deconv_8 = deconv_layer(concat_8, conv_size = 3, output_depth = 128, name = 'layer15')
deconv_8 = deconv_layer(deconv_8, conv_size = 3, output_depth = 128, name = 'layer16')
uppool_9 = unpooling_layer(deconv_8, 2)
concat_9 = concat_layer(conv_1, uppool_9)
deconv_9 = deconv_layer(concat_9, conv_size = 3, output_depth = 64, name = 'layer17')
deconv_9 = deconv_layer(deconv_9, conv_size = 3, output_depth = 64, name = 'layer18')
deconv_10 = deconv_layer(deconv_9, conv_size = 3, output_depth = 2, name = 'layer19')
conv_11 = conv_layer(deconv_10, conv_size = 1, output_depth = 1, name = 'layer20',
activation_function = tf.nn.sigmoid, normalize = False)
return conv_11
def Mini_Unet(inputs, keep_prob = 1):
conv_1 = conv_layer(inputs, conv_size = 3, output_depth = 64, name = 'layer1')
conv_1 = conv_layer(conv_1, conv_size = 3, output_depth = 64, name = 'layer2')
pool_1 = max_pooling_layer(conv_1, 2)
conv_2 = conv_layer(pool_1, conv_size = 3, output_depth = 128, name = 'layer3')
conv_2 = conv_layer(conv_2, conv_size = 3, output_depth = 128, name = 'layer4')
drop_2 = dropout_layer(conv_2, keep_prob)
pool_2 = max_pooling_layer(drop_2, 2)
conv_3 = conv_layer(pool_2, conv_size = 3, output_depth = 256, name = 'layer5')
conv_3 = conv_layer(conv_3, conv_size = 3, output_depth = 256, name = 'layer6')
drop_3 = dropout_layer(conv_3, keep_prob)
uppool_4 = deconv_layer(drop_3, conv_size = 2, output_depth = 128, stride = 2, name = 'layer7')
concat_4 = concat_layer(drop_2, uppool_4)
conv_4 = conv_layer(concat_4, conv_size = 3, output_depth = 128, name = 'layer8')
conv_4 = conv_layer(conv_4, conv_size = 3, output_depth = 128, name = 'layer9')
uppool_5 = deconv_layer(conv_4, conv_size = 2, output_depth = 64, stride = 2, name = 'layer10')
concat_5 = concat_layer(conv_1, uppool_5)
conv_5 = conv_layer(concat_5, conv_size = 3, output_depth = 64, name = 'layer11')
conv_5 = conv_layer(conv_5, conv_size = 3, output_depth = 64, name = 'layer12')
conv_6 = conv_layer(conv_5, conv_size = 1, output_depth = 1, name = 'layer13',
activation_function = tf.nn.sigmoid, normalize = False)
return conv_6
class Network(object):
def __init__(self, net_name, y_size, x_size, channels, classes, pretrain_path = None):
"""
Uses the model to create a prediction for the given data
:param model_path: path to the model checkpoint to restore
:param inputs: Data to predict on. Shape [batch_size, x_size, y_size, channels]
:returns prediction: The unet prediction Shape [labels] (px=nx-self.offset/2)
"""
self.net_name = net_name
self.inputs = tf.placeholder(tf.float32, shape = [None, y_size, x_size, channels], name = 'input')
self.ground_truth = tf.placeholder(tf.int32, shape = [None, y_size, x_size, classes],
name = 'ground_truth')
self.keep_prob = tf.placeholder(tf.float32, name = 'dropout_probability')
self.parameter = []
self.pretrain_path = pretrain_path
self.sess = tf.Session()
with tf.name_scope('result'):
if net_name == 'Unet':
self.predicter = Unet(self.inputs, self.keep_prob)
elif net_name == 'Mini_Unet':
self.predicter = Mini_Unet(self.inputs, self.keep_prob)
elif net_name == 'VGGUnet':
self.predicter = VGGUnet(self.inputs, self.keep_prob, self.parameter)
with tf.name_scope('binary_entropy'):
self.binary_entropy = image_binary_entropy(self.predicter, self.ground_truth)
with tf.name_scope('dice_loss'):
self.dice_loss = image_dice_loss(self.predicter, self.ground_truth)
with tf.name_scope('focal_loss'):
self.focal_loss = image_focal_loss(self.predicter, self.ground_truth, 2)
with tf.name_scope('mixed_loss'):
self.mixed_loss = image_mixed_loss(self.predicter, self.ground_truth)
self.saver = tf.train.Saver()
def _initialize(self, optimizer = 'Adam', learning_rate = 1e-4, momentum = 0.2):
# tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS))
if optimizer == 'Adam':
optimizer = tf.train.AdamOptimizer(learning_rate)
elif optimizer == 'SGD':
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
elif optimizer == 'Momentum':
optimizer = tf.train.MomentumOptimizer(learning_rate, momentum)
self.train_step = optimizer.minimize(self.mixed_loss)
init = tf.global_variables_initializer()
self.sess.run(init)
if self.net_name == 'VGGUnet' and self.pretrain_path != None:
Network.load_pretrain_parameter(self)
def predict(self, inputs):
"""
Uses the model to create a prediction for the given data
:param sess: current session
:param inputs: Data to predict on. Shape [batch_size, x_size, y_size, channels]
:returns prediction: The unet prediction. Shape [batch_size, x_size, y_size, channels]
"""
prediction = self.sess.run(self.predicter, feed_dict = {self.inputs: inputs, self.keep_prob: 1.})
return prediction
def train(self, inputs, ground_truth):
"""
Uses the input & ground truth to train the model
:param sess: current session
:param inputs: Data to train. Shape [batch_size, x_size, y_size, channels]
:param ground truth: Data to calculate loss and model cability.
Shape [batch_size, x_sizedeconv_layer, y_size, channels]
:return loss: Batch binary cross entropy
"""
self.sess.run(self.train_step, feed_dict = {self.inputs: inputs, self.ground_truth: ground_truth,
self.keep_prob: 0.5})
loss = self.sess.run(self.mixed_loss, feed_dict = {self.inputs: inputs, self.ground_truth: ground_truth,
self.keep_prob: 1})
return loss
def save(self, model_path = 'ckpt/'):
"""
Saves the current session to a checkpoint
:param sess: current session
:param model_path: path to file system location
"""
save_path = self.saver.save(self.sess, model_path)
return save_path
def restore(self, model_path = 'ckpt/', epochs = None):
"""
Restores a session from a checkpoint
:param sess: current session instance
:param model_path: path to file system checkpoint location
"""
if epochs == None:
file_check_point = open(model_path + 'checkpoint')
check_point = file_check_point.readlines()
final_model = (check_point[0].strip('\n').split(' '))[1].strip('"')
self.saver.restore(self.sess, model_path + final_model)
print("Model restored from file: %s" % (model_path + final_model))
else:
model_name = model_path + self.net_name + '_model_' + str(epochs) + '.ckpt'
print("Model restored from file: %s" % model_name)
self.saver.restore(self.sess, model_name)
def load_pretrain_parameter(self):
weights = np.load(self.pretrain_path)
keys = sorted(weights.keys())
# print(self.sess.run(self.parameter[0]))
print('\nLoad Pretrain Parameter: VGG16----------')
for i, k in enumerate(keys):
if k.strip("_0123456789bW") != "conv":
# print(k)
continue
print( i, k, np.shape(weights[k]))
# self.sess.run(tf.assign(self.parameter[i], weights[k]))
self.sess.run(self.parameter[i].assign(weights[k]))
# print(self.sess.run(self.parameter[0]))<file_sep>import tensorflow as tf
import numpy as np
def weight_variable(shape, name, stddev = 0.1):
initial = tf.truncated_normal(shape, stddev = stddev)
weights = tf.Variable(initial, dtype = tf.float32, name = name)
return weights
def bias_variable(shape, name, stddev = 0.1):
initial = tf.constant(stddev, shape = shape)
bias = tf.Variable(initial, dtype = tf.float32, name = name)
return bias
def normalize_variable(shape, name):
initial = tf.ones(shape = shape)
variable = tf.Variable(initial, dtype = tf.float32, name = name)
return variable
def nomalize_layer(input_data, name, training):
y_size = input_data.get_shape()[1]
x_size = input_data.get_shape()[2]
output_depth = input_data.get_shape()[3]
output_shape = [y_size, x_size, output_depth]
mean_variable = normalize_variable(output_shape, name = name + '_mean')
var_variable = normalize_variable(output_shape, name = name + '_var')
if training:
mean, var = tf.nn.moments(input_data, axes = [0])
ema = tf.train.ExponentialMovingAverage(decay=0.5)
ema_apply_op = ema.apply([mean, var])
tf.control_dependencies([ema_apply_op])
mean_variable.assign(tf.identity(mean))
var_variable.assign(tf.identity(var))
scale = tf.Variable(tf.ones(output_shape), name = name + '_scale')
shift = tf.Variable(tf.zeros(output_shape), name = name + '_shift')
epsilon = 0.001
conv_normalize = tf.nn.batch_normalization(input_data, mean_variable, var_variable, shift, scale, epsilon)
return conv_normalize
def conv_layer(input_data, conv_size, output_depth, name,
activation_function = tf.nn.relu, normalize = True, parameter = None):
with tf.name_scope(name):
input_depth = input_data.get_shape()[3]
mask_shape = tf.stack([conv_size, conv_size, input_depth, output_depth])
conv_weights = weight_variable(mask_shape, name = name + '_w')
conv_biases = bias_variable([output_depth], name = name + '_b')
if parameter != None:
parameter += [conv_weights, conv_biases]
convolution = tf.nn.conv2d(input_data, conv_weights, strides = [1, 1, 1, 1],
padding = 'SAME') + conv_biases
if normalize:
conv_normalize =tf.nn.l2_normalize(convolution, axis = [0])
# conv_normalize = tf.layers.batch_normalization(convolution, training = training, name = name + '_norm')
# update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
else:
conv_normalize = convolution
conv_activation = activation_function(conv_normalize)
return conv_activation
def deconv_layer(input_data, conv_size, output_depth, name,
activation_function = tf.nn.relu, normalize = True, stride = 1):
with tf.name_scope(name):
batch_shape = tf.shape(input_data)[0]
y_size = input_data.get_shape()[1] * stride
x_size = input_data.get_shape()[2] * stride
input_depth = input_data.get_shape()[3]
mask_shape = tf.stack([conv_size, conv_size, output_depth, input_depth])
output_shape = tf.stack([batch_shape, y_size, x_size, output_depth])
deconv_weights = weight_variable(mask_shape, name = name + '_w')
deconv_biases = bias_variable([output_depth], name + '_b')
deconvolution = tf.nn.conv2d_transpose(input_data, deconv_weights, output_shape,
strides=[1, stride, stride, 1], padding='SAME') + deconv_biases
if normalize:
deconv_normalize =tf.nn.l2_normalize(deconvolution, axis = [0])
# deconv_normalize = nomalize_layer(deconvolution, name = name, training = training)
else:
deconv_normalize = deconvolution
deconv_activation = activation_function(deconv_normalize)
return deconv_activation
def fully_connect_layer(input_data, input_depth, output_depth, name,
activation_function = tf.nn.relu, normalize = True):
with tf.name_scope(name):
fcn_w = weight_variable([input_depth, output_depth], name + '_w')
fcn_b = bias_variable([output_depth], name + '_b')
fcn_fcn = tf.matmul(input_data, fcn_w) + fcn_b
if normalize:
fcn_normal = tf.nn.l2_normalize(fcn_fcn, axis = [0])
else:
fcn_normal = fcn_fcn
fcn_activation = activation_function(fcn_normal)
return fcn_activation
def max_pooling_layer(input_data, pool_size):
output = tf.nn.max_pool(input_data, ksize = [1, pool_size, pool_size, 1],
strides = [1, pool_size, pool_size, 1], padding = 'SAME')
return output
def unpooling_layer(input_data, unpool_size):
layer_shape = input_data.get_shape()
output_size = [layer_shape[1] * unpool_size, layer_shape[2] * unpool_size]
output = tf.image.resize_nearest_neighbor(input_data, output_size)
return output
def concat_layer(input_data_1, input_data_2):
output = tf.concat([input_data_1, input_data_2], axis = 3)
return output
def dropout_layer(input_data, keep_prob):
output = tf.nn.dropout(input_data, keep_prob)
return output
def image_binary_entropy(input_data, ground_truth):
GT_float = tf.to_float(ground_truth)
positive_entropy = -1 * tf.multiply(GT_float, tf.log(input_data))
negative_entropy = -1 * tf.multiply((1 - GT_float), tf.log(1 - input_data))
batch_entropy = tf.reduce_mean(positive_entropy + negative_entropy)
return batch_entropy
def mean_square_error(input_data, ground_truth):
GT_float = tf.to_float(ground_truth)
square_error = tf.square(input_data - GT_float)
image_total_error = tf.reduce_sum(square_error, reduction_indices = [1, 2, 3])
mean_error = tf.reduce_mean(image_total_error)
return mean_error
def image_dice_loss(input_data, ground_truth):
GT_float = tf.to_float(ground_truth)
product = tf.multiply(input_data, GT_float)
intersection = tf.reduce_sum(product, reduction_indices = [1, 2, 3])
GT_sum = tf.reduce_sum(GT_float, reduction_indices = [1, 2, 3])
prediction_sum = tf.reduce_sum(input_data, reduction_indices = [1, 2, 3])
coefficient = (2. * intersection + 1.) / (GT_sum + prediction_sum + 1.)
loss = tf.reduce_mean(-1 * tf.log(coefficient))
return loss
def image_focal_loss(input_data, ground_truth, gamma):
GT_float = tf.to_float(ground_truth)
positive_parameter = -1 * tf.pow(1 - input_data, gamma)
positive_loss = tf.multiply(GT_float, tf.multiply(positive_parameter, tf.log(input_data)))
negative_parameter = -1 * tf.pow(input_data, gamma)
negative_loss = tf.multiply(1 - GT_float, tf.multiply(negative_parameter, tf.log(1 - input_data)))
focal_loss = tf.reduce_mean(positive_loss + negative_loss)
return focal_loss
def image_mixed_loss(input_data, ground_truth):
loss = 10. * image_focal_loss(input_data, ground_truth, 2) + \
image_dice_loss(input_data, ground_truth)
return loss
|
ea87a892bde46fba5cc3e32e65c0dee5d593a9c8
|
[
"Markdown",
"Python"
] | 8 |
Python
|
jianjiesun/VGGUnet
|
8a2adb9e067ad8991f488ee8b12db86afc0aeef4
|
9ea7b8fea6180946690aff405d45ce1a82530753
|
refs/heads/master
|
<repo_name>jerji/website-jekyll<file_sep>/Resume.md
---
layout: page
title: Resume
---
My resume is availible here for download.
* [English](RESUME.pdf)
* French is pending
<file_sep>/_posts/2020-05-18-nsec2020-dreamcast-challenge.md
---
title: 'Nsec2020: Dreamcast Challenge'
layout: post
---
This year was my third year at northsec and it was also my best year. My team was "skiddies as a service" and we placed 4th this year at 125 points. I personally participated in many challenges and scored 23 points.
## Dreamcast Challenge
The first challenge I picked up was called "Dreamcast Japanese Imports". It started with four files:
* dc_rom_r0.elf
* dc_rom_r0.cdi
* dc_rom_r1.elf
* dc_rom_r1.cdi
The cdi images were roms that could be run on an emulator. Running them led to the following:

If an invalid code was entered, the following would display:

The elf files were compiled version of the roms that were not scrambled. I loaded them into ghidra, looked at the functions and searched for "flag". I found a function called "\_draw_flag" that was called by a function called "\_process_code".

At first I thought the goal was to reverse the code from the function and I tried but I couldn't find it so what I did was looked at what bytes would change if I patched the "mov.l ->\_failure,r1" to "mov.l ->\_draw_flag,r1". I copied the address of "\_draw_flag" and pasted it into the first mov.l instruction. the bytes at offset 0x01068A changed from "10 D1" to "11 D1".


Next came the challenge of applying the patch to the cdi file. I first tried to put the cdi into ghidra but after some research, I found out that dreamcast images are scrambled on the cd images (Probably to help with loading/seeking times). So with that idea out of the window I loaded up my favorite hex editor, [*010editor*](https://www.sweetscape.com/010editor/) (Thanks @Jax), and opened the cdi file. I looked for the pattern "0A 89 10 D1 0B" which are the mov instruction and the bytes around it. I then changed the 10 to 11 and saved the file. I booted up the rom and pressed start to accept the _000000_ code. And I was greeted with this:

I repeated the same process for the second rom. Turns out that in the end, because the code between the two roms is so similar, the patch "0A 89 10 D1 0B" -> "0A 89 11 D1 0B" works for both files. The second flag was found:

That is how I completed the dreamcast challenge. I enjoyed it quite a bit as it was the first time I worked with roms and an emulator. Thank you to @vincelesal for the wonderful challenge.
<file_sep>/README.md
# website-jekyll
Trying to make a website using jekyll...
This is the repo for my personal website [jouellet.net](https://jouellet.net)
It's based on Jekyll, this is my second attempt at a website.
<file_sep>/_upload.sh
#!/bin/bash
ssh debgum "rm -rf /var/www/html/*"
echo "Removed old version"
bundle exec jekyll build
echo "Built"
rsync -rzv _site/* debgum:/var/www/html/
echo "Sent files"
ssh -t debgum "sudo chown -R angel:www-data /var/www/html"
ssh debgum "chmod -R 750 /var/www/html"
echo "Permissions set, Website is live!"
<file_sep>/_projects/animatronic.md
---
title: Animatronic for shooting gallery
layout: page
field: Electronics
---
I built an animatronic for use in an old shooting gallery.
When I was studying in at 24 Juin in Sherbrooke, a classmate asked me to help him build an animatronic like the ones in old timey shooting gallery and naturally I said yes. Over the course of the next few weeks we built what looked like a ducktape monster.

<p style="text-align: center;"><i>Me in an oversized Tshirt with our monster and Jacob to the left</i></p>

<p style="text-align: center;"><i>This was our prototype, it was a fine mess of wires but it kinda worked</i></p>
We blew two arduino megas in the process, turns out they dont like powering stalled servos...
The final prototype all dressed up looked like this:

<p style="text-align: center;"><i>Final Prototype</i></p>
Here is a [video](http://www.youtube.com/watch?&v=fApZLNiPXt8) where you can watch it move.
We were happy that it was working but it was still a sad sight.
TODO: Add second part
<file_sep>/pi.md
---
layout: nono
permalink: / net/
---
<style>
video {
max-width: 90%;
height: auto;
}
</style>
<video controls autoplay>
<source src="/net.mp4" type="video/mp4">
Your browser does not support the video tag.
</video> <file_sep>/_projects/_museum.md
---
title: Museum exposition
layout: page
field: Electronics
---
In June 2016 I was employed by the museum of science and technology in Sherbrooke to help put together an exposition.
I was in charge of figuring out all of the ele
<file_sep>/_posts/2019-04-29-first-post.markdown
---
title: Welcome to my first post
layout: post
date: '2019-04-29 13:31:31 +0000'
---
Hey, welcome to my first blog post... I made the website and put it on my server and the only thing that is left to add is the content. That's the hard part.
So my name is Jeremy and I have multiple interests. I studied electronic repair at 24 Juin in Sherbrooke, I tried college, the first time I got kicked out because I didn't know what I wanted and the second time I had to leave because of health. since I was around 15, I taught myself Electronics and IT and I had always wished to go to a conference like DEFCON and last year I finally made it there. I will probably make another post about that not to saturate this one.
I currently live in Montreal, QC. I moved here in 2017 and since then I have had an absolute blast here. I've made friends in all sectors and what I like about big cities like these is the fact that I can open the door and there is always something to do. Or I can always sit in my basement on my thinkpad making a website for 2 days.
<file_sep>/projects.md
---
layout: projects
title: Projects
permalink: /projects/:path
---
<file_sep>/_posts/2020-05-18-nsec2020-ssh-client-challenge.md
---
title: 'Nsec2020: SSH Client challenge'
layout: post
---
Another challenge I picked up was the SSH-Client challenge. It started with a linux ssh binary. The premise was that this was an ssh client with a secret in it. At first I didn't know what to do with it, as I didn't have a version of this that I could compare it to. My teammate had already uncovered that it was OpenSSH_8.2p1 with OpenSSL 1.0.2. I then set up a docker container running *Ubuntu 18.04* with *libssl1.0* and *gcc5*. I then downloaded [the source for OpenSSH](https://www.openssh.com/portable.html) and compiled it.
The first thing I tried was to diff the binaries, but everything was shifted and moved around, so obviously that didn't work. I then loaded the challenge binary into ghidra to look for obvious things. I searched the function list and the strings to no avail. I then took a break as I was not getting anywhere.
After helping my teammates with the android part of the *Hey Kids* challenge, I got an idea. I loaded both the challenge binary and the binary I built into ghidra, and after going to the main function of both binaries, I opened the function graphs. This was the result:

I began to compare the two graphs side by side, and after a while I noticed that in the first quarter there was a difference in the peak. The binary I built looked like a pretty even triangle, while the challenge one was not a good-looking triangle, so I zoomed in and got this:

Confirmed! Definitely a difference. After zooming a bit more, I found this:

After going to that part of the code, I saw this:

Comparing it with the [Source](https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/ssh.c?annotate=1.527) (line 738) revealed that this was in the argument passing, and that this was the parsing for the -Q argument. Finally the solutin was to run *./ssh -Q secret*.

This was an interesting challenge that I solved in a weird way, but hey, as long as it works!
Thank you to @pmb for the challenge :D
<file_sep>/index.md
---
layout: page
title: Welcome!
menu: Home
---
This is my personal website. I have many different interests including electronics, programming and infosec. I invite you to take a look around.
|
58b08fad1ab909e8d6774f672984d438377839d2
|
[
"Markdown",
"Shell"
] | 11 |
Markdown
|
jerji/website-jekyll
|
2b2d0f9b7a02f3a0327c0dfd1109d4be073bd074
|
c7fca509a09d4bab2fbd4ae03b4482f1465e332c
|
refs/heads/master
|
<repo_name>BEDIRHANSAMSA/.Net-Framwork-Hatasi-Cozumu<file_sep>/WindowsFormsApp2/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Principal;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ButtonCikis_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void HataCözButton_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("DISM /Online /Enable-Feature /FeatureName:NetFx3 /All");
CmdOutputTxtBox.Text = "Yükleniyor.... \n Sabrınız için teşekkürler. Biraz zaman alabilir.";
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
CmdOutputTxtBox.Text = CmdOutputTxtBox.Text + cmd.StandardOutput.ReadToEnd();
if (CmdOutputTxtBox.Text.Contains("[==========================100.0%==========================] ") ==true)
{
CmdOutputTxtBox.Text = "\n\n\n.Net Freamwork başarıyla yüklendi/güncelledi. Lütfen bedirhansamsa.com'adresini ziyaret etmeyi unutmayın!";
System.Diagnostics.Process.Start("http://bedirhansamsa.com/");
}
else if (CmdOutputTxtBox.Text.Contains("Elevated permissions are required to run DISM"))
{
CmdOutputTxtBox.Text = "\n\nLütfen programı kapatıp Yönetici olarak Çalıştırın. \n\nHATA KODU: CMD UNAVAILABLE";
}
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
throw;
}
}
}
}
<file_sep>/README.md
# .Net Framework Hatası Çözümü
|
0207381e236cfd1fc284e369f585b427013b5e90
|
[
"Markdown",
"C#"
] | 2 |
C#
|
BEDIRHANSAMSA/.Net-Framwork-Hatasi-Cozumu
|
9f5f05cf594e3bbca5329fffdb582c933aae4c16
|
f872a819c770bb7dcf680615188f8739f6ea8e98
|
refs/heads/master
|
<repo_name>dzsi1994/WebHemi<file_sep>/tests/WebHemiTest/Data/Entity/ApplicationEntityTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use DateTimeZone;
use InvalidArgumentException;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\DateTime;
/**
* Class ApplicationEntityTest
*/
class ApplicationEntityTest extends AbstractEntityTestCase
{
/** @var array */
protected $testData = [
'id_application' => 1,
'name' => '<NAME>',
'title' => 'test title',
'introduction' => 'test introduction',
'subject' => 'test subject',
'description' => 'test description',
'keywords' => 'test keywords',
'copyright' => 'test copyright',
'path' => 'test path',
'theme' => 'test theme',
'type' => 'test type',
'locale' => 'en_GB',
'timezone' => 'Europe/London',
'is_read_only' => 1,
'is_enabled' => 0,
'date_created' => '2016-04-26 23:21:19',
'date_modified' => null,
];
/** @var array */
protected $expectedGetters = [
'getApplicationId' => 1,
'getName' => '<NAME>',
'getTitle' => 'test title',
'getIntroduction' => 'test introduction',
'getSubject' => 'test subject',
'getDescription' => 'test description',
'getKeywords' => 'test keywords',
'getCopyright' => 'test copyright',
'getPath' => 'test path',
'getTheme' => 'test theme',
'getType' => 'test type',
'getLocale' => 'en_GB',
'getTimeZone' => null,
'getIsReadOnly' => true,
'getIsEnabled' => false,
'getDateCreated' => null,
'getDateModified' => null,
];
/** @var array */
protected $expectedSetters = [
'setApplicationId' => 1,
'setName' => 'test name',
'setTitle' => 'test title',
'setIntroduction' => 'test introduction',
'setSubject' => 'test subject',
'setDescription' => 'test description',
'setKeywords' => 'test keywords',
'setCopyright' => 'test copyright',
'setPath' => 'test path',
'setTheme' => 'test theme',
'setType' => 'test type',
'setLocale' => 'en_GB',
'setTimeZone' => null,
'setIsReadOnly' => true,
'setIsEnabled' => false,
'setDateCreated' => null,
];
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$dateTimeZone = new DateTimeZone('Europe/London');
$dateTime = new DateTime('2016-04-26 23:21:19');
$this->expectedGetters['getTimeZone'] = $dateTimeZone;
$this->expectedGetters['getDateCreated'] = $dateTime;
$this->expectedSetters['setTimeZone'] = $dateTimeZone;
$this->expectedSetters['setDateCreated'] = $dateTime;
$this->entity = new ApplicationEntity();
}
/**
* Test date modified setters and getters
*/
public function testDateModified()
{
$entity = new ApplicationEntity();
$this->assertEmpty($entity->getDateModified());
$dateTime = new DateTime('2016-04-26 23:21:19');
$entity->setDateModified($dateTime);
$actualObject = var_export($entity->getDateModified(), true);
$expectedObject = var_export($dateTime, true);
$this->assertSame($expectedObject, $actualObject);
}
/**
* Test invalid argument
*/
public function testError()
{
$this->expectException(InvalidArgumentException::class);
$data = ['non_existing_index' => 'data'];
$entity = new ApplicationEntity();
$entity->fromArray($data);
}
}
<file_sep>/src/WebHemi/DependencyInjection/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\DependencyInjection;
use WebHemi\Configuration\ServiceInterface as ConfigurationService;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationService $configuration
*/
public function __construct(ConfigurationService $configuration);
/**
* Returns true if the given service is registered.
*
* @param string $identifier
* @return bool
*/
public function has(string $identifier) : bool;
/**
* Gets a service.
*
* @param string $identifier
* @return object
*/
public function get(string $identifier);
/**
* Retrieves configuration for a service.
*
* @param string $identifier
* @param string $moduleName
* @return array
*/
public function getServiceConfiguration(string $identifier, string $moduleName = null) : array;
/**
* Register the service.
*
* @param string $identifier
* @param string $moduleName
* @return ServiceInterface
*/
public function registerService(string $identifier, string $moduleName = 'Global') : ServiceInterface;
/**
* Register the service object instance.
*
* @param string $identifier
* @param object $serviceInstance
* @return ServiceInterface
*/
public function registerServiceInstance(string $identifier, $serviceInstance) : ServiceInterface;
/**
* Register module specific services.
* If a service is already registered in the Global namespace, it will be skipped.
*
* @param string $moduleName
* @return ServiceInterface
*/
public function registerModuleServices(string $moduleName) : ServiceInterface;
}
<file_sep>/tests/WebHemiTest/Data/Entity/FilesystemDirectoryDataEntityTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use WebHemi\Data\Entity\FilesystemDirectoryDataEntity;
/**
* Class FilesystemDirectoryDataEntityTest
*/
class FilesystemDirectoryDataEntityTest extends AbstractEntityTestCase
{
/** @var array */
protected $testData = [
'id_filesystem' => 1,
'id_application' => 1,
'id_filesystem_directory' => 1,
'description' => 'test description',
'directory_type' => 'test dir type',
'proxy' => 'test proxy',
'is_autoindex' => 1,
'path' => 'test path',
'basename' => 'test basenane',
'uri' => 'test uri',
'type' => 'test type',
'title' => 'test title',
];
/** @var array */
protected $expectedGetters = [
'getFilesystemId' => 1,
'getApplicationId' => 1,
'getFilesystemDirectoryId' => 1,
'getDescription' => 'test description',
'getDirectoryType' => 'test dir type',
'getProxy' => 'test proxy',
'getIsAutoIndex' => true,
'getPath' => 'test path',
'getBaseName' => 'test basenane',
'getUri' => 'test uri',
'getType' => 'test type',
'getTitle' => 'test title',
];
/** @var array */
protected $expectedSetters = [
'setFilesystemId' => 1,
'setApplicationId' => 1,
'setFilesystemDirectoryId' => 1,
'setDescription' => 'test description',
'setDirectoryType' => 'test dir type',
'setProxy' => 'test proxy',
'setIsAutoIndex' => true,
'setPath' => 'test path',
'setBaseName' => 'test basenane',
'setUri' => 'test uri',
'setType' => 'test type',
'setTitle' => 'test title',
];
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$this->entity = new FilesystemDirectoryDataEntity();
}
}
<file_sep>/tests/WebHemiTest/StringLibTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest;
use PHPUnit\Framework\TestCase;
use WebHemi\StringLib;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
/**
* Class StringLibTest
*/
class StringLibTest extends TestCase
{
use AssertTrait;
/**
* Data provider for the CamelCase test.
*
* @return array
*/
public function camelCaseDataProvider()
{
return [
['CamelCase', 'camel_case'],
['Camel_Case', 'camel__case'],
['__CamelCase__', '___camel_case__'],
['CAMELCASE', 'c_a_m_e_l_c_a_s_e'],
];
}
/**
* Tests the convertCamelCaseToUnderscore method.
*
* @param string $input
* @param string $expectedOutput
*
* @dataProvider camelCaseDataProvider
*/
public function testCamelCaseToUnderscore($input, $expectedOutput)
{
$actualOutput = StringLib::convertCamelCaseToUnderscore($input);
$this->assertSame($expectedOutput, $actualOutput);
}
/**
* Data provider for the under_score test.
*
* @return array
*/
public function underscoreDataProvider()
{
return [
['camel_case', 'CamelCase'],
['camel__case', 'Camel_Case'],
['___camel_case__', '__CamelCase__'],
['c_a_M_e_l_C_a_s_e','CAMELCASE'],
];
}
/**
* Tests the convertUnderscoreToCamelCase method.
*
* @param string $input
* @param string $expectedOutput
*
* @dataProvider underscoreDataProvider
*/
public function testUnderscoreToCamelCase($input, $expectedOutput)
{
$actualOutput = StringLib::convertUnderscoreToCamelCase($input);
$this->assertSame($expectedOutput, $actualOutput);
}
/**
* Data provider for the under_score test.
*
* @return array
*/
public function nonAlphanumeric()
{
return [
['under_score', '', 'under_score'],
['CamelCase', '', 'CamelCase'],
['array[representation]', '', 'array_representation'],
['array[representation]', '[]', 'array[representation]'],
['array[representation]', ']', 'array_representation]'],
['[({*&%$})]','',''],
];
}
/**
* Tests the convertNonAlphanumericToUnderscore method.
*
* @param string $input
* @param string $extraCharacters
* @param string $expectedOutput
*
* @dataProvider nonAlphanumeric
*/
public function testNonAlphanumeric($input, $extraCharacters, $expectedOutput)
{
$actualOutput = StringLib::convertNonAlphanumericToUnderscore($input, $extraCharacters);
$this->assertSame($expectedOutput, $actualOutput);
}
/**
* Tests the convertTextToLines method.
*/
public function testConvertTextToLines()
{
$input = <<<EOH
something
happens in Denmark.
Don't know
what
but it
stinks
EOH;
$expextedOutput = [
'something',
'happens in Denmark.',
'Don\'t know',
'what',
'but it',
'stinks',
];
$currentOutput = StringLib::convertTextToLines($input);
$this->assertArraysAreSimilar($expextedOutput, $currentOutput);
}
/**
* Tests the convertLinesToText method.
*/
public function testConvertLinesToText()
{
$input = [
'something',
'happens in Denmark.',
'Don\'t know',
'what',
'',
'but it',
'stinks',
];
$expextedOutput = 'something'.PHP_EOL.'happens in Denmark.'.PHP_EOL.'Don\'t know'.PHP_EOL.'what'.PHP_EOL.
PHP_EOL.'but it'.PHP_EOL.'stinks';
$currentOutput = StringLib::convertLinesToText($input);
$this->assertSame($expextedOutput, $currentOutput);
}
}
<file_sep>/src/WebHemi/I18n/TimeZoneInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\I18n;
/**
* Interface TimeZoneInterface.
*/
interface TimeZoneInterface
{
/**
* Loads date format data regarding to the time zone.
*
* @param string $timeZone
*/
public function loadTimeZoneData(string $timeZone) : void;
}
<file_sep>/src/WebHemi/Middleware/Action/Auth/LogoutAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Auth;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class LogoutAction.
*/
class LogoutAction extends AbstractMiddlewareAction
{
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* LogoutAction constructor.
*
* @param AuthInterface $authAdapter
* @param EnvironmentInterface $environmentManager
*/
public function __construct(AuthInterface $authAdapter, EnvironmentInterface $environmentManager)
{
$this->authAdapter = $authAdapter;
$this->environmentManager = $environmentManager;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return '';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$this->authAdapter->clearIdentity();
$this->response = $this->response->withStatus(ResponseInterface::STATUS_REDIRECT, 'Found')
->withHeader('Location', $this->environmentManager->getSelectedApplicationUri());
return [];
}
}
<file_sep>/tests/WebHemiTest/Renderer/Helper/IsAllowedHelperTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTestX\Renderer\Helper;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use WebHemi\Acl\ServiceAdapter\Base\ServiceAdapter as Acl;
use WebHemi\Acl\ServiceInterface as AclAdapterInterface;
use WebHemi\Auth\ServiceAdapter\Base\ServiceAdapter as Auth;
use WebHemi\Auth\ServiceInterface as AuthAdapterInterface;
use WebHemi\Environment\ServiceAdapter\Base\ServiceAdapter as EnvironmentManager;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\ResourceStorage;
use WebHemi\Data\Storage\ApplicationStorage;
use WebHemi\Renderer\Helper\IsAllowedHelper;
/**
* Class IsAllowedHelperTest.
*/
class IsAllowedHelperTest extends TestCase
{
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
/** @var ConfigInterface */
private $config;
/** @var UserEntity */
private $userEntity;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$configData = [
'applications' => [
'website' => [
'module' => 'Website',
'language' => 'en',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
],
'admin' => [
'module' => 'Admin',
'language' => 'en',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
],
],
'router' => [
'Website' => [
'some_page' => [
'path' => '/some/url[/]',
'middleware' => 'SomeMiddleware'
],
'some_other_page' => [
'path' => '/some/url/{id:\d+}',
'middleware' => 'SomeOtherMiddleware'
],
],
'Admin' => [
'some_admin_page' => [
'path' => '/some/admin/page[/]',
'middleware' => 'SomeMiddleware'
],
'some_other_admin_page' => [
'path' => '/some/other/admin/page[/]',
'middleware' => 'SomeOtherMiddleware'
],
],
],
];
$this->config = new Config($configData);
$this->userEntity = new UserEntity();
$this->userEntity->setUserId(1);
}
/**
* Tests the helper invoke
*/
public function testHelperWithResourceName()
{
$environmentProphecy = $this->prophesize(EnvironmentManager::class);
$environmentProphecy->getSelectedApplication()->willReturn('website');
$environmentManager = $environmentProphecy->reveal();
$aclProphecy = $this->prophesize(AclAdapterInterface::class);
$aclProphecy->isAllowed(Argument::any(), Argument::any(), Argument::any(), Argument::any())->will(
function ($arguments) {
/** @var UserEntity $userEntity */
$userEntity = $arguments[0];
/** @var ResourceEntity $resourceEntity */
$resourceEntity = $arguments[1];
/** @var ApplicationEntity $applicationEntity */
$applicationEntity = $arguments[2];
if (is_null($userEntity)
|| is_null($resourceEntity)
|| is_null($applicationEntity)
) {
return false;
}
return ($userEntity->getUserId() === 1
&& $resourceEntity->getResourceId() === $applicationEntity->getApplicationId()
);
}
);
$aclAdapter = $aclProphecy->reveal();
$user = $this->userEntity;
$authProphecy = $this->prophesize(AuthAdapterInterface::class);
$authProphecy->getIdentity()->will(
function () use ($user) {
return $user;
}
);
$authAdapter = $authProphecy->reveal();
$resourceStorage = $this->getMockBuilder(ResourceStorage::class)
->disableOriginalConstructor()
->setMethods(['getResourceByName'])
->getMock();
$resourceStorage->method('getResourceByName')
->will($this->returnCallback([$this, 'resourceStorageGetResourceByName']));
$applicationStorage = $this->getMockBuilder(ApplicationStorage::class)
->disableOriginalConstructor()
->setMethods(['getApplicationByName'])
->getMock();
$applicationStorage->method('getApplicationByName')
->will($this->returnCallback([$this, 'applicationStorageGetApplicationByName']));
/**
* @var EnvironmentManager $environmentManager
* @var Acl $aclAdapter
* @var Auth $authAdapter
* @var ResourceStorage $resourceStorage
* @var ApplicationStorage $applicationStorage
*/
$helper = new IsAllowedHelper(
$this->config,
$environmentManager,
$aclAdapter,
$authAdapter,
$resourceStorage,
$applicationStorage
);
// result = (resourceId == applicationId)
// 1, 1 => true
$this->assertTrue($helper('SomeMiddleware'));
// 2, 1 => false
$this->assertFalse($helper('SomeOtherMiddleware', 'GET'));
// 1, 2 => false
$this->assertFalse($helper('SomeMiddleware', 'GET', 'admin'));
// 2, 2 => true
$this->assertTrue($helper('SomeOtherMiddleware', null, 'admin'));
// null, 1 => false
$this->assertFalse($helper('SomeNotDefinedMiddleware', 'POST'));
// null, null => false
$this->assertFalse($helper('SomeNotDefinedMiddleware', null, 'fake_app'));
}
/**
* Since the PHPUnit Prophecy has issues with nullable return types, we use Mocking instead of prophecy...
*
* @param $applicationName
* @return null|ApplicationEntity
*/
public function applicationStorageGetApplicationByName($applicationName)
{
if ($applicationName == 'website') {
$applicationEntity = new ApplicationEntity();
$applicationEntity->setApplicationId(1)
->setName('website');
return $applicationEntity;
} elseif ($applicationName == 'admin') {
$applicationEntity = new ApplicationEntity();
$applicationEntity->setApplicationId(2)
->setName('admin');
return $applicationEntity;
}
return null;
}
/**
* Since the PHPUnit Prophecy has issues with nullable return types, we use Mocking instead of prophecy...
*
* @param $resourceName
* @return null|ResourceEntity
*/
public function resourceStorageGetResourceByName($resourceName)
{
if ($resourceName == 'SomeMiddleware') {
$resourceEntity = new ResourceEntity();
$resourceEntity->setResourceId(1)
->setName('SomeMiddleware');
return $resourceEntity;
} elseif ($resourceName == 'SomeOtherMiddleware') {
$resourceEntity = new ResourceEntity();
$resourceEntity->setResourceId(2)
->setName('SomeOtherMiddleware');
return $resourceEntity;
}
return null;
}
/**
* Tests helper when no user is defined.
*/
public function testNoUser()
{
$config = new Config([]);
$environmentProphecy = $this->prophesize(EnvironmentManager::class);
$environmentManager = $environmentProphecy->reveal();
$aclProphecy = $this->prophesize(AclAdapterInterface::class);
$aclAdapter = $aclProphecy->reveal();
$authAdapter = $this->getMockBuilder(Auth::class)
->disableOriginalConstructor()
->setMethods(['getIdentity'])
->getMock();
$authAdapter->method('getIdentity')
->willReturn(null);
$resourceProphecy = $this->prophesize(ResourceStorage::class);
$resourceStorage = $resourceProphecy->reveal();
$applicationProphecy = $this->prophesize(ApplicationStorage::class);
$applicationStorage = $applicationProphecy->reveal();
/**
* @var EnvironmentManager $environmentManager
* @var Acl $aclAdapter
* @var Auth $authAdapter
* @var ResourceStorage $resourceStorage
* @var ApplicationStorage $applicationStorage
*/
$helper = new IsAllowedHelper(
$config,
$environmentManager,
$aclAdapter,
$authAdapter,
$resourceStorage,
$applicationStorage
);
$this->assertFalse($helper('Anything, since the user is not logged in, should return FALSE.'));
}
}
<file_sep>/src/WebHemi/Middleware/Common/FinalMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Common;
use RuntimeException;
use Throwable;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Logger\ServiceInterface as LoggerInterface;
use WebHemi\Middleware\MiddlewareInterface;
/**
* Class FinalMiddleware.
*/
class FinalMiddleware implements MiddlewareInterface
{
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var LoggerInterface
*/
private $logAdapter;
/**
* FinalMiddleware constructor.
*
* @param AuthInterface $authAdapter
* @param EnvironmentInterface $environmentManager
* @param LoggerInterface $logAdapter
*/
public function __construct(
AuthInterface $authAdapter,
EnvironmentInterface $environmentManager,
LoggerInterface $logAdapter
) {
$this->authAdapter = $authAdapter;
$this->environmentManager = $environmentManager;
$this->logAdapter = $logAdapter;
}
/**
* Sends out the headers and prints the response body to the output.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return void
*/
public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void
{
// Handle errors here.
if (!in_array($response->getStatusCode(), [ResponseInterface::STATUS_OK, ResponseInterface::STATUS_REDIRECT])) {
$exception = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_MIDDLEWARE_EXCEPTION)
?? new RuntimeException($response->getReasonPhrase(), $response->getStatusCode());
// Make sure that the Request has the exception.
$request = $request->withAttribute(ServerRequestInterface::REQUEST_ATTR_MIDDLEWARE_EXCEPTION, $exception);
$this->logErrorResponse($exception, $request, $response);
}
}
/**
* Logs the error.
*
* @param Throwable $exception
* @param ServerRequestInterface $request
* @param ResponseInterface $response
*/
private function logErrorResponse(
Throwable $exception,
ServerRequestInterface&$request,
ResponseInterface&$response
) : void {
$identity = '<PASSWORD>';
if ($this->authAdapter->hasIdentity()) {
/**
* @var UserEntity $userEntity
*/
$userEntity = $this->authAdapter->getIdentity();
$identity = $userEntity->getEmail();
}
$logData = [
'User' => $identity,
'IP' => $this->environmentManager->getClientIp(),
'RequestUri' => $request->getUri()->getPath().'?'.$request->getUri()->getQuery(),
'RequestMethod' => $request->getMethod(),
'Error' => $response->getStatusCode().' '.$response->getReasonPhrase(),
'Exception' => $this->getExceptionAsString($exception),
'Parameters' => $request->getParsedBody()
];
$this->logAdapter->log('error', json_encode($logData));
}
/**
* Convert the exception into plain text instead of the fancy HTML output of the xdebug...
*
* @param Throwable $exception
* @return string
*/
private function getExceptionAsString(Throwable $exception)
{
return 'Exception ('.$exception->getCode().'): "'.$exception->getMessage().'" '
.'in '.$exception->getFile().' on line '.$exception->getLine().PHP_EOL
.'Call stack'.PHP_EOL
.$exception->getTraceAsString();
}
}
<file_sep>/src/WebHemi/Form/Element/Html/AbstractElement.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form\Element\Html;
use InvalidArgumentException;
use WebHemi\Form\ElementInterface;
use WebHemi\StringLib;
use WebHemi\Validator\ValidatorInterface;
/**
* Class AbstractElement.
*/
abstract class AbstractElement implements ElementInterface
{
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $identifier;
/**
* @var null|string
*/
private $label;
/**
* @var string
*/
private $type;
/**
* @var array
*/
private $values = [];
/**
* @var array
*/
private $valueRange = [];
/**
* @var ValidatorInterface[]
*/
private $validators = [];
/**
* @var array
*/
private $errors = [];
/**
* @var array
*/
protected $validTypes = [];
/**
* AbstractElement constructor.
*
* @param string $type The type of the form element.
* @param string $name For HTML forms it is the name attribute.
* @param string $label Optional. The label of the element. If not set the $name should be used.
* @param array $values Optional. The values of the element.
* @param array $valueRange Optional. The range of interpretation.
*/
public function __construct(
string $type = null,
string $name = null,
string $label = null,
array $values = [],
array $valueRange = []
) {
if (!empty($type)) {
$this->setType($type);
}
if (!empty($name)) {
$this->setName($name);
}
$this->label = $label;
$this->values = $values;
$this->valueRange = $valueRange;
}
/**
* Sets element's name.
*
* @param string $name
* @throws InvalidArgumentException
* @return ElementInterface
*/
public function setName(string $name) : ElementInterface
{
$name = StringLib::convertCamelCaseToUnderscore($name);
$name = StringLib::convertNonAlphanumericToUnderscore($name, '[]');
if (empty($name)) {
throw new InvalidArgumentException('During conversion the argument value become an empty string!', 1000);
}
$this->name = $name;
$this->identifier = 'id_'.StringLib::convertNonAlphanumericToUnderscore($name);
return $this;
}
/**
* Gets the element's name.
*
* @return string
*/
public function getName() : string
{
return $this->name;
}
/**
* Gets the element's name.
*
* @return string
*/
public function getId() : string
{
return $this->identifier;
}
/**
* Sets the element's type.
*
* @param string $type
* @return ElementInterface
*/
public function setType(string $type) : ElementInterface
{
if (!in_array($type, $this->validTypes)) {
throw new InvalidArgumentException(
sprintf('%s is not a valid %s type', $type, get_called_class()),
1001
);
}
$this->type = $type;
return $this;
}
/**
* Gets the element's type.
*
* @return string
*/
public function getType() : string
{
return $this->type;
}
/**
* Sets the element's label.
*
* @param string $label
* @return ElementInterface
*/
public function setLabel(string $label) : ElementInterface
{
$this->label = $label;
return $this;
}
/**
* Gets the element's label.
*
* @return string
*/
public function getLabel() : string
{
return $this->label ?? $this->name;
}
/**
* Sets the values.
*
* @param array $values
* @return ElementInterface
*/
public function setValues(array $values) : ElementInterface
{
$this->values = $values;
return $this;
}
/**
* Gets the values.
*
* @return array
*/
public function getValues() : array
{
return $this->values;
}
/**
* Sets the range of interpretation. Depends on the element type how it is used: exact element list or a min/max.
*
* @param array $valueRange
* @return ElementInterface
*/
public function setValueRange(array $valueRange) : ElementInterface
{
$this->valueRange = $valueRange;
return $this;
}
/**
* Get the range of interpretation.
*
* @return array
*/
public function getValueRange() : array
{
return $this->valueRange;
}
/**
* Adds a validator to the element.
*
* @param ValidatorInterface $validator
* @return ElementInterface
*/
public function addValidator(ValidatorInterface $validator) : ElementInterface
{
$validatorClass = get_class($validator);
$this->validators[$validatorClass] = $validator;
return $this;
}
/**
* Validates the element.
*
* @return ElementInterface
*/
public function validate() : ElementInterface
{
/**
* @var ValidatorInterface $validator
*/
foreach ($this->validators as $validatorClass => $validator) {
$isValid = $validator->validate($this->values);
if (!$isValid) {
$this->errors[$validatorClass] = $validator->getErrors();
} else {
$this->setValues($validator->getValidData());
}
}
return $this;
}
/**
* Set custom error.
*
* @param string $validator
* @param string $error
* @return ElementInterface
*/
public function setError(string $validator, string $error) : ElementInterface
{
$this->errors[$validator] = [$error];
return $this;
}
/**
* Returns the errors collected during the validation.
*
* @return array
*/
public function getErrors() : array
{
return $this->errors;
}
}
<file_sep>/src/WebHemi/Http/ServerRequestInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http;
use Psr\Http\Message\ServerRequestInterface as PsrServerRequestInterface;
/**
* Interface ServerRequestInterface.
*/
interface ServerRequestInterface extends PsrServerRequestInterface
{
public const REQUEST_ATTR_RESOLVED_ACTION_CLASS = 'resolved_action_middleware';
public const REQUEST_ATTR_ACTION_MIDDLEWARE = 'action_middleware_instance';
public const REQUEST_ATTR_MIDDLEWARE_EXCEPTION = 'middleware_exception';
public const REQUEST_ATTR_ROUTING_PARAMETERS = 'routing_parameters';
public const REQUEST_ATTR_ROUTING_RESOURCE = 'routing_resource';
public const REQUEST_ATTR_DISPATCH_TEMPLATE = 'dispatch_template';
public const REQUEST_ATTR_DISPATCH_DATA = 'dispatch_data';
public const REQUEST_ATTR_AUTHENTICATED_USER = 'authenticated_user';
public const REQUEST_ATTR_AUTHENTICATED_USER_META = 'authenticated_user_meta';
/**
* Checks if it is an XML HTTP Request (Ajax) or not.
*
* @return bool
*/
public function isXmlHttpRequest() : bool;
}
<file_sep>/config/modules/admin/router.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Middleware\Action;
return [
'router' => [
'Admin' => [
// Auth
'admin-login' => [
'path' => '^/auth/login/?$',
'middleware' => Action\Auth\LoginAction::class,
'allowed_methods' => ['GET', 'POST'],
],
'admin-logout' => [
'path' => '^/auth/logout/?$',
'middleware' => Action\Auth\LogoutAction::class,
'allowed_methods' => ['GET'],
],
// Dashboard
'dashboard' => [
'path' => '^/$',
'middleware' => Action\Admin\DashboardAction::class,
'allowed_methods' => ['GET'],
'resource_name' => 'admin-dashboard', // Define resorce name in the options
],
// Applications
'admin-applications-list' => [ // Define resource name in the index (fallback if no option presents)
'path' => '^/applications/?$',
'middleware' => Action\Admin\Applications\IndexAction::class,
'allowed_methods' => ['GET'],
],
'admin-applications-add' => [
'path' => '^/applications/add/?$',
'middleware' => Action\Admin\Applications\AddAction::class,
'allowed_methods' => ['GET'],
],
'admin-applications-view' => [
'path' => '^/applications/(?P<name>[a-z0-9\-\_]+)/?$',
'middleware' => Action\Admin\Applications\ViewAction::class,
'allowed_methods' => ['GET'],
],
'admin-applications-preferences' => [
'path' => '^/applications/(?P<name>[a-z0-9\-\_]+)/preferences/?$',
'middleware' => Action\Admin\Applications\PreferencesAction::class,
'allowed_methods' => ['GET'],
],
'admin-applications-save' => [
'path' => '^/applications/(?P<name>[a-z0-9\-\_]+)/(?P<action>save)/?$',
'middleware' => Action\Admin\Applications\SaveAction::class,
'allowed_methods' => ['POST'],
],
'admin-applications-delete' => [
'path' => '^/applications/(?P<name>[a-z0-9\-\_]+)/delete/?$',
'middleware' => Action\Admin\Applications\DeleteAction::class,
'allowed_methods' => ['GET', 'POST'],
],
// Control Panel
'admin-control-panel-index' => [
'path' => '^/control-panel/?$',
'middleware' => Action\Admin\ControlPanel\IndexAction::class,
'allowed_methods' => ['GET'],
],
// Settings
'admin-control-panel-settings-index' => [
'path' => '^/control-panel/settings/?$',
'middleware' => Action\Admin\ControlPanel\Settings\IndexAction::class,
'allowed_methods' => ['GET'],
],
// Themes
'admin-control-panel-themes-list' => [
'path' => '^/control-panel/themes/?$',
'middleware' => Action\Admin\ControlPanel\Themes\IndexAction::class,
'allowed_methods' => ['GET'],
],
'admin-control-panel-themes-add' => [
'path' => '^/control-panel/themes/add/?$',
'middleware' => Action\Admin\ControlPanel\Themes\AddAction::class,
'allowed_methods' => ['GET', 'POST'],
],
'admin-control-panel-themes-view' => [
'path' => '^/control-panel/themes/(?P<name>[a-z0-9\-\_]+)/?$',
'middleware' => Action\Admin\ControlPanel\Themes\ViewAction::class,
'allowed_methods' => ['GET'],
],
'admin-control-panel-themes-delete' => [
'path' => '^/control-panel/themes/(?P<name>[a-z0-9\-\_]+)/delete/?$',
'middleware' => Action\Admin\ControlPanel\Themes\DeleteAction::class,
'allowed_methods' => ['GET', 'POST'],
],
// Add-Ons
'admin-control-panel-add-ons-index' => [
'path' => '^/control-panel/add-ons/?$',
'middleware' => Action\Admin\ControlPanel\AddOns\IndexAction::class,
'allowed_methods' => ['GET'],
],
// Users
'admin-control-panel-users-list' => [
'path' => '^/control-panel/users/?$',
'middleware' => Action\Admin\ControlPanel\Users\IndexAction::class,
'allowed_methods' => ['GET'],
],
// Groups
'admin-control-panel-groups-list' => [
'path' => '^/control-panel/groups/?$',
'middleware' => Action\Admin\ControlPanel\Groups\ListAction::class,
'allowed_methods' => ['GET'],
],
// 'admin-control-panel-groups-add' => [
// 'path' => '^/control-panel/groups/add/?$',
// 'middleware' => Action\Admin\ControlPanel\Groups\AddAction::class,
// 'allowed_methods' => ['GET', 'POST'],
// ],
'admin-control-panel-groups-view' => [
'path' => '^/control-panel/groups/view/(?P<userGroupId>\d+)/?$',
'middleware' => Action\Admin\ControlPanel\Groups\ViewAction::class,
'allowed_methods' => ['GET'],
],
// 'admin-control-panel-groups-edit' => [
// 'path' => '^/control-panel/groups/edit/(?P<userGroupId>\d+)/?$',
// 'middleware' => Action\Admin\ControlPanel\Groups\EditAction::class,
// 'allowed_methods' => ['GET', 'POST'],
// ],
// Resources
'admin-control-panel-resources-list' => [
'path' => '^/control-panel/resources/?$',
'middleware' => Action\Admin\ControlPanel\Resources\IndexAction::class,
'allowed_methods' => ['GET'],
],
// Policies
'admin-control-panel-policies-list' => [
'path' => '^/control-panel/policies/?$',
'middleware' => Action\Admin\ControlPanel\Policies\IndexAction::class,
'allowed_methods' => ['GET'],
],
// Logs
'admin-control-panel-logs-list' => [
'path' => '^/control-panel/logs/?$',
'middleware' => Action\Admin\ControlPanel\Logs\IndexAction::class,
'allowed_methods' => ['GET'],
],
// About
'admin-about-index' => [
'path' => '^/about/?$',
'middleware' => Action\Admin\About\IndexAction::class,
'allowed_methods' => ['GET'],
],
],
],
];
<file_sep>/src/WebHemi/Data/Storage/StorageInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use InvalidArgumentException;
use WebHemi\Data\Query\QueryInterface;
use WebHemi\Data\Entity\EntityInterface;
use WebHemi\Data\Entity\EntitySet;
/**
* Interface StorageInterface.
*/
interface StorageInterface
{
/**
* StorageInterface constructor.
*
* @param QueryInterface $queryAdapter
* @param EntitySet $entitySetPrototype
* @param EntityInterface[] ...$entityPrototypes
*/
public function __construct(
QueryInterface $queryAdapter,
EntitySet $entitySetPrototype,
EntityInterface ...$entityPrototypes
);
/**
* @return QueryInterface
*/
public function getQueryAdapter() : QueryInterface;
/**
* Creates a clean instance of the Entity.
*
* @param string $entityClass
* @throws InvalidArgumentException
* @return EntityInterface
*/
public function createEntity(string $entityClass) : EntityInterface;
/**
* Creates an empty entity set.
*
* @return EntitySet
*/
public function createEntitySet() : EntitySet;
}
<file_sep>/progress.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
$progressId = $_GET['progress_id'] ?? '_';
$progressPath = __DIR__.'/data/progress/';
if ($progressId && file_exists($progressPath.$progressId.'.json')) {
$data = file_get_contents($progressPath.$progressId.'.json');
} else {
$data = ['error' => 'no progress found'];
$data = json_encode($data);
}
header('Content-Type: application/json');
echo $data;
<file_sep>/src/WebHemi/Renderer/Filter/MarkDownFilter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Filter;
use WebHemi\Parser\ServiceInterface as ParserInterface;
use WebHemi\Renderer\FilterInterface;
/**
* Class MarkDownFilter
*
* @codeCoverageIgnore - See tests for the WebHemi\Parser\ServiceAdapter\Parsedown\ServiceAdapter::class
*/
class MarkDownFilter implements FilterInterface
{
/**
* @var ParserInterface
*/
private $parser;
/**
* MarkDownFilter constructor.
*
* @param ParserInterface $parser
*/
public function __construct(ParserInterface $parser)
{
$this->parser = $parser;
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'markdown';
}
/**
* Should return the definition of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{{ "some **markdown** text"|markdown }}';
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Parses the input text as a markdown script and outputs the HTML.';
}
/**
* Gets filter options for the render.
*
* @return array
* @codeCoverageIgnore - fix array
*/
public static function getOptions() : array
{
return ['is_safe' => ['html']];
}
/**
* Parses the input text as a markdown script and outputs the HTML.
*
* @return string
*/
public function __invoke() : string
{
$text = func_get_args()[0] ?? '';
$content = $this->parser->parse($text);
$content = str_replace(
['<table>', '</table>'],
['<div class="table"><table>', '</table></div>'],
$content
);
return $content;
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyFormPreset.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Form\ElementInterface;
use WebHemi\Form\Preset\AbstractPreset;
/**
* Class EmptyFormPreset
*/
class EmptyFormPreset extends AbstractPreset
{
/**
* Initialize.
*/
protected function init() : void
{
return;
}
/**
* Passes parameters to protected method to be able to test.
*
* @param string $class
* @param string $type
* @param string $name
* @param string $label
* @return ElementInterface
*/
public function creatingTestElement(string $class, string $type, string $name, string $label) : ElementInterface
{
return $this->createElement($class, $type, $name, $label);
}
}
<file_sep>/tests/WebHemiTest/test_config.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
use WebHemi\DateTime;
use WebHemi\Data;
use WebHemi\Environment\ServiceInterface as EnvironmentManager;
use WebHemi\Http\ServiceInterface as HttpAdapterInterface;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\ServiceAdapter as GuzzleHttpAdapter;
use WebHemi\I18n\ServiceInterface as I18nServiceAdapterInterface;
use WebHemi\I18n\ServiceAdapter\Base\ServiceAdapter as I18nServiceAdapter;
use WebHemi\I18n\DriverInterface as I18nDriverAdapterInterface;
use WebHemi\I18n\DriverAdapter\Gettext\DriverAdapter as I18nDriverAdapter;
use WebHemi\Middleware\Common\FinalMiddleware;
use WebHemi\Middleware\Common\DispatcherMiddleware;
use WebHemi\Middleware\Common\RoutingMiddleware;
use WebHemi\Renderer\ServiceInterface as RendererAdapterInterface;
use WebHemi\Renderer\ServiceAdapter\Twig\ServiceAdapter as TwigRendererAdapter;
use WebHemi\Router\ServiceInterface as RouterAdapterInterface;
use WebHemi\Router\ProxyInterface as RouterProxyInterface;
use WebHemi\Router\ServiceAdapter\Base\ServiceAdapter as RouteAdapter;
use WebHemi\Router\Result\Result;
use WebHemiTest\TestService\EmptyRendererHelper;
use WebHemiTest\TestService\EmptyService;
use WebHemiTest\TestService\TestMiddleware;
use WebHemiTest\TestService\TestActionMiddleware;
use WebHemiTest\TestService\EmptyRouteProxy as RouteProxy;
return [
'applications' => [
'website' => [
'module' => 'Website',
'type' => 'domain',
'path' => 'www',
'theme' => 'default',
'language' => 'en',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
],
'admin' => [
'module' => 'Admin',
'type' => 'domain',
'path' => 'admin',
'theme' => 'test_theme',
'language' => 'en',
'locale' => 'en_US.UTF-8',
'timezone' => 'America/Detroit',
],
'some_app' => [
'module' => 'SomeApp',
'type' => 'directory',
'path' => 'some_application',
'theme' => 'test_theme',
'language' => 'pt',
'locale' => 'pt_BR.UTF-8',
'timezone' => 'America/Sao_Paulo',
],
],
'auth' => [],
'dependencies' => [
'Global' => [
'actionOk' => [
'class' => TestActionMiddleware::class,
'arguments' => ['just a boolean' => false],
],
'actionBad' => [
'class' => TestActionMiddleware::class,
'arguments' => ['boolean' => true],
],
'actionForbidden' => [
'class' => TestActionMiddleware::class,
'arguments' => ['should simulate an error?' => true, 'response code' => 403],
],
'pipe1' => [
'class' => TestMiddleware::class,
'arguments' => ['this is the name' => 'pipe1']
],
'pipe2' => [
'class' => TestMiddleware::class,
'arguments' => ['literal' => 'pipe2']
],
'pipe3' => [
'class' => TestMiddleware::class,
'arguments' => ['no reference lookup for this' => 'pipe3']
],
'pipe4' => [
'class' => TestMiddleware::class,
'arguments' => ['pipe name' => 'pipe4']
],
// Adapter
HttpAdapterInterface::class => [
'class' => GuzzleHttpAdapter::class,
'arguments' => [
EnvironmentManager::class,
],
'shared' => true,
],
RouterAdapterInterface::class => [
'class' => RouteAdapter::class,
'arguments' => [
ConfigInterface::class,
EnvironmentManager::class,
Result::class,
RouterProxyInterface::class
],
'shared' => true,
],
RouterProxyInterface::class => [
'class' => RouteProxy::class,
'arguments' => [],
'shared' => true,
],
RendererAdapterInterface::class => [
'class' => TwigRendererAdapter::class,
'arguments' => [
ConfigInterface::class,
EnvironmentManager::class,
I18nServiceAdapterInterface::class
],
'shared' => true,
],
I18nServiceAdapterInterface::class => [
'class' => I18nServiceAdapter::class,
'arguments' => [
ConfigInterface::class,
EnvironmentManager::class
],
'shared' => true,
],
I18nDriverAdapterInterface::class => [
'class' => I18nDriverAdapter::class,
'arguments' => [
I18nServiceAdapterInterface::class
],
],
// Middleware
RoutingMiddleware::class => [
'arguments' => [
RouterAdapterInterface::class,
]
],
DispatcherMiddleware::class => [
'arguments' => [
RendererAdapterInterface::class,
]
],
FinalMiddleware::class => [
'class' => TestMiddleware::class,
'arguments' => ['this is the final middleware simulation' => 'final']
],
],
'Website' => [
DateTime::class => [
'arguments' => [
'time' => '2016-04-05 01:02:03',
DateTimeZone::class
]
],
DateTimeZone::class => [
'arguments' => ['timezone' => 'Europe/Berlin']
],
'ThisWillHurt' => [
'class' => WebHemiTest\TestService\TestExceptionMiddleware::class
],
],
'SomeApp' => [
'alias' => [
'class' => ArrayObject::class,
'arguments' => [
'input' => ['something', 2]
]
],
'otherAlias' => [
'inherits' => 'alias'
],
'moreAlias' => [
'inherits' => 'otherAlias',
'shared' => true
],
'lastInherit' => [
'inherits' => 'moreAlias'
],
EmptyService::class => [
'inherits' => 'lastInherit',
'shared' => false
],
'alias1' => [
'class' => DateTime::class,
'arguments' => [
'date' => '2016-04-05 01:02:03'
]
],
'special' => [
'class' => ArrayObject::class,
'calls' => [['offsetSet', ['offset_name' => 'date', 'alias1']]],
'shared' => true
]
],
'OtherApp' => [
'aliasWithReference' => [
'class' => EmptyService::class,
'arguments' => [
'key' => 'theKey',
DateTime::class
]
],
'aliasWithFalseReference' => [
'class' => EmptyService::class,
'arguments' => [
'key' => 'theKey',
'data'=> 'ItIsNotAClassName'
]
],
'aliasWithLiteral' => [
'class' => EmptyService::class,
'arguments' => [
'key' => 'theKey',
'data' => DateTime::class
]
]
]
],
'logger' => [
'unit' => [
'path' => __DIR__.'/../../data/log',
'file_name' => 'testlog-',
'file_extension' => 'log',
'date_format' => 'Y-m-d H:i:s.u',
'log_level' => 0
],
],
'middleware_pipeline' => [
'Global' => [
['service' => 'pipe1', 'priority' => 66],
['service' => 'pipe2', 'priority' => -20],
['service' => 'pipe3'],
['service' => 'pipe4', 'priority' => 100],
['service' => FinalMiddleware::class],
],
'Website' => [],
'SomeApp' => [
['service' => 'someModuleAlias', 'priority' => 55],
],
],
'renderer' => [
'Global' => [
'filter' => [
],
'helper' => [
EmptyRendererHelper::class
],
]
],
'router' => [
'Website' => [
'index' => [
'path' => '^/$',
'middleware' => 'actionOk',
'allowed_methods' => ['GET','POST'],
],
'login' => [
'path' => '^/login$',
'middleware' => 'SomeLoginMiddleware',
'allowed_methods' => ['GET'],
],
'error' => [
'path' => '^/error/?$',
'middleware' => 'actionBad',
'allowed_methods' => ['GET'],
],
'forbidden' => [
'path' => '^/restricted/?$',
'middleware' => 'actionForbidden',
'allowed_methods' => ['GET'],
],
'proxy-view-test' => [
'path' => '^/proxytest'
.'(?P<path>\/[\w\/\-]*\w)?\/(?P<basename>(?!index\.html$)[\w\-\.]+\.[a-z0-9]{2,5})$',
'middleware' => 'proxy',
'allowed_methods' => ['GET'],
],
'proxy-list-test' => [
'path' => '^/proxytest'
.'(?P<path>\/[\w\/\-]*\w)?\/(?P<basename>(?!index\.html$)[\w\-\.]+)(?:\/|\/index\.html)?$',
'middleware' => 'proxy',
'allowed_methods' => ['GET'],
],
],
'SomeApp' => [
'index' => [
'path' => '^/$',
'middleware' => 'SomeIndexMiddleware',
'allowed_methods' => ['GET','POST'],
],
'somepath' => [
'path' => '^/some/path$',
'middleware' => 'SomeOtherMiddleware',
'allowed_methods' => ['GET'],
],
],
],
'session' => [
'namespace' => 'TEST',
'cookie_prefix' => 'abcd',
'session_name_salt' => '<PASSWORD>'
],
'themes' => [
'default' => [
'features' => [
'admin_support' => true,
'admin_login_support' => true,
'website_support' => true
],
'map' => [
'test-page' => 'unit/test.twig',
],
],
'test_theme' => [
'features' => [
'admin_support' => true,
'admin_login_support' => true,
'website_support' => true
],
'map' => [
'test-page' => 'unit/test.twig'
],
],
'test_theme_no_admin' => [
'features' => [
'admin_support' => false,
'admin_login_support' => true,
'website_support' => true
],
'map' => [
'test-page' => 'unit/test.twig'
],
],
'test_theme_no_admin_login' => [
'features' => [
'admin_support' => true,
'admin_login_support' => false,
'website_support' => true
],
'map' => [
'test-page' => 'unit/test.twig'
],
],
'test_theme_no_website' => [
'features' => [
'admin_support' => true,
'admin_login_support' => true,
'website_support' => false
],
'map' => [
'test-page' => 'unit/test.twig'
],
],
],
'ftp' => [],
'email' => []
];
<file_sep>/tests/WebHemiTest/Renderer/TwigRendererAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Renderer;
use InvalidArgumentException;
use WebHemi\Renderer\ServiceInterface as RendererAdapterInterface;
use WebHemi\Renderer\ServiceAdapter\Twig\ServiceAdapter as TwigRendererAdapter;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestService\EmptyEnvironmentManager;
use WebHemiTest\TestService\EmptyI18nService;
use PHPUnit\Framework\TestCase;
/**
* Class TwigRendererAdapterTest.
*/
class TwigRendererAdapterTest extends TestCase
{
/** @var Config */
protected $config;
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
/** @var EmptyEnvironmentManager */
protected $environmentManager;
/** @var EmptyI18nService */
protected $i18nService;
use AssertTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$this->environmentManager = new EmptyEnvironmentManager(
$this->config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$this->i18nService = new EmptyI18nService(
$this->config,
$this->environmentManager
);
}
/**
* Test constructor.
*/
public function testConstructor()
{
$resultObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$this->assertInstanceOf(RendererAdapterInterface::class, $resultObj);
$this->assertAttributeInstanceOf(\Twig_Environment::class, 'adapter', $resultObj);
// test if the config doesn't has the selected theme
$this->environmentManager->setSelectedTheme('someNoneExistingTheme');
$resultObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$this->assertInstanceOf(RendererAdapterInterface::class, $resultObj);
}
/**
* Test renderer for website.
*/
public function testRendererForWebsite()
{
// Website pages are supported by the test_theme
$this->environmentManager->setSelectedApplication('website')
->setSelectedApplicationUri('/')
->setSelectedModule('Website')
->setSelectedTheme('test_theme')
->setRequestUri('/some/page');
$adapterObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$result = $adapterObj->render('test-page');
$resultData = json_decode($result, true);
$this->assertInternalType('array', $resultData);
$this->assertTrue(isset($resultData['template_resource_path']));
$this->assertEquals(
$this->environmentManager->getResourcePath().'/static',
$resultData['template_resource_path']
);
$this->assertEquals('Hello World!', $resultData['message']);
$result = $adapterObj->render('unit/test.twig');
$resultDataOther = json_decode($result, true);
$this->assertArraysAreSimilar($resultData, $resultDataOther);
// Website pages are supported by the test_theme_no_website
$this->environmentManager->setSelectedApplication('website')
->setSelectedApplicationUri('/')
->setSelectedModule('Website')
->setSelectedTheme('test_theme_no_website')
->setRequestUri('/some/page');
$adapterObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$result = $adapterObj->render('test-page');
$resultData = json_decode($result, true);
$this->assertInternalType('array', $resultData);
$this->assertTrue(isset($resultData['template_resource_path']));
$this->assertEquals(
'/resources/default_theme/static',
$resultData['template_resource_path']
);
$this->expectException(InvalidArgumentException::class);
$adapterObj->render('some_non_existing_theme_map_file');
}
/**
* Test renderer for admin login.
*/
public function testRendererForAdminLogin()
{
// Admin login is supported by the test_theme
$this->environmentManager->setSelectedApplication('admin')
->setSelectedApplicationUri('/')
->setSelectedModule('Admin')
->setSelectedTheme('test_theme')
->setRequestUri('/auth/login');
$adapterObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$result = $adapterObj->render('test-page');
$resultData = json_decode($result, true);
$this->assertInternalType('array', $resultData);
$this->assertTrue(isset($resultData['template_resource_path']));
$this->assertEquals(
$this->environmentManager->getResourcePath().'/static',
$resultData['template_resource_path']
);
$this->assertEquals('Hello World!', $resultData['message']);
$result = $adapterObj->render('unit/test.twig');
$resultDataOther = json_decode($result, true);
$this->assertArraysAreSimilar($resultData, $resultDataOther);
// Admin login is NOT supported by the test_theme_no_admin_login
$this->environmentManager->setSelectedApplication('admin')
->setSelectedApplicationUri('/')
->setSelectedModule('Admin')
->setSelectedTheme('test_theme_no_admin_login')
->setRequestUri('/auth/login');
$adapterObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$result = $adapterObj->render('test-page');
$resultData = json_decode($result, true);
$this->assertInternalType('array', $resultData);
$this->assertTrue(isset($resultData['template_resource_path']));
$this->assertEquals(
'/resources/default_theme/static',
$resultData['template_resource_path']
);
$this->expectException(InvalidArgumentException::class);
$adapterObj->render('some_non_existing_theme_map_file');
}
/**
* Test renderer for admin pages.
*/
public function testRendererForAdminPage()
{
// Admin pages are supported by the test_theme
$this->environmentManager->setSelectedApplication('admin')
->setSelectedApplicationUri('/')
->setSelectedModule('Admin')
->setSelectedTheme('test_theme')
->setRequestUri('/some/page');
$adapterObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$result = $adapterObj->render('test-page');
$resultData = json_decode($result, true);
$this->assertInternalType('array', $resultData);
$this->assertTrue(isset($resultData['template_resource_path']));
$this->assertEquals(
$this->environmentManager->getResourcePath().'/static',
$resultData['template_resource_path']
);
$this->assertEquals('Hello World!', $resultData['message']);
$result = $adapterObj->render('unit/test.twig');
$resultDataOther = json_decode($result, true);
$this->assertArraysAreSimilar($resultData, $resultDataOther);
// Admin pages are NOT supported by the test_theme_no_admin
$this->environmentManager->setSelectedApplication('admin')
->setSelectedApplicationUri('/')
->setSelectedModule('Admin')
->setSelectedTheme('test_theme_no_admin')
->setRequestUri('/some/page');
$adapterObj = new TwigRendererAdapter($this->config, $this->environmentManager, $this->i18nService);
$result = $adapterObj->render('test-page');
$resultData = json_decode($result, true);
$this->assertInternalType('array', $resultData);
$this->assertTrue(isset($resultData['template_resource_path']));
$this->assertEquals(
'/resources/default_theme/static',
$resultData['template_resource_path']
);
$this->expectException(InvalidArgumentException::class);
$adapterObj->render('some_non_existing_theme_map_file');
}
}
<file_sep>/src/WebHemi/Renderer/Filter/TagParserFilter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Filter;
use WebHemi\Renderer\FilterInterface;
use WebHemi\Renderer\TagFilterInterface;
/**
* Class TagParserFilter
*/
class TagParserFilter implements FilterInterface
{
/**
* @var TagFilterInterface[]
*/
private $tagFilters;
/**
* TagParserFilter constructor.
*
* @param TagFilterInterface[] ...$tagFilterInterfaces
*/
public function __construct(TagFilterInterface ...$tagFilterInterfaces)
{
foreach ($tagFilterInterfaces as $instance) {
$filterClass = get_class($instance);
$this->tagFilters[$filterClass] = $instance;
}
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'tagParser';
}
/**
* Should return the definition of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{{ "some text with [TAG] in the content"|tagParser }}';
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Search the input text for available tags and replaces them with action outputs';
}
/**
* Gets filter options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* Parses the input text as a markdown script and outputs the HTML.
*
* @uses TagParserFilter::getCurrentUri()
*
* @return string
*/
public function __invoke() : string
{
$text = func_get_args()[0] ?? '';
$matches = [];
if (preg_match_all('/\#(\w+)\#/', $text, $matches)) {
foreach ($matches[1] as $tagFilter) {
$className = __NAMESPACE__.'\\Tags\\'.$tagFilter;
if (isset($this->tagFilters[$className])) {
/**
* @var TagFilterInterface $filter
*/
$filter = $this->tagFilters[$className];
$text = $filter->filter($text);
}
}
}
return $text;
}
}
<file_sep>/config/modules/website/router.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Middleware\Action;
return [
'router' => [
'Website' => [
'website-index' => [
'path' => '^/$',
'middleware' => Action\Website\IndexAction::class,
'allowed_methods' => ['GET', 'POST'],
],
'website-view' => [
'path' => '^(?P<path>\/[\w\/\-]*\w)?\/(?P<basename>(?!index\.html$)[\w\-\.]+\.[a-z0-9]{2,5})$',
'middleware' => 'proxy',
'allowed_methods' => ['GET'],
],
'website-list' => [
'path' => '^(?P<path>\/[\w\/\-]*\w)?\/(?P<basename>(?!index\.html$)[\w\-\.]+)(?:\/|\/index\.html)?$',
'middleware' => 'proxy',
'allowed_methods' => ['GET'],
],
],
],
];
<file_sep>/tests/WebHemiTest/Data/Entity/AbstractEntityTestCase.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use PHPUnit\Framework\TestCase;
use WebHemi\Data\Entity\EntityInterface;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait;
/**
* Class AbstractEntityTestCase
*/
abstract class AbstractEntityTestCase extends TestCase
{
/** @var EntityInterface */
protected $entity;
/** @var array */
protected $testData = [];
/** @var array */
protected $expectedGetters = [];
/** @var array */
protected $expectedSetters = [];
use AssertArraysAreSimilarTrait;
/**
* Tests setters by getting the same array back as the test data
*/
public function testSetters()
{
foreach ($this->expectedSetters as $method => $parameter) {
$this->entity->$method($parameter);
}
$actualResult = $this->entity->toArray();
$this->assertArraysAreSimilar($this->testData, $actualResult, 'toArray');
}
/**
* Tests getters by loading test data.
*/
public function testGetters()
{
$this->entity->fromArray($this->testData);
foreach ($this->expectedGetters as $method => $expectedResult) {
//var_dump($this->testData, $expectedResult, $this->entity->$method());
if (is_array($expectedResult)) {
$this->assertArraysAreSimilar($expectedResult, $this->entity->$method(), $method);
} elseif (is_object($expectedResult)) {
$actualObject = var_export($this->entity->$method(), true);
$expectedObject = var_export($expectedResult, true);
$this->assertSame($expectedObject, $actualObject, $method);
} else {
$this->assertSame($expectedResult, $this->entity->$method(), $method);
}
}
}
}
<file_sep>/src/WebHemi/Middleware/Action/Admin/ControlPanel/Themes/IndexAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Admin\ControlPanel\Themes;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class IndexAction
*/
class IndexAction extends AbstractMiddlewareAction
{
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @var EnvironmentInterface
*/
private $environment;
/**
* @var array
*/
private $defaultData = [
'name' => null,
'title' => null,
'description' => '',
'version' => '',
'author' => 'Unknown',
'homepage' => '',
'license' => '',
'read_only' => false,
'feature_website' => false,
'feature_login' => false,
'feature_admin' => false,
'logo' => '',
'preview' => '',
];
/**
* IndexAction constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environment
*/
public function __construct(ConfigurationInterface $configuration, EnvironmentInterface $environment)
{
$this->configuration = $configuration;
$this->environment = $environment;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-control-panel-themes-list';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$themes = $usedThemes = [];
foreach ($this->configuration->getData('applications') as $application) {
$usedThemes[$application['theme']] = $application['theme'];
}
// Make the default theme read-only.
$usedThemes['default'] = 'default';
foreach ($this->configuration->getData('themes') as $themeName => $themeData) {
$themeStaticPath = '/resources/'.
($themeName == 'default' ? 'default_theme' : 'vendor_themes/'.$themeName)
. '/static/';
$themes[$themeName] = $this->defaultData;
$themes[$themeName]['name'] = $themes[$themeName]['title'] = $themeName;
$themes[$themeName]['read_only'] = isset($usedThemes[$themeName]);
$themes[$themeName]['feature_website'] = (bool) ($themeData['features']['website_support'] ?? false);
$themes[$themeName]['feature_login'] = (bool) ($themeData['features']['admin__login_support'] ?? false);
$themes[$themeName]['feature_admin'] = (bool) ($themeData['features']['admin_support'] ?? false);
foreach ($themeData['legal'] as $name => $value) {
if (in_array($name, ['logo', 'preview'])) {
$value = $themeStaticPath.$value;
}
$themes[$themeName][$name] = $value;
}
}
ksort($themes);
return [
'themes' => $themes,
'progressId' => 'test'
];
}
}
<file_sep>/src/WebHemi/Data/Entity/FilesystemDirectoryEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemDirectoryEntity
*/
class FilesystemDirectoryEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_filesystem_directory' => null,
'description' => null,
'directory_type' => null,
'proxy' => null,
'is_autoindex' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return FilesystemDirectoryEntity
*/
public function setFilesystemDirectoryId(int $identifier) : FilesystemDirectoryEntity
{
$this->container['id_filesystem_directory'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemDirectoryId() : ? int
{
return !is_null($this->container['id_filesystem_directory'])
? (int) $this->container['id_filesystem_directory']
: null;
}
/**
* @param string $description
* @return FilesystemDirectoryEntity
*/
public function setDescription(string $description) : FilesystemDirectoryEntity
{
$this->container['description'] = $description;
return $this;
}
/**
* @return null|string
*/
public function getDescription() : ? string
{
return $this->container['description'];
}
/**
* @param string $directoryType
* @return FilesystemDirectoryEntity
*/
public function setDirectoryType(string $directoryType) : FilesystemDirectoryEntity
{
$this->container['directory_type'] = $directoryType;
return $this;
}
/**
* @return null|string
*/
public function getDirectoryType() : ? string
{
return $this->container['directory_type'];
}
/**
* @param string $proxy
* @return FilesystemDirectoryEntity
*/
public function setProxy(string $proxy) : FilesystemDirectoryEntity
{
$this->container['proxy'] = $proxy;
return $this;
}
/**
* @return null|string
*/
public function getProxy() : ? string
{
return $this->container['proxy'];
}
/**
* @param bool $isAutoindex
* @return FilesystemDirectoryEntity
*/
public function setIsAutoIndex(bool $isAutoindex) : FilesystemDirectoryEntity
{
$this->container['is_autoindex'] = $isAutoindex ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsAutoIndex() : bool
{
return !empty($this->container['is_autoindex']);
}
/**
* @param DateTime $dateTime
* @return FilesystemDirectoryEntity
*/
public function setDateCreated(DateTime $dateTime) : FilesystemDirectoryEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return FilesystemDirectoryEntity
*/
public function setDateModified(DateTime $dateTime) : FilesystemDirectoryEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/src/WebHemi/Form/MultipleElementInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form;
/**
* Interface MultipleElementInterface
*/
interface MultipleElementInterface extends ElementInterface
{
/**
* Sets element to be multiple
*
* @param bool $isMultiple
* @return MultipleElementInterface
*/
public function setMultiple(bool $isMultiple) : MultipleElementInterface;
/**
* Gets element multiple flag.
*
* @return bool
*/
public function getMultiple() : bool;
}
<file_sep>/src/WebHemi/Data/Entity/FilesystemDirectoryDataEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemDirectoryDataEntity
*/
class FilesystemDirectoryDataEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_filesystem' => null,
'id_application' => null,
'id_filesystem_directory' => null,
'description' => null,
'directory_type' => null,
'proxy' => null,
'is_autoindex' => null,
'path' => null,
'basename' => null,
'uri' => null,
'type' => null,
'title' => null,
];
/**
* @param int $identifier
* @return FilesystemDirectoryDataEntity
*/
public function setFilesystemId(int $identifier) : FilesystemDirectoryDataEntity
{
$this->container['id_filesystem'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemId() : ? int
{
return !is_null($this->container['id_filesystem'])
? (int) $this->container['id_filesystem']
: null;
}
/**
* @param int $applicationIdentifier
* @return FilesystemDirectoryDataEntity
*/
public function setApplicationId(int $applicationIdentifier) : FilesystemDirectoryDataEntity
{
$this->container['id_application'] = $applicationIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getApplicationId() : ? int
{
return !is_null($this->container['id_application'])
? (int) $this->container['id_application']
: null;
}
/**
* @param int $identifier
* @return FilesystemDirectoryDataEntity
*/
public function setFilesystemDirectoryId(int $identifier) : FilesystemDirectoryDataEntity
{
$this->container['id_filesystem_directory'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemDirectoryId() : ? int
{
return !is_null($this->container['id_filesystem_directory'])
? (int) $this->container['id_filesystem_directory']
: null;
}
/**
* @param string $description
* @return FilesystemDirectoryDataEntity
*/
public function setDescription(string $description) : FilesystemDirectoryDataEntity
{
$this->container['description'] = $description;
return $this;
}
/**
* @return null|string
*/
public function getDescription() : ? string
{
return $this->container['description'];
}
/**
* @param string $directoryType
* @return FilesystemDirectoryDataEntity
*/
public function setDirectoryType(string $directoryType) : FilesystemDirectoryDataEntity
{
$this->container['directory_type'] = $directoryType;
return $this;
}
/**
* @return null|string
*/
public function getDirectoryType() : ? string
{
return $this->container['directory_type'];
}
/**
* @param string $proxy
* @return FilesystemDirectoryDataEntity
*/
public function setProxy(string $proxy) : FilesystemDirectoryDataEntity
{
$this->container['proxy'] = $proxy;
return $this;
}
/**
* @return null|string
*/
public function getProxy() : ? string
{
return $this->container['proxy'];
}
/**
* @param bool $isAutoindex
* @return FilesystemDirectoryDataEntity
*/
public function setIsAutoIndex(bool $isAutoindex) : FilesystemDirectoryDataEntity
{
$this->container['is_autoindex'] = $isAutoindex ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsAutoIndex() : bool
{
return !empty($this->container['is_autoindex']);
}
/**
* @param string $path
* @return FilesystemDirectoryDataEntity
*/
public function setPath(string $path) : FilesystemDirectoryDataEntity
{
$this->container['path'] = $path;
return $this;
}
/**
* @return null|string
*/
public function getPath() : ? string
{
return $this->container['path'];
}
/**
* @param string $baseName
* @return FilesystemDirectoryDataEntity
*/
public function setBaseName(string $baseName) : FilesystemDirectoryDataEntity
{
$this->container['basename'] = $baseName;
return $this;
}
/**
* @return null|string
*/
public function getBaseName() : ? string
{
return $this->container['basename'];
}
/**
* @param string $uri
* @return FilesystemDirectoryDataEntity
*/
public function setUri(string $uri) : FilesystemDirectoryDataEntity
{
$this->container['uri'] = $uri;
return $this;
}
/**
* @return null|string
*/
public function getUri() : ? string
{
return $this->container['uri'];
}
/**
* @param string $type
* @return FilesystemDirectoryDataEntity
*/
public function setType(string $type) : FilesystemDirectoryDataEntity
{
$this->container['type'] = $type;
return $this;
}
/**
* @return null|string
*/
public function getType() : ? string
{
return $this->container['type'];
}
/**
* @param string $title
* @return FilesystemDirectoryDataEntity
*/
public function setTitle(string $title) : FilesystemDirectoryDataEntity
{
$this->container['title'] = $title;
return $this;
}
/**
* @return null|string
*/
public function getTitle() : ? string
{
return $this->container['title'];
}
}
<file_sep>/config/modules/website/dependencies.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Data;
use WebHemi\Environment;
use WebHemi\Middleware\Action\Website;
use WebHemi\Renderer;
use WebHemi\Router;
return [
'dependencies' => [
'Website' => [
// Services
Router\ServiceInterface::class => [
'class' => Router\ServiceAdapter\Base\ServiceAdapter::class,
'arguments' => [
// This will be added to the Global definition
3 => Router\ProxyInterface::class
],
'shared' => true,
],
Router\ProxyInterface::class => [
'class' => Router\Proxy\FilesystemProxy::class,
'arguments' => [
Data\Storage\ApplicationStorage::class,
Data\Storage\FilesystemStorage::class
],
'shared' => true,
],
// Actions
Website\IndexAction::class => [
'arguments' => [
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class,
Data\Storage\UserStorage::class,
Data\Storage\FilesystemStorage::class,
]
],
// Proxies
'view-post' => [
'class' => Website\View\PostAction::class,
'inherits' => Website\IndexAction::class
],
'list-post' => [
'class' => Website\Directory\PostAction::class,
'inherits' => Website\IndexAction::class
],
'list-category' => [
'class' => Website\Directory\CategoryAction::class,
'inherits' => Website\IndexAction::class
],
'list-tag' => [
'class' => Website\Directory\TagAction::class,
'inherits' => Website\IndexAction::class
],
'list-archive' => [
'class' => Website\Directory\ArchiveAction::class,
'inherits' => Website\IndexAction::class
],
'list-gallery' => [
'class' => Website\Directory\GalleryAction::class,
'inherits' => Website\IndexAction::class
],
'list-binary' => [
'class' => Website\Directory\BinaryAction::class,
'inherits' => Website\IndexAction::class
],
'list-user' => [
'class' => Website\Directory\UserAction::class,
'inherits' => Website\IndexAction::class
],
// Renderer Helpers
Renderer\Helper\GetTagsHelper::class => [
'arguments' => [
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class,
Data\Storage\FilesystemStorage::class,
]
],
Renderer\Helper\GetCategoriesHelper::class => [
'arguments' => [
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class,
Data\Storage\FilesystemStorage::class,
]
],
Renderer\Helper\GetDatesHelper::class => [
'arguments' => [
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class,
Data\Storage\FilesystemStorage::class,
]
]
],
],
];
<file_sep>/src/WebHemi/Router/Proxy/FilesystemProxy.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Router\Proxy;
use WebHemi\Data\Entity;
use WebHemi\Data\Storage\ApplicationStorage;
use WebHemi\Data\Storage\FilesystemStorage;
use WebHemi\Router\ProxyInterface;
use WebHemi\Router\Result\Result;
/**
* Class FilesystemProxy
*/
class FilesystemProxy implements ProxyInterface
{
/**
* @var ApplicationStorage
*/
private $applicationStorage;
/**
* @var FilesystemStorage
*/
private $filesystemStorage;
/**
* FilesystemProxy constructor.
*
* @param ApplicationStorage $applicationStorage
* @param FilesystemStorage $filesystemStorage
*/
public function __construct(
ApplicationStorage $applicationStorage,
FilesystemStorage $filesystemStorage
) {
$this->applicationStorage = $applicationStorage;
$this->filesystemStorage = $filesystemStorage;
}
/**
* Resolves the middleware class name for the application and URL.
*
* @param string $applicationName
* @param Result $routeResult
* @return void
*/
public function resolveMiddleware(string $applicationName, Result&$routeResult) : void
{
/**
* @var null|Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->applicationStorage->getApplicationByName($applicationName);
if (!$applicationEntity instanceof Entity\ApplicationEntity) {
return;
}
$parameters = $routeResult->getParameters();
/**
* @var Entity\FilesystemEntity $fileSystemEntity
*/
$fileSystemEntity = $this->getFilesystemEntityByRouteParams($applicationEntity, $routeResult);
if (!$fileSystemEntity instanceof Entity\FilesystemEntity) {
$routeResult->setStatus(Result::CODE_NOT_FOUND)
->setMatchedMiddleware(null);
return;
}
if ($fileSystemEntity->getType() == Entity\FilesystemEntity::TYPE_DIRECTORY) {
$this->validateDirectoryMiddleware($fileSystemEntity, $routeResult);
} else {
$routeResult->setStatus(Result::CODE_FOUND)
->setMatchedMiddleware(self::VIEW_POST);
}
$routeResult->setParameters($parameters);
}
/**
* @param Entity\FilesystemEntity $fileSystemEntity
* @param Result $routeResult
* @return void
*/
protected function validateDirectoryMiddleware(
Entity\FilesystemEntity $fileSystemEntity,
Result&$routeResult
) : void {
// DirectoryId must exists, as well as the relevant directory entity...
$fileSystemDirectoryEntity = $this->filesystemStorage
->getFilesystemDirectoryById((int) $fileSystemEntity->getFilesystemDirectoryId());
if ($fileSystemDirectoryEntity instanceof Entity\FilesystemDirectoryEntity
&& $fileSystemDirectoryEntity->getIsAutoIndex() === false
) {
$routeResult->setStatus(Result::CODE_FORBIDDEN)
->setMatchedMiddleware(null);
} else {
// Theoretically this alway should be valid, since the proxy is not editable
$middleware = $fileSystemDirectoryEntity->getProxy() ?? self::LIST_POST;
$routeResult->setStatus(Result::CODE_FOUND)
->setMatchedMiddleware($middleware);
}
}
/**
* Gets the filesystem entity.
*
* @param Entity\ApplicationEntity $applicationEntity
* @param Result $routeResult
* @return null|Entity\FilesystemEntity
*/
private function getFilesystemEntityByRouteParams(
Entity\ApplicationEntity $applicationEntity,
Result&$routeResult
) : ? Entity\FilesystemEntity {
$parameters = $routeResult->getParameters();
$path = $parameters['path'];
$baseName = $parameters['basename'];
/**
* @var null|Entity\FilesystemEntity $fileSystemEntity
*/
$fileSystemEntity = $this->filesystemStorage->getFilesystemByApplicationAndPath(
(int) $applicationEntity->getApplicationId(),
$path,
$baseName
);
// If we don't find it as a created content, we try with the preserved contents (tag, categories etc)
if (!$fileSystemEntity && $path != '/' && $routeResult->getResource() == 'website-list') {
$uri = trim($path.'/'.$baseName, '/');
$parts = explode('/', $uri);
$parameters = [
'path' => '/',
'basename' => array_shift($parts),
'uri_parameter' => implode('/', $parts)
];
$routeResult->setParameters($parameters);
$fileSystemEntity = $this->getFilesystemEntityByRouteParams($applicationEntity, $routeResult);
}
return $fileSystemEntity;
}
}
<file_sep>/tests/WebHemiTest/Form/FormPresetTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Form;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use WebHemi\Form\ElementInterface as FormElementInterface;
use WebHemi\Form\ServiceInterface as FormInterface;
use WebHemi\Form\PresetInterface as FormPresetInterface;
use WebHemi\Form\ServiceAdapter\Base\ServiceAdapter as HtmlForm;
use WebHemi\Form\Element\Html\HtmlElement as HtmlFormElement;
use WebHemi\Form\Element\Html\Html5Element as Html5FormElement;
use WebHemi\Form\Element\Html\HtmlMultipleElement as MultipleHtmlFormElement;
use WebHemiTest\TestService\EmptyFormPreset;
/**
* Class FormPresetTest
*/
class FormPresetTest extends TestCase
{
/**
* Tests constructor.
*/
public function testContructor()
{
$htmlElement = new HtmlFormElement();
$html5Element = new Html5FormElement();
$htmlMutipleElement = new MultipleHtmlFormElement();
$formPreset = new EmptyFormPreset(new HtmlForm(), $htmlElement);
$this->assertInstanceOf(FormPresetInterface::class, $formPreset);
$this->assertInstanceOf(FormInterface::class, $formPreset->getPreset());
$expectedArray = [
HtmlFormElement::class => $htmlElement
];
$this->assertAttributeCount(count($expectedArray), 'elementPrototypes', $formPreset);
$formPreset = new EmptyFormPreset(new HtmlForm(), $htmlElement, $htmlMutipleElement, $html5Element);
$expectedArray = [
HtmlFormElement::class => $htmlElement,
MultipleHtmlFormElement::class => $htmlMutipleElement,
Html5FormElement::class => $html5Element
];
$this->assertAttributeCount(count($expectedArray), 'elementPrototypes', $formPreset);
}
/**
* Tests element initializer.
*/
public function testElementCreator()
{
$formPreset = new EmptyFormPreset(new HtmlForm(), new HtmlFormElement());
$element = $formPreset->creatingTestElement(
HtmlFormElement::class,
HtmlFormElement::HTML_ELEMENT_BUTTON,
'test_button',
'Test Button'
);
$this->assertInstanceOf(FormElementInterface::class, $element);
$this->assertSame(HtmlFormElement::HTML_ELEMENT_BUTTON, $element->getType());
$this->expectException(InvalidArgumentException::class);
$formPreset->creatingTestElement(
Html5FormElement::class,
Html5FormElement::HTML5_ELEMENT_DATALIST,
'test_datalist',
'Test Datalist'
);
}
}
<file_sep>/tests/WebHemiTest/Auth/ResultTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Auth;
use Prophecy\Argument;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Query\QueryInterface as DataAdapterInterface;
use WebHemi\Auth\Result\Result;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Data\Entity\UserEntity;
use WebHemiTest\TestService\EmptyAuthAdapter;
use WebHemiTest\TestService\EmptyAuthStorage;
use WebHemiTest\TestService\EmptyCredential;
use WebHemiTest\TestService\EmptyUserStorage;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use PHPUnit\Framework\TestCase;
/**
* Class ResultTest
*/
class ResultTest extends TestCase
{
/** @var array */
private $config;
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
}
/**
* Tests auth adapter Result
*
* @covers \WebHemi\Auth\Result\Result
*/
public function testResult()
{
$defaultAdapter = $this->prophesize(DataAdapterInterface::class);
/** @var DataAdapterInterface $defaultAdapterInstance */
$defaultAdapterInstance = $defaultAdapter->reveal();
$config = new Config($this->config);
$result = new Result();
$authStorage = new EmptyAuthStorage();
$dataEntity = new UserEntity();
$entitySet = new EntitySet();
$dataStorage = new EmptyUserStorage($defaultAdapterInstance, $entitySet, $dataEntity);
$adapter = new EmptyAuthAdapter(
$config,
$result,
$authStorage,
$dataStorage
);
$emptyCredential = new EmptyCredential();
$emptyCredential->setCredential('authResultShouldBe', Result::SUCCESS);
$result = $adapter->authenticate($emptyCredential);
$this->assertTrue($result->isValid());
$this->assertSame(Result::SUCCESS, $result->getCode());
$emptyCredential->setCredential('authResultShouldBe', Result::FAILURE);
$result = $adapter->authenticate($emptyCredential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE, $result->getCode());
// set it to a non-valid result code
$emptyCredential->setCredential('authResultShouldBe', -100);
$result = $adapter->authenticate($emptyCredential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE_OTHER, $result->getCode());
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getUserByCredentials.sql
SELECT
u.`id_user`,
u.`username`,
u.`email`,
u.`password`,
u.`hash`,
u.`is_active`,
u.`is_enabled`,
u.`date_created`,
u.`date_modified`
FROM
`webhemi_user` AS u
WHERE
u.`username` = :username AND
u.`password` = :<PASSWORD>
<file_sep>/tests/WebHemiTest/Router/RouterAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Adapter\Router;
use PHPUnit\Framework\TestCase;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\ServerRequest;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Router\ServiceInterface as RouterAdapterInterface;
use WebHemi\Router\ServiceAdapter\Base\ServiceAdapter as RouteAdapter;
use WebHemi\Router\Result\Result;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use WebHemiTest\TestService\EmptyEnvironmentManager;
use WebHemiTest\TestService\EmptyRouteProxy;
/**
* Class RouterAdapterTest.
*/
class RouterAdapterTest extends TestCase
{
/** @var Config */
protected $config = [];
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
/** @var EmptyEnvironmentManager */
protected $environmentManager;
/** @var Result */
protected $routeResult;
/** @var EmptyRouteProxy */
protected $routeProxy;
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$this->environmentManager = new EmptyEnvironmentManager(
$this->config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$this->routeResult = new Result();
$this->routeProxy = new EmptyRouteProxy();
}
/**
* Tests constructor.
*/
public function testConstructor()
{
$adapterObj = new RouteAdapter(
$this->config,
$this->environmentManager,
$this->routeResult,
$this->routeProxy
);
$this->assertInstanceOf(RouterAdapterInterface::class, $adapterObj);
}
/**
* Tests a private method for various cases.
*/
public function testPrivateMethod()
{
$adapterObj = new RouteAdapter(
$this->config,
$this->environmentManager,
$this->routeResult,
$this->routeProxy
);
$request = new ServerRequest('GET', '/');
$result = $this->invokePrivateMethod($adapterObj, 'getApplicationRouteUri', [$request]);
$this->assertEquals('/', $result);
$request = new ServerRequest('GET', '/some/path/');
$result = $this->invokePrivateMethod($adapterObj, 'getApplicationRouteUri', [$request]);
$this->assertEquals('/some/path/', $result);
// Change application root
$this->environmentManager->setSelectedApplicationUri('/some_application');
$adapterObj = new RouteAdapter(
$this->config,
$this->environmentManager,
$this->routeResult,
$this->routeProxy
);
$request = new ServerRequest('GET', '/some_application/some/path/');
$result = $this->invokePrivateMethod($adapterObj, 'getApplicationRouteUri', [$request]);
$this->assertEquals('/some/path/', $result);
$request = new ServerRequest('GET', '/some_application/');
$result = $this->invokePrivateMethod($adapterObj, 'getApplicationRouteUri', [$request]);
$this->assertEquals('/', $result);
}
/**
* Tests routing with default application.
*/
public function testRouteMatchWithDefaultApplication()
{
$adapterObj = new RouteAdapter(
$this->config,
$this->environmentManager,
$this->routeResult,
$this->routeProxy
);
$request = new ServerRequest('GET', '/');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('actionOk', $result->getMatchedMiddleware());
$request = new ServerRequest('POST', '/');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('actionOk', $result->getMatchedMiddleware());
$request = new ServerRequest('GET', '/login');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('SomeLoginMiddleware', $result->getMatchedMiddleware());
$request = new ServerRequest('POST', '/login');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_BAD_METHOD, $result->getStatus());
$request = new ServerRequest('POST', '/some-non-existing-address');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_NOT_FOUND, $result->getStatus());
}
/**
* Tests routing with not the default application.
*/
public function testRouteMatchWithNonDefaultApplication()
{
$this->environmentManager->setSelectedModule('SomeApp')
->setSelectedApplicationUri('/some_application')
->setSelectedApplication('some_app');
$adapterObj = new RouteAdapter(
$this->config,
$this->environmentManager,
$this->routeResult,
$this->routeProxy
);
$request = new ServerRequest('GET', '/some_application/');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('SomeIndexMiddleware', $result->getMatchedMiddleware());
$request = new ServerRequest('POST', '/some_application/');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('SomeIndexMiddleware', $result->getMatchedMiddleware());
$request = new ServerRequest('GET', '/some_application/some/path');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('SomeOtherMiddleware', $result->getMatchedMiddleware());
$request = new ServerRequest('POST', '/some_application/some/path');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_BAD_METHOD, $result->getStatus());
$request = new ServerRequest('POST', '/some_application/some-non-existing-address');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_NOT_FOUND, $result->getStatus());
}
/**
* Tests routing with default application.
*/
public function testRouteMatchWithProxy()
{
$adapterObj = new RouteAdapter(
$this->config,
$this->environmentManager,
$this->routeResult,
$this->routeProxy
);
$request = new ServerRequest('GET', '/proxytest/test/level/1/actionok.html');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('ActionOK', $result->getMatchedMiddleware());
$this->assertEquals('proxy-view-test', $result->getResource());
$request = new ServerRequest('GET', '/proxytest/some/sub/directory/actionbad.html');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FOUND, $result->getStatus());
$this->assertEquals('ActionBad', $result->getMatchedMiddleware());
$this->assertEquals('proxy-view-test', $result->getResource());
$request = new ServerRequest('GET', '/proxytest/some/sub/directory/non_existing.html');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_NOT_FOUND, $result->getStatus());
$this->assertEquals('proxy-view-test', $result->getResource());
// Test if a directory listing is denied
$request = new ServerRequest('GET', '/proxytest/some/sub/directory');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FORBIDDEN, $result->getStatus());
$this->assertEquals('proxy-list-test', $result->getResource());
$request = new ServerRequest('GET', '/proxytest/some/sub/directory/index.html');
$result = $adapterObj->match($request);
$this->assertEquals(Result::CODE_FORBIDDEN, $result->getStatus());
$this->assertEquals('proxy-list-test', $result->getResource());
}
}
<file_sep>/tests/WebHemiTest/Auth/NameAndPasswordCredentialTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Auth;
use InvalidArgumentException;
use WebHemi\Auth\CredentialInterface as AuthCredentialInterface;
use WebHemi\Auth\Credential\NameAndPasswordCredential;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use PHPUnit\Framework\TestCase;
/**
* Class NameAndPasswordCredentialTest
*/
class NameAndPasswordCredentialTest extends TestCase
{
use AssertTrait;
/**
* Tests constructor.
*/
public function testConstruct()
{
$credential = new NameAndPasswordCredential();
$this->assertInstanceOf(AuthCredentialInterface::class, $credential);
}
/**
* Tests setter and getter methods.
*/
public function testSetterGetter()
{
$credential = new NameAndPasswordCredential();
$expectedResult = ['username' => '', 'password' => ''];
$this->assertArraysAreSimilar($expectedResult, $credential->getCredentials());
$credential->setCredential('username', 'test');
$expectedResult = ['username' => 'test', 'password' => ''];
$this->assertArraysAreSimilar($expectedResult, $credential->getCredentials());
$credential->setCredential('password', '<PASSWORD>');
$expectedResult = ['username' => 'test', 'password' => '<PASSWORD>'];
$this->assertArraysAreSimilar($expectedResult, $credential->getCredentials());
$credential->setCredential('username', '');
$expectedResult = ['username' => '', 'password' => '<PASSWORD>'];
$this->assertArraysAreSimilar($expectedResult, $credential->getCredentials());
$this->expectException(InvalidArgumentException::class);
$credential->setCredential('something', 'test');
}
}
<file_sep>/config/functions.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
/**
* Sets PHP settings according to the environment
*
* @return void
*/
function set_environment()
{
if (!getenv('APPLICATION_ENV')) {
putenv('APPLICATION_ENV=live');
}
if ('dev' == getenv('APPLICATION_ENV')) {
error_reporting(E_ALL);
ini_set('display_errors', 'on');
ini_set('xdebug.var_display_max_depth', 10);
}
}
/**
* Collects and returns some information about the render time. First call will start start, the others will return.
*
* @return array
*/
function render_stat() : array
{
return \WebHemi\GeneralLib::renderStat();
}
/**
* Merge config arrays in the correct way.
* This rewrites the given key->value pairs and does not make key->array(value1, value2) like the
* `array_merge_recursive` does.
*
* @return array
*
* @throws InvalidArgumentException
*/
function merge_array_overwrite()
{
$arguments = func_get_args();
return forward_static_call_array([\WebHemi\GeneralLib::class, 'mergeArrayOverwrite'], $arguments);
}
/**
* Reads the module config directory and returns the config.
*
* @param string $path
* @return array
*/
function compose_config($path = 'modules')
{
$config = [];
$path = trim($path, '/');
$configPath = realpath(__DIR__.'/'.$path);
$entries = glob($configPath.'/*');
foreach ($entries as $entry) {
if (is_file($entry) && preg_match('/.*\.php$/', $entry)) {
$entryConfig = require $entry;
$config = merge_array_overwrite($config, $entryConfig);
} elseif (is_dir($entry)) {
$modulePath = str_replace(__DIR__, '', $entry);
$config = merge_array_overwrite($config, compose_config($modulePath));
}
}
return $config;
}
/**
* Gets the full config
*
* @return array
*/
function get_full_config()
{
static $config;
if (!isset($config)) {
$settingsConfig = compose_config('settings');
$modulesConfig = compose_config('modules');
$config = merge_array_overwrite($settingsConfig, $modulesConfig);
$readOnlyApplications = [
'admin',
'website'
];
$readOnlyApplicationConfig = [
'applications' => [
'website' => [
'module' => 'Website',
'path' => '/',
'type' => 'domain',
],
'admin' => [
'module' => 'Admin',
],
],
];
$config = merge_array_overwrite($config, $readOnlyApplicationConfig);
// ensure that nobody plays with the modules
foreach ($config['applications'] as $application => &$settings) {
if (!in_array($application, $readOnlyApplications)) {
$settings['module'] = 'Website';
}
}
// It is important that the custom application should be checked first, then the 'admin', and the 'website' last
$config['applications'] = array_reverse($config['applications']);
// Add theme config from actual installed themes
$config['themes'] = get_theme_config();
}
return $config;
}
/**
* Reads and parses all the available theme configs.
*
* @return array
*/
function get_theme_config()
{
$themeConfig = [
'themes' => []
];
$defaultThemeConfig = file_get_contents(__DIR__.'/../resources/default_theme/config.json');
$themeConfig['themes']['default'] = json_decode($defaultThemeConfig, true);
$vendorThemePath = realpath(__DIR__.'/../resources/vendor_themes');
$handle = opendir($vendorThemePath);
if (!$handle) {
return $themeConfig['themes'];
}
while (false !== ($entry = readdir($handle))) {
if (is_dir($vendorThemePath.'/'.$entry) && file_exists($vendorThemePath.'/'.$entry.'/config.json')) {
$vendorThemeConfig = file_get_contents($vendorThemePath.'/'.$entry.'/config.json');
$themeConfig['themes'][$entry] = @json_decode($vendorThemeConfig, true);
}
}
closedir($handle);
return $themeConfig['themes'];
}
<file_sep>/src/WebHemi/Middleware/MiddlewareInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
/**
* Interface MiddlewareInterface.
*/
interface MiddlewareInterface
{
/**
* A middleware is a callable. It can do whatever is appropriate with the Request and Response objects.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return void
*/
public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void;
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemDirectoryById.sql
SELECT
fsd.`id_filesystem_directory`,
fsd.`description`,
fsd.`directory_type`,
fsd.`proxy`,
fsd.`is_autoindex`,
fsd.`date_created`,
fsd.`date_modified`
FROM
`webhemi_filesystem_directory` AS fsd
WHERE
fsd.`id_filesystem_directory` = :idDirectory
<file_sep>/src/WebHemi/Middleware/Action/AbstractMiddlewareAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Middleware\MiddlewareInterface;
use WebHemi\Middleware\ActionMiddlewareInterface;
/**
* Class AbstractMiddlewareAction.
*/
abstract class AbstractMiddlewareAction implements MiddlewareInterface, ActionMiddlewareInterface
{
/**
* @var ServerRequestInterface
*/
protected $request;
/**
* @var ResponseInterface
*/
protected $response;
/**
* Gets template map name or template file path.
*
* @return string
*/
abstract public function getTemplateName() : string;
/**
* Gets template data.
*
* @return array
*/
abstract public function getTemplateData() : array;
/**
* Invokes the middleware action.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return void
*/
final public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void
{
// Init
$this->request = $request;
$this->response = $response;
// Process
$templateData = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA, []);
$templateData = array_merge($templateData, $this->getTemplateData());
// Save
$request = $this->request
->withAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_TEMPLATE, $this->getTemplateName())
->withAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA, $templateData);
$response = $this->response;
}
/**
* Returns the routing parameters.
*
* @return array
*/
protected function getRoutingParameters() : array
{
return $this->request->getAttribute('routing_parameters');
}
/**
* Returns the query paramters. This is the processed and filtered _GET data.
*
* @return array
*/
protected function getGetParameters() : array
{
return $this->request->getQueryParams();
}
/**
* Returns the post paramters. This is the processed and filtered _POST data.
*
* @return null|array|object
*/
protected function getPostParameters()
{
return $this->request->getParsedBody();
}
/**
* Returns data from the upladed files.
*
* @return array
*/
protected function getUploadedFiles() : array
{
return $this->request->getUploadedFiles();
}
/**
* Returns all kind of parameters.
*
* @return array
*/
protected function getAllParameters() : array
{
return [
'ROUTE' => $this->getRoutingParameters(),
'GET' => $this->getGetParameters(),
'POST' => $this->getPostParameters(),
'FILES' => $this->getUploadedFiles()
];
}
}
<file_sep>/src/WebHemi/Mailer/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Mailer;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* MailAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration);
/**
* Sets the sender.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function setFrom(string $name, string $email) : ServiceInterface;
/**
* Sets a recipient.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function addTo(string $name, string $email) : ServiceInterface;
/**
* Sets a Carbon Copy recipient.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function addCc(string $name, string $email) : ServiceInterface;
/**
* Sets a Blind Carbon Copy recipient.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function addBcc(string $name, string $email) : ServiceInterface;
/**
* Sets the subject.
*
* @param string $subject
* @return ServiceInterface
*/
public function setSubject(string $subject) : ServiceInterface;
/**
* Sets the body.
*
* @param string $body
* @return ServiceInterface
*/
public function setBody(string $body) : ServiceInterface;
/**
* Adds an attachment to the mail.
*
* @param string $name
* @param string $path
* @return ServiceInterface
*/
public function addAttachment(string $name, string $path) : ServiceInterface;
/**
* Sends the email.
*
* @return bool
*/
public function send() : bool;
}
<file_sep>/src/WebHemi/Environment/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Environment\ServiceAdapter\Base;
use Exception;
use InvalidArgumentException;
use LayerShifter\TLDExtract\Extract;
use LayerShifter\TLDExtract\Result;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\AbstractAdapter;
/**
* Class ServiceAdapter.
*
* @SuppressWarnings(PHPMD.TooManyFields)
*/
class ServiceAdapter extends AbstractAdapter
{
/**
* @var Extract
*/
private $domainAdapter;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
* @param array $getData
* @param array $postData
* @param array $serverData
* @param array $cookieData
* @param array $filesData
* @param array $optionsData
* @throws Exception
*/
public function __construct(
ConfigurationInterface $configuration,
array $getData,
array $postData,
array $serverData,
array $cookieData,
array $filesData,
array $optionsData
) {
$this->configuration = $configuration->getConfig('applications');
$this->domainAdapter = new Extract();
$this->applicationRoot = realpath(__DIR__.'/../../../../../');
// In case when the backend sources are out of the document root.
$this->documentRoot = realpath($this->applicationRoot.'/');
$this->options = $optionsData;
if (isset($serverData['HTTP_REFERER'])) {
$serverData['HTTP_REFERER'] = urldecode($serverData['HTTP_REFERER']);
}
$this->environmentData = [
'GET' => $getData,
'POST' => $postData,
'SERVER' => $serverData,
'COOKIE' => $cookieData,
'FILES' => $filesData,
];
$this->isHttps = isset($this->environmentData['SERVER']['HTTPS']) && $this->environmentData['SERVER']['HTTPS'];
$this->url = 'http'.($this->isHttps ? 's' : '').'://'
.$this->environmentData['SERVER']['HTTP_HOST']
.$this->environmentData['SERVER']['REQUEST_URI']; // contains also the query string
$this->selectedModule = self::DEFAULT_MODULE;
$this->selectedApplication = self::DEFAULT_APPLICATION;
$this->selectedTheme = self::DEFAULT_THEME;
$this->selectedThemeResourcePath = self::DEFAULT_THEME_RESOURCE_PATH;
$this->selectedApplicationUri = self::DEFAULT_APPLICATION_URI;
$this->setDomain()
->setApplication();
}
/**
* Gets the request URI
*
* @return string
*/
public function getRequestUri() : string
{
return rtrim($this->environmentData['SERVER']['REQUEST_URI'], '/');
}
/**
* Gets the request method.
*
* @return string
*/
public function getRequestMethod(): string
{
return $this->environmentData['SERVER']['REQUEST_METHOD'] ?? 'GET';
}
/**
* Gets environment data.
*
* @param string $key
* @return array
*/
public function getEnvironmentData(string $key) : array
{
if (!isset($this->environmentData[$key])) {
throw new InvalidArgumentException(sprintf('The "%s" is not a valid environment key.', $key));
}
return $this->environmentData[$key];
}
/**
* Gets the client IP address.
*
* @return string
*/
public function getClientIp() : string
{
$ipAddress = '';
if (!empty($this->environmentData['SERVER']['HTTP_X_FORWARDED_FOR'])) {
$ipAddress = $this->environmentData['SERVER']['HTTP_X_FORWARDED_FOR'];
} elseif (!empty($this->environmentData['SERVER']['REMOTE_ADDR'])) {
$ipAddress = $this->environmentData['SERVER']['REMOTE_ADDR'];
}
return (string) $ipAddress;
}
/**
* Parses server data and tries to set domain information.
*
* @throws Exception
* @return ServiceAdapter
*/
private function setDomain() : ServiceAdapter
{
$this->setAdapterOptions();
/**
* @var Result $domainParts
*/
$domainParts = $this->domainAdapter->parse($this->url);
if (empty($domainParts->getSuffix())) {
throw new Exception('This application does not support IP access');
}
$this->checkSubdomain($domainParts);
$this->subDomain = $domainParts->getSubdomain();
$this->topDomain = $domainParts->getHostname().'.'.$domainParts->getSuffix();
$this->applicationDomain = $domainParts->getFullHost();
return $this;
}
/**
* Set some adapter specific options.
*
* @return int
*
* @codeCoverageIgnore - don't test third party library
*/
private function setAdapterOptions() : int
{
try {
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE') && 'dev' == getenv('APPLICATION_ENV')) {
$this->domainAdapter->setExtractionMode(Extract::MODE_ALLOW_NOT_EXISTING_SUFFIXES);
}
} catch (\Throwable $exception) {
return $exception->getCode();
}
return 0;
}
/**
* Checks whether the subdomain exists, and rediretcs if no.
*
* @param Result $domainParts
*
* @codeCoverageIgnore - don't test redirect
*/
private function checkSubdomain(Result $domainParts) : void
{
// Redirecting to www when no subdomain is present
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE') && empty($domainParts->getSubdomain())) {
$schema = 'http'.($this->isSecuredApplication() ? 's' : '').'://';
$uri = $this->environmentData['SERVER']['REQUEST_URI'];
header('Location: '.$schema.'www.'.$domainParts->getFullHost().$uri);
exit;
}
}
/**
* Sets application related data.
*
* @throws Exception
* @return ServiceAdapter
*/
private function setApplication() : ServiceAdapter
{
// @codeCoverageIgnoreStart
if (!isset($this->applicationDomain)) {
// For safety purposes only, But it can't happen unless somebody change/overwrite the constructor.
throw new Exception('Domain is not set');
}
// @codeCoverageIgnoreEnd
$urlParts = parse_url($this->url);
list($subDirectory) = explode('/', ltrim($urlParts['path'], '/'), 2);
$applications = $this->configuration->toArray();
$aplicationNames = array_keys($applications);
$selectedApplication = $this->getSelectedApplicationName($aplicationNames, $subDirectory);
$applicationData = $applications[$selectedApplication];
$this->selectedModule = $applicationData['module'] ?? self::DEFAULT_MODULE;
$this->selectedApplication = $selectedApplication;
$this->selectedTheme = $applicationData['theme'] ?? self::DEFAULT_THEME;
$this->selectedApplicationUri = $applicationData['type'] == self::APPLICATION_TYPE_DIRECTORY
? '/'.$subDirectory
: '/';
// Final check for config and resources.
if ($this->selectedTheme !== self::DEFAULT_THEME) {
$this->selectedThemeResourcePath = '/resources/vendor_themes/'.$this->selectedTheme;
}
return $this;
}
/**
* Gets the selected application's name.
*
* @param array $aplicationNames
* @param string $subDirectory
* @return string
*/
private function getSelectedApplicationName(array $aplicationNames, string $subDirectory) : string
{
$selectedApplication = self::DEFAULT_APPLICATION;
/**
* @var string $applicationName
*/
foreach ($aplicationNames as $applicationName) {
if ($this->checkDirectoryIsValid($applicationName, $subDirectory)
|| $this->checkDomainIsValid($applicationName)
) {
$selectedApplication = $applicationName;
break;
}
}
return $selectedApplication;
}
/**
* Checks from type, path it the current URI segment is valid.
*
* @param string $applicationName
* @param string $subDirectory
* @return bool
*/
private function checkDirectoryIsValid(string $applicationName, string $subDirectory) : bool
{
$applications = $this->configuration->toArray();
$applicationData = $applications[$applicationName];
return $applicationName != 'website'
&& $this->applicationDomain == $applicationData['domain']
&& !empty($subDirectory)
&& $applicationData['type'] == self::APPLICATION_TYPE_DIRECTORY
&& $applicationData['path'] == '/'.$subDirectory;
}
/**
* Checks from type and path if the domain is valid. If so, it sets the $subDirectory to the default.
*
* @param string $applicationName
* @return bool
*/
private function checkDomainIsValid(string $applicationName) : bool
{
$applications = $this->configuration->toArray();
$applicationData = $applications[$applicationName];
return $this->applicationDomain == $applicationData['domain']
&& $applicationData['type'] == self::APPLICATION_TYPE_DOMAIN;
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyRendererHelper.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemiTest\TestService;
use WebHemi\Renderer\HelperInterface;
/**
* Class EmptyRendererHelper
*/
class EmptyRendererHelper implements HelperInterface
{
/**
* Should return the name of the helper.
*
* @return string
*/
public static function getName() : string
{
return 'empty';
}
/**
* Should return the name of the helper.
*
* @return string
*/
public static function getDefinition() : string
{
return 'empty(void)';
}
/**
* Should return a description text.
*
* @return string
*/
public static function getDescription() : string
{
return 'Does nothing; returns the arguments';
}
/**
* Should return an array.
*
* @return array
*/
public static function getOptions() : array
{
return [];
}
/**
* A renderer helper should be called with its name.
*
* @param array ...$arguments
* @return mixed
*/
public function __invoke(...$arguments)
{
return implode(' ', $arguments);
}
}
<file_sep>/src/WebHemi/Router/Result/Result.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Router\Result;
use InvalidArgumentException;
/**
* Class Result.
*/
class Result
{
public const CODE_FOUND = 200;
public const CODE_FORBIDDEN = 403;
public const CODE_NOT_FOUND = 404;
public const CODE_BAD_METHOD = 405;
/**
* @var int
*/
private $status;
/**
* @var null|string
*/
private $matchedMiddleware;
/**
* @var string
*/
private $resource;
/**
* @var array
*/
private $statusReason = [
self::CODE_FOUND => 'Resource found.',
self::CODE_FORBIDDEN => 'The requested resource is not accessible.',
self::CODE_NOT_FOUND => 'The requested resource cannot be found.',
self::CODE_BAD_METHOD => 'Bad request method was used by the client.'
];
/**
* @var array
*/
private $parameters;
/**
* Define clone behaviour.
*/
public function __clone()
{
unset($this->status);
unset($this->matchedMiddleware);
unset($this->parameters);
unset($this->resource);
unset($this->parameters);
}
/**
* Sets resource.
*
* @param string $resource
* @return Result
*/
public function setResource(string $resource) : Result
{
$this->resource = $resource;
return $this;
}
/**
* Gets resource.
*
* @return string
*/
public function getResource() : string
{
return $this->resource ?? '';
}
/**
* Sets status code.
*
* @param int $status
* @throws InvalidArgumentException
* @return Result
*/
public function setStatus(int $status) : Result
{
if (!isset($this->statusReason[$status])) {
throw new InvalidArgumentException(sprintf('The parameter "%s" is not a valid router status.', $status));
}
$this->status = $status;
return $this;
}
/**
* Gets status code.
*
* @return int
*/
public function getStatus() : int
{
return $this->status ?? self::CODE_NOT_FOUND;
}
/**
* Gets reason for the status set.
*
* @return string
*/
public function getStatusReason() : string
{
return $this->statusReason[$this->getStatus()] ?? '';
}
/**
* Sets matched middleware.
*
* @param null|string $matchedMiddleware
* @return Result
*/
public function setMatchedMiddleware(? string $matchedMiddleware)
{
$this->matchedMiddleware = $matchedMiddleware;
return $this;
}
/**
* Gets matched middleware.
*
* @return null|string
*/
public function getMatchedMiddleware() : ? string
{
return $this->matchedMiddleware ?? null;
}
/**
* Sets the parameters.
*
* @param array $parameters
* @return Result
*/
public function setParameters(array $parameters) : Result
{
$this->parameters = $parameters;
return $this;
}
/**
* Gets the parameters.
*
* @return array
*/
public function getParameters() : array
{
return $this->parameters ?? [];
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getUserGroupListByUser.sql
SELECT
ug.`id_user_group`,
ug.`name`,
ug.`title`,
ug.`description`,
ug.`is_read_only`,
ug.`date_created`,
ug.`date_modified`
FROM
`webhemi_user_group` AS ug
INNER JOIN `webhemi_user_to_user_group` AS utug ON ug.`id_user_group` = utug.`fk_user_group`
WHERE
utug.`fk_user` = :userId
ORDER BY
ug.`name`
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Middleware/Action/Website/IndexAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Website;
use InvalidArgumentException;
use WebHemi\Data\Entity;
use WebHemi\Data\Storage;
use WebHemi\Data\Storage\StorageInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
use WebHemi\Router\ProxyInterface;
/**
* Class IndexAction.
*/
class IndexAction extends AbstractMiddlewareAction
{
/**
* @var EnvironmentInterface
*/
protected $environmentManager;
/**
* @var StorageInterface[]
*/
private $dataStorages;
/**
* IndexAction constructor.
*
* @param EnvironmentInterface $environmentManager
* @param StorageInterface[] ...$dataStorages
*/
public function __construct(EnvironmentInterface $environmentManager, StorageInterface ...$dataStorages)
{
$this->environmentManager = $environmentManager;
foreach ($dataStorages as $storage) {
$this->dataStorages[get_class($storage)] = $storage;
}
}
/**
* Returns a stored storage instance.
*
* @param string $storageClass
* @return StorageInterface
*/
private function getStorage(string $storageClass) : StorageInterface
{
if (!isset($this->dataStorages[$storageClass])) {
throw new InvalidArgumentException(
sprintf('Storage class reference "%s" is not defined in this class.', $storageClass),
1000
);
}
return $this->dataStorages[$storageClass];
}
/**
* Gets the application storage instance.
*
* @return Storage\ApplicationStorage
*/
protected function getApplicationStorage() : Storage\ApplicationStorage
{
/** @var Storage\ApplicationStorage $storage */
$storage = $this->getStorage(Storage\ApplicationStorage::class);
return $storage;
}
/**
* Gets the filesystem storage instance.
*
* @return Storage\FilesystemStorage
*/
protected function getFilesystemStorage() : Storage\FilesystemStorage
{
/** @var Storage\FilesystemStorage $storage */
$storage = $this->getStorage(Storage\FilesystemStorage::class);
return $storage;
}
/**
* Gets the user storage instance.
*
* @return Storage\UserStorage
*/
protected function getUserStorage() : Storage\UserStorage
{
/** @var Storage\UserStorage $storage */
$storage = $this->getStorage(Storage\UserStorage::class);
return $storage;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'website-index';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$blogPosts = [];
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->getApplicationStorage()
->getApplicationByName($this->environmentManager->getSelectedApplication());
/**
* @var Entity\EntitySet $publications
*/
$publications = $this->getFilesystemStorage()
->getFilesystemPublishedDocumentList((int) $applicationEntity->getApplicationId());
/**
* @var Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
*/
foreach ($publications as $publishedDocumentEntity) {
$blogPosts[] = $this->getBlobPostData($applicationEntity, $publishedDocumentEntity);
}
return [
'activeMenu' => '',
'application' => $this->getApplicationData($applicationEntity),
'fixPost' => $applicationEntity->getIntroduction(),
'blogPosts' => $blogPosts,
];
}
/**
* Gets application data to render.
*
* @param Entity\ApplicationEntity $applicationEntity
* @return array
*/
protected function getApplicationData(Entity\ApplicationEntity $applicationEntity) : array
{
return [
'name' => $applicationEntity->getName(),
'title' => $applicationEntity->getTitle(),
'introduction' => $applicationEntity->getIntroduction(),
'subject' => $applicationEntity->getSubject(),
'description' => $applicationEntity->getDescription(),
'keywords' => $applicationEntity->getKeywords(),
'coptright' => $applicationEntity->getCopyright()
];
}
/**
* Collets the blog post data
*
* @param Entity\ApplicationEntity $applicationEntity
* @param Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
* @return array
*/
protected function getBlobPostData(
Entity\ApplicationEntity $applicationEntity,
Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
) : array {
/**
* @var array $documentMeta
*/
$documentMeta = $this->getFilesystemStorage()
->getSimpleFilesystemMetaListByFilesystem((int) $publishedDocumentEntity->getFilesystemId());
return [
'author' => $this->getPublicationAuthor(
(int) $applicationEntity->getApplicationId(),
(int) $publishedDocumentEntity->getAuthorId()
),
'tags' => $this->getPublicationTags(
(int) $applicationEntity->getApplicationId(),
(int) $publishedDocumentEntity->getFilesystemId()
),
'category' => $this->getPublicationCategory(
(int) $applicationEntity->getApplicationId(),
(int) $publishedDocumentEntity->getCategoryId()
),
'path' => $publishedDocumentEntity->getUri(),
'title' => $publishedDocumentEntity->getTitle(),
'summary' => $publishedDocumentEntity->getDescription(),
'contentLead' => $publishedDocumentEntity->getContentLead(),
'contentBody' => $publishedDocumentEntity->getContentBody(),
'publishedAt' => $publishedDocumentEntity->getDatePublished(),
'meta' => $documentMeta,
];
}
/**
* Gets author information for a filesystem record.
*
* @param int $applicationId
* @param int $userId
* @return array
*/
protected function getPublicationAuthor(int $applicationId, int $userId) : array
{
/**
* @var Entity\UserEntity $user
*/
$user = $this->getUserStorage()
->getUserById($userId);
/**
* @var array $userMeta
*/
$userMeta = $this->getUserStorage()
->getSimpleUserMetaListByUser($userId);
/**
* @var Entity\FilesystemDirectoryDataEntity $userDirectoryData
*/
$userDirectoryData = $this->getFilesystemStorage()
->getFilesystemDirectoryDataByApplicationAndProxy($applicationId, ProxyInterface::LIST_USER);
return [
'userId' => $userId,
'userName' => $user->getUserName(),
'url' => $userDirectoryData->getUri().'/'.$user->getUserName(),
'meta' => $userMeta,
];
}
/**
* Collects all the tags for a filesystem record.
*
* @param int $applicationId
* @param int $filesystemId
* @return array
*/
protected function getPublicationTags(int $applicationId, int $filesystemId) : array
{
$tags = [];
/**
* @var Entity\EntitySet $tagEntities
*/
$tagEntities = $this->getFilesystemStorage()
->getFilesystemTagListByFilesystem($filesystemId);
/**
* @var Entity\FilesystemDirectoryDataEntity $categoryDirectoryData
*/
$categoryDirectoryData = $this->getFilesystemStorage()
->getFilesystemDirectoryDataByApplicationAndProxy($applicationId, ProxyInterface::LIST_TAG);
/**
* @var Entity\FilesystemTagEntity $tagEntity
*/
foreach ($tagEntities as $tagEntity) {
$tags[] = [
'url' => $categoryDirectoryData->getUri().'/'.$tagEntity->getName(),
'name' => $tagEntity->getName(),
'title' => $tagEntity->getTitle()
];
}
return $tags;
}
/**
* Gets the category for a filesystem record.
*
* @param int $applicationId
* @param int $categoryId
* @return array
*/
protected function getPublicationCategory(int $applicationId, int $categoryId) : array
{
/**
* @var Entity\FilesystemCategoryEntity $categoryEntity
*/
$categoryEntity = $this->getFilesystemStorage()
->getFilesystemCategoryById($categoryId);
/**
* @var Entity\FilesystemDirectoryDataEntity $categoryDirectoryData
*/
$categoryDirectoryData = $this->getFilesystemStorage()
->getFilesystemDirectoryDataByApplicationAndProxy($applicationId, ProxyInterface::LIST_CATEGORY);
$category = [
'url' => $categoryDirectoryData->getUri().'/'.$categoryEntity->getName(),
'name' => $categoryEntity->getName(),
'title' => $categoryEntity->getTitle()
];
return $category;
}
}
<file_sep>/src/WebHemi/StringLib.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi;
/**
* Class StringLib
*/
class StringLib
{
/**
* Converts CamelCase text to under_score equivalent.
*
* @param string $input
* @return string
*/
public static function convertCamelCaseToUnderscore(string $input) : string
{
$input[0] = strtolower($input[0]);
return strtolower(preg_replace('/([A-Z])/', '_\\1', $input));
}
/**
* Converts under_score to CamelCase equivalent.
*
* @param string $input
* @return string
*/
public static function convertUnderscoreToCamelCase(string $input) : string
{
$input = preg_replace('/_([a-zA-Z0-9])/', '#\\1', $input);
$parts = explode('#', $input);
array_walk(
$parts,
function (&$value) {
$value = ucfirst(strtolower($value));
}
);
return implode($parts);
}
/**
* Converts all non-alphanumeric and additional extra characters to underscore.
*
* @param string $input
* @param string $extraCharacters
* @return string
*/
public static function convertNonAlphanumericToUnderscore(string $input, string $extraCharacters = '') : string
{
// Escape some characters that can affect badly the regular expression.
$extraCharacters = str_replace(
['-', '[', ']', '(', ')', '/', '$', '^'],
['\\-', '\\[', '\\]', '\\(', '\\)', '\\/', '\\$', '\\^'],
$extraCharacters
);
$output = preg_replace('/[^a-zA-Z0-9'.$extraCharacters.']/', '_', $input);
while (strpos($output, '__') !== false) {
$output = str_replace('__', '_', $output);
}
return trim($output, '_');
}
/**
* Splits text into array of lines and also trims and skips empty lines.
*
* @param string $input
* @param int $flags
* @return array
*/
public static function convertTextToLines(string $input, int $flags = PREG_SPLIT_NO_EMPTY) : array
{
return preg_split('/\s*\R\s*/', trim($input), -1, $flags);
}
/**
* Joins array of lines into text.
*
* @param array $input
* @return string
*/
public static function convertLinesToText(array $input) : string
{
return implode(PHP_EOL, $input);
}
}
<file_sep>/src/WebHemi/Data/Storage/ApplicationStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Query\QueryInterface;
/**
* Class ApplicationStorage.
*/
class ApplicationStorage extends AbstractStorage
{
/**
* Returns every Application entity.
*
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getApplicationList(
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getApplicationList',
[
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(ApplicationEntity::class, $data);
}
/**
* Returns a Application entity identified by (unique) ID.
*
* @param int $identifier
* @return null|ApplicationEntity
*/
public function getApplicationById(int $identifier) : ? ApplicationEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getApplicationById',
[
':idApplication' => $identifier
]
);
/** @var null|ApplicationEntity $entity */
$entity = $this->getEntity(ApplicationEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns an Application entity by name.
*
* @param string $name
* @return null|ApplicationEntity
*/
public function getApplicationByName(string $name) : ? ApplicationEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getApplicationByName',
[
':name' => $name
]
);
/** @var null|ApplicationEntity $entity */
$entity = $this->getEntity(ApplicationEntity::class, $data[0] ?? []);
return $entity;
}
}
<file_sep>/tests/WebHemiTest/Configuration/ConfigTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Configuration;
use InvalidArgumentException;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use PHPUnit\Framework\TestCase;
/**
* Class ConfigTest.
*/
class ConfigTest extends TestCase
{
/** @var array */
protected $testConfig;
/** @var array */
protected $processedConfig;
use AssertTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->testConfig = [
'A' => [
'A1' => [
'A11' => [
'some_key' => 'some data',
'some other key' => 'some other data',
],
'A12' => [
'some_key_of_a12' => 'some data',
'some other key' => [
'A12x4' => 'deepest level',
]
],
],
'A2' => null,
],
'B' => 'data',
'C' => [
'C1' => [
'some_key' => 'some data',
'some other key' => 'some other data',
],
],
];
$this->processConfig('', $this->testConfig);
}
/**
* Processes the config into a one dimensional array.
*
* @param $path
* @param $config
*/
protected function processConfig($path, $config)
{
if (!is_array($config)) {
return;
}
foreach ($config as $key => $value) {
$this->processedConfig[$path.$key] = $value;
if (is_array($value) && !empty($value)) {
$this->processConfig($path.$key.'/', $value);
}
}
}
/**
* Test constructor with empty array.
*/
public function testEmptyConfig()
{
$config = new Config([]);
$this->assertAttributeEmpty('pathMap', $config);
$this->assertAttributeEmpty('rawConfig', $config);
}
/**
* Test constructor with test config.
*/
public function testConfigProcess()
{
$config = new Config($this->testConfig);
$this->assertAttributeEquals($this->testConfig, 'rawConfig', $config);
$this->assertAttributeEquals($this->processedConfig, 'pathMap', $config);
}
/**
* Test the processed config.
*/
public function testPathMap()
{
$config = new Config($this->testConfig);
$this->assertFalse($config->has('NonExistingKey'));
$this->assertTrue($config->has('A/A1/A11'));
$this->assertFalse($config->has('A/A1/A11/'));
$this->assertArraysAreSimilar($config->getData('A/A1/A11'), $this->testConfig['A']['A1']['A11']);
$this->assertEquals('deepest level', $config->getData('A/A1/A12/some other key/A12x4')[0]);
$this->assertArraysAreSimilar($config->getData('C/C1'), $this->testConfig['A']['A1']['A11']);
$subConfig = $config->getConfig('A/A1/A11');
$this->assertInstanceOf(Config::class, $subConfig);
$this->assertFalse($config === $subConfig);
$this->assertArraysAreSimilar($subConfig->toArray(), $this->testConfig['A']['A1']['A11']);
}
/**
* Test whether the instance throws exception for invalid path.
*
* @throws InvalidArgumentException
*/
public function testExceptionData()
{
$this->expectException(InvalidArgumentException::class);
$config = new Config($this->testConfig);
$config->getData('NonExistingKey');
}
/**
* Test whether the instance throws exception for invalid path.
*
* @throws InvalidArgumentException
*/
public function testExceptionConfig()
{
$this->expectException(InvalidArgumentException::class);
$config = new Config($this->testConfig);
$config->getConfig('NonExistingKey');
}
}
<file_sep>/tests/WebHemiTest/Environment/EnvironmentManagerTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Environment;
use InvalidArgumentException;
use WebHemi\Environment\ServiceAdapter\Base\ServiceAdapter as EnvironmentManager;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use PHPUnit\Framework\TestCase;
/**
* Class EnvironmentManagerTest.
*/
class EnvironmentManagerTest extends TestCase
{
/** @var array */
protected $config;
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
use AssertTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = [
'applications' => [
'website' => [
'module' => 'Website',
'type' => 'domain',
'path' => '/',
'domain' => 'unittest.dev',
'language' => 'en',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
],
'admin' => [
'module' => 'Admin',
'type' => 'directory',
'path' => 'admin',
'domain' => 'unittest.dev',
'language' => 'en',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
]
],
'themes' => [
'default' => [],
'test_theme' => []
]
];
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'HTTP_REFERER' => 'http://foo.org?uri='.urlencode('https://www.youtube.com/'),
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
}
/**
* Returns the config in the correct order.
*
* @return array
*/
private function getOrderedConfig()
{
// It is important that the custom application should be checked first, then the 'admin', and the 'website' last
$this->config['applications'] = array_reverse($this->config['applications']);
return $this->config;
}
/**
* Tests constructor with basic data.
*/
public function testConstructor()
{
$config = new Config($this->config);
$options = ['some' => 'option'];
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
$options
);
$this->assertInstanceOf(EnvironmentManager::class, $testObj);
$this->assertEquals(EnvironmentManager::DEFAULT_APPLICATION, $testObj->getSelectedApplication());
$this->assertEquals(EnvironmentManager::DEFAULT_APPLICATION_URI, $testObj->getSelectedApplicationUri());
$this->assertEquals(EnvironmentManager::DEFAULT_MODULE, $testObj->getSelectedModule());
$this->assertEquals(EnvironmentManager::DEFAULT_THEME, $testObj->getSelectedTheme());
$this->assertEquals(EnvironmentManager::DEFAULT_THEME_RESOURCE_PATH, $testObj->getResourcePath());
$this->assertEquals(realpath(__DIR__.'/../../../'), $testObj->getDocumentRoot());
$this->assertEquals(realpath(__DIR__.'/../../..'), $testObj->getApplicationRoot());
$this->assertArraysAreSimilar($options, $testObj->getOptions());
$actualServerData = $testObj->getEnvironmentData('SERVER');
$expectedServerData = $this->server;
$expectedServerData['HTTP_REFERER'] = urldecode($expectedServerData['HTTP_REFERER']);
$this->assertArraysAreSimilar($actualServerData, $expectedServerData);
$this->expectException(InvalidArgumentException::class);
$testObj->getEnvironmentData('WEBSERVER');
}
/**
* Tests directory-based application.
*/
public function testDirectoryApplicationSettings()
{
$this->config['applications']['TestApplication'] = [
'domain' => 'unittest.dev',
'type' => 'directory',
'path' => '/test_app',
];
$this->server['REQUEST_URI'] = '/test_app/some_page';
$config = new Config($this->getOrderedConfig());
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertInstanceOf(EnvironmentManager::class, $testObj);
$this->assertEquals('TestApplication', $testObj->getSelectedApplication());
$this->assertEquals('/test_app', $testObj->getSelectedApplicationUri());
$this->assertEquals('/test_app/some_page', $testObj->getRequestUri());
}
/**
* Tests domain-based application.
*/
public function testDomainApplicationSettings()
{
$this->config['applications']['TestApplication'] = [
'domain' => 'test.app.unittest.dev',
'type' => 'domain',
'path' => '/',
];
$this->server['HTTP_HOST'] = 'test.app.unittest.dev';
$this->server['SERVER_NAME'] = 'test.app.unittest.dev';
$this->server['REQUEST_URI'] = '/test_app/some_page';
$config = new Config($this->getOrderedConfig());
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertInstanceOf(EnvironmentManager::class, $testObj);
$this->assertEquals('TestApplication', $testObj->getSelectedApplication());
$this->assertEquals('/', $testObj->getSelectedApplicationUri());
$this->assertEquals('test.app.unittest.dev', $testObj->getApplicationDomain());
$this->assertFalse($testObj->isSecuredApplication());
}
/**
* Tests getting client IP.
*/
public function testGetClientIp()
{
$config = new Config($this->getOrderedConfig());
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertEmpty($testObj->getClientIp());
$this->server['REMOTE_ADDR'] = 'some_ip';
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertSame('some_ip', $testObj->getClientIp());
$this->server['HTTP_X_FORWARDED_FOR'] = 'some_forwarded_ip';
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertSame('some_forwarded_ip', $testObj->getClientIp());
$this->server['REMOTE_ADDR'] = 'some_other_ip';
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertSame('some_forwarded_ip', $testObj->getClientIp());
}
/**
* Tests vendor theme resource path.
*/
public function testThemePathSettings()
{
$this->config['applications']['TestApplication'] = [
'domain' => 'test.app.unittest.dev',
'type' => 'domain',
'path' => '/',
'theme' => 'test_theme'
];
$this->server['HTTP_HOST'] = 'test.app.unittest.dev';
$this->server['SERVER_NAME'] = 'test.app.unittest.dev';
$this->server['REQUEST_URI'] = '/test_app/some_page';
$config = new Config($this->getOrderedConfig());
$testObj = new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$this->assertInstanceOf(EnvironmentManager::class, $testObj);
$this->assertEquals('TestApplication', $testObj->getSelectedApplication());
$this->assertEquals('/', $testObj->getSelectedApplicationUri());
$this->assertEquals('/resources/vendor_themes/test_theme', $testObj->getResourcePath());
}
/**
* Tests setDomain() error.
*/
public function testSetDomainWithIp()
{
$this->config['applications']['TestApplication'] = [
'domain' => '192.168.100.12',
'type' => 'domain',
'path' => '/',
'theme' => 'test_theme'
];
$this->server['HTTP_HOST'] = '192.168.100.12';
$this->server['SERVER_NAME'] = '192.168.100.12';
$this->server['REQUEST_URI'] = '/test_app/some_page';
$config = new Config($this->getOrderedConfig());
$expectedError = 'This application does not support IP access';
try {
new EnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
} catch (\Throwable $exception) {
$this->assertSame($expectedError, $exception->getMessage());
}
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptySessionManager.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Session\ServiceAdapter\Base\ServiceAdapter as SessionManager;
use WebHemi\Session\ServiceInterface;
/**
* Class EmptySessionManager.
*/
class EmptySessionManager extends SessionManager
{
/** @var string */
public $namespace;
/** @var string */
public $cookiePrefix;
/** @var string */
public $sessionNameSalt;
/** @var array */
public $readOnly = [];
/** @var array */
public $data = [];
/** @var array */
public $session;
/** @var string */
public $sessionName;
/** @var string */
public $sessionId;
/** @var int */
public $sessionIdCounter = 1;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$configuration = $configuration->getData('session');
$this->namespace = $configuration['namespace'];
$this->cookiePrefix = $configuration['cookie_prefix'];
$this->sessionNameSalt = $configuration['session_name_salt'];
}
/**
* Saves data back to session.
*/
public function __destruct()
{
$this->write();
}
/**
* Reads PHP Session array to class property.
*
* @return void
*
* @codeCoverageIgnore
*/
private function read() : void
{
$this->data = $this->session[$this->namespace];
}
/**
* Writes class property to PHP Session array.
*
* @return void
*
* @codeCoverageIgnore
*/
private function write() : void
{
$this->session[$this->namespace] = $this->data;
}
/**
* Check whether the session has already been started.
*
* @return bool
*
* @codeCoverageIgnore
*/
private function sessionStarted() : bool
{
return !empty($this->session);
}
/**
* Starts a session.
*
* @param string $name
* @param int $timeOut
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httpOnly
* @return ServiceInterface
*/
public function start(
string $name,
int $timeOut = 3600,
string $path = '/',
? string $domain = null,
bool $secure = false,
bool $httpOnly = false
) : ServiceInterface {
if ($this->sessionStarted()) {
throw new RuntimeException('Cannot start session. Session is already started.', 1000);
}
unset($timeOut, $path, $domain, $secure, $httpOnly);
$this->session[$this->namespace]['started'] = true;
$this->sessionName = $this->cookiePrefix.'-'.bin2hex($name.$this->sessionNameSalt);
$this->sessionId = 'unittest_'.md5($this->namespace.$this->sessionIdCounter);
$this->read();
return $this;
}
/**
* Regenerates session identifier.
*
* @return ServiceInterface
*/
public function regenerateId() : ServiceInterface
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot regenerate session identifier. Session is not started yet.', 1001);
}
$this->sessionIdCounter++;
$this->sessionId = 'unittest_'.md5($this->namespace.$this->sessionIdCounter);
return $this;
}
/**
* Returns the session id.
*
* @return string
*/
public function getSessionId() : string
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot retrieve session identifier. Session is not started yet.', 1010);
}
return $this->sessionId;
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemTagByApplicationAndName.sql
SELECT
fst.`id_filesystem_tag`,
fst.`fk_application`,
fst.`name`,
fst.`title`,
fst.`description`,
fst.`date_created`,
fst.`date_modified`
FROM
`webhemi_filesystem_tag` AS fst
WHERE
fst.`fk_application` = :idApplication AND
fst.`name` = :name
<file_sep>/tests/WebHemiTest/Form/HtmlFormElementTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Form;
use PHPUnit\Framework\TestCase;
use InvalidArgumentException;
use WebHemi\Form\Element\Html\HtmlElement as HtmlFormElement;
use WebHemi\Form\Element\Html\HtmlMultipleElement as HtmlMultipleFormElement;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestService\TestFalseValidator;
use WebHemiTest\TestService\TestTrueValidator;
/**
* Class HtmlFormElementTest
*/
class HtmlFormElementTest extends TestCase
{
use AssertTrait;
/**
* Test constructor.
*/
public function testConstructor()
{
$formElement = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_FILE, 'test');
$this->assertSame('inputFile', $formElement->getType());
$this->assertSame('test', $formElement->getName());
$this->assertSame('id_test', $formElement->getId());
$this->assertSame('test', $formElement->getLabel());
$this->assertEmpty($formElement->getValues());
$this->assertEmpty($formElement->getValueRange());
$this->assertEmpty($formElement->getErrors());
$this->expectException(InvalidArgumentException::class);
new HtmlMultipleFormElement(HtmlFormElement::HTML_ELEMENT_BUTTON, 'not-good');
}
/**
* Tests the setName method which also sets the identifier.
*/
public function testSetNameAndId()
{
$formElement = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_FILE, 'test');
$this->assertSame('test', $formElement->getName());
$this->assertSame('id_test', $formElement->getId());
$formElement->setName('SomeCamelCaseName');
$this->assertSame('some_camel_case_name', $formElement->getName());
$this->assertSame('id_some_camel_case_name', $formElement->getId());
$formElement->setName('SomeCamelCaseName[with-Dash][and-NestedName]');
$this->assertSame('some_camel_case_name[with_dash][and_nested_name]', $formElement->getName());
$this->assertSame('id_some_camel_case_name_with_dash_and_nested_name', $formElement->getId());
$this->expectException(InvalidArgumentException::class);
$formElement->setName('{--$#--}(%)');
}
/**
* Tests simple setter and getter methods.
*/
public function testSettersAndGetters()
{
$formElement = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'test');
$result = $formElement->setLabel('My Label');
$this->assertInstanceOf(HtmlFormElement::class, $result);
$this->assertSame('My Label', $formElement->getLabel());
$this->assertEmpty($formElement->getValueRange());
$formElement->setValueRange([]);
$this->assertEmpty($formElement->getValueRange());
$this->assertInternalType('array', $formElement->getValueRange());
$expectedData = ['my' => 'data', 'unit_test' => 'passed'];
$formElement->setValueRange($expectedData);
$this->assertInternalType('array', $formElement->getValueRange());
$this->assertArraysAreSimilar($expectedData, $formElement->getValueRange());
$this->assertEmpty($formElement->getValues());
$expectedData = ['my' => 'values', 'unit_test' => 'passed'];
$formElement->setValues($expectedData);
$this->assertInternalType('array', $formElement->getValues());
$this->assertArraysAreSimilar($expectedData, $formElement->getValues());
$formElement = new HtmlMultipleFormElement(HtmlMultipleFormElement::HTML_MULTIPLE_ELEMENT_SELECT, 'test');
$this->assertFalse($formElement->getMultiple());
$formElement->setMultiple(true);
$this->assertTrue($formElement->getMultiple());
$formElement->setMultiple(false);
$this->assertFalse($formElement->getMultiple());
}
/**
* Test validation.
*/
public function testValidator()
{
$trueValidator = new TestTrueValidator();
$falseValidator = new TestFalseValidator();
$formElement = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'test');
$formElement->validate();
$this->assertEmpty($formElement->getErrors());
$formElement->addValidator($trueValidator);
$formElement->validate();
$this->assertEmpty($formElement->getErrors());
$expectedErrors = [TestFalseValidator::class => ['The data is not valid']];
$formElement->addValidator($falseValidator);
$formElement->validate();
$this->assertArraysAreSimilar($expectedErrors, $formElement->getErrors());
$expectedErrors = [TestFalseValidator::class => ['The data is not valid'], 'something' => ['error']];
$formElement->setError('something', 'error');
$this->assertArraysAreSimilar($expectedErrors, $formElement->getErrors());
}
}
<file_sep>/src/WebHemi/Data/Entity/ApplicationEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use DateTimeZone;
use WebHemi\DateTime;
/**
* Class AbstractEntity
*/
class ApplicationEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_application' => null,
'name' => null,
'title' => null,
'introduction' => null,
'subject' => null,
'description' => null,
'keywords' => null,
'copyright' => null,
'path' => null,
'theme' => null,
'type' => null,
'locale' => null,
'timezone' => null,
'is_read_only' => null,
'is_enabled' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return ApplicationEntity
*/
public function setApplicationId(int $identifier) : ApplicationEntity
{
$this->container['id_application'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getApplicationId() : ? int
{
return !is_null($this->container['id_application'])
? (int) $this->container['id_application']
: null;
}
/**
* @param string $name
* @return ApplicationEntity
*/
public function setName(string $name) : ApplicationEntity
{
$this->container['name'] = $name;
return $this;
}
/**
* @return null|string
*/
public function getName() : ? string
{
return $this->container['name'];
}
/**
* @param string $title
* @return ApplicationEntity
*/
public function setTitle(string $title) : ApplicationEntity
{
$this->container['title'] = $title;
return $this;
}
/**
* @return null|string
*/
public function getTitle() : ? string
{
return $this->container['title'];
}
/**
* @param string $introduction
* @return ApplicationEntity
*/
public function setIntroduction(string $introduction) : ApplicationEntity
{
$this->container['introduction'] = $introduction;
return $this;
}
/**
* @return null|string
*/
public function getIntroduction() : ? string
{
return $this->container['introduction'];
}
/**
* @param string $subject
* @return ApplicationEntity
*/
public function setSubject(string $subject) : ApplicationEntity
{
$this->container['subject'] = $subject;
return $this;
}
/**
* @return null|string
*/
public function getSubject() : ? string
{
return $this->container['subject'];
}
/**
* @param string $description
* @return ApplicationEntity
*/
public function setDescription(string $description) : ApplicationEntity
{
$this->container['description'] = $description;
return $this;
}
/**
* @return null|string
*/
public function getDescription() : ? string
{
return $this->container['description'];
}
/**
* @param string $keywords
* @return ApplicationEntity
*/
public function setKeywords(string $keywords) : ApplicationEntity
{
$this->container['keywords'] = $keywords;
return $this;
}
/**
* @return null|string
*/
public function getKeywords() : ? string
{
return $this->container['keywords'];
}
/**
* @param string $copyright
* @return ApplicationEntity
*/
public function setCopyright(string $copyright) : ApplicationEntity
{
$this->container['copyright'] = $copyright;
return $this;
}
/**
* @return null|string
*/
public function getCopyright() : ? string
{
return $this->container['copyright'];
}
/**
* @param string $path
* @return ApplicationEntity
*/
public function setPath(string $path) : ApplicationEntity
{
$this->container['path'] = $path;
return $this;
}
/**
* @return null|string
*/
public function getPath() : ? string
{
return $this->container['path'];
}
/**
* @param string $theme
* @return ApplicationEntity
*/
public function setTheme(string $theme) : ApplicationEntity
{
$this->container['theme'] = $theme;
return $this;
}
/**
* @return null|string
*/
public function getTheme() : ? string
{
return $this->container['theme'];
}
/**
* @param string $type
* @return ApplicationEntity
*/
public function setType(string $type) : ApplicationEntity
{
$this->container['type'] = $type;
return $this;
}
/**
* @return null|string
*/
public function getType() : ? string
{
return $this->container['type'];
}
/**
* @param string $locale
* @return ApplicationEntity
*/
public function setLocale(string $locale) : ApplicationEntity
{
$this->container['locale'] = $locale;
return $this;
}
/**
* @return null|string
*/
public function getLocale() : ? string
{
return $this->container['locale'];
}
/**
* @param DateTimeZone $timeZone
* @return ApplicationEntity
*/
public function setTimeZone(DateTimeZone $timeZone) : ApplicationEntity
{
$this->container['timezone'] = $timeZone->getName();
return $this;
}
/**
* @return DateTimeZone|null
*/
public function getTimeZone() : ? DateTimeZone
{
return !empty($this->container['timezone'])
? new DateTimeZone($this->container['timezone'])
: null;
}
/**
* @param bool $isReadonly
* @return ApplicationEntity
*/
public function setIsReadOnly(bool $isReadonly) : ApplicationEntity
{
$this->container['is_read_only'] = $isReadonly ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsReadOnly() : bool
{
return !empty($this->container['is_read_only']);
}
/**
* @param bool $isEnabled
* @return ApplicationEntity
*/
public function setIsEnabled(bool $isEnabled) : ApplicationEntity
{
$this->container['is_enabled'] = $isEnabled ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsEnabled() : bool
{
return !empty($this->container['is_enabled']);
}
/**
* @param DateTime $dateTime
* @return ApplicationEntity
*/
public function setDateCreated(DateTime $dateTime) : ApplicationEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return ApplicationEntity
*/
public function setDateModified(DateTime $dateTime) : ApplicationEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/tests/WebHemiTest/Router/ResultTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Router;
use InvalidArgumentException;
use WebHemi\Router\Result\Result;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use PHPUnit\Framework\TestCase;
/**
* Class ResultTest.
*/
class ResultTest extends TestCase
{
use AssertTrait;
/**
* Test general usage.
*/
public function testGeneralResult()
{
$result = new Result();
$this->assertInstanceOf(Result::class, $result);
$result->setMatchedMiddleware('Some data');
$this->assertEquals($result->getMatchedMiddleware(), 'Some data');
$testParam = [
'param_1' => 'data 1',
'param_2' => 'data 2'
];
$result->setParameters($testParam);
$this->assertArraysAreSimilar($testParam, $result->getParameters());
$result->setStatus(200);
$this->assertEquals($result->getStatus(), Result::CODE_FOUND);
$this->assertEquals($result->getStatusReason(), 'Resource found.');
$result->setStatus(404);
$this->assertEquals($result->getStatus(), Result::CODE_NOT_FOUND);
$this->assertEquals($result->getStatusReason(), 'The requested resource cannot be found.');
$result->setStatus(405);
$this->assertEquals($result->getStatus(), Result::CODE_BAD_METHOD);
$this->assertEquals($result->getStatusReason(), 'Bad request method was used by the client.');
}
/**
* Test whether the instance throws exception for invalid status code.
*
* @throws InvalidArgumentException
*/
public function testException()
{
$this->expectException(InvalidArgumentException::class);
$result = new Result();
$result->setStatus(102);
}
}
<file_sep>/src/WebHemi/Router/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Router;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param Result\Result $routeResult
* @param null|ProxyInterface $routerProxy
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
Result\Result $routeResult,
? ProxyInterface $routerProxy = null
);
/**
* Processes the Request and give a Result.
*
* @param ServerRequestInterface $request
* @return Result\Result
*/
public function match(ServerRequestInterface $request) : Result\Result;
}
<file_sep>/tests/WebHemiTest/Application/BaseApplicationTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Application;
use PHPUnit\Framework\TestCase;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionInterface;
use WebHemi\DependencyInjection\ServiceAdapter\Symfony\ServiceAdapter as DependencyInjectionAdapter;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\MiddlewarePipeline\ServiceInterface as PipelineInterface;
use WebHemi\MiddlewarePipeline\ServiceAdapter\Base\ServiceAdapter as PipelineManager;
use WebHemi\Application\ServiceInterface as ApplicationInterface;
use WebHemi\Application\ServiceAdapter\Base\ServiceAdapter as Application;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use WebHemiTest\TestService\EmptyEnvironmentManager;
use WebHemiTest\TestService\TestMiddleware;
/**
* Class BaseApplicationTest.
*/
class BaseApplicationTest extends TestCase
{
/** @var array */
protected $config;
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*/
public function tearDown()
{
parent::tearDown();
TestMiddleware::$counter = 0;
TestMiddleware::$trace = [];
}
/**
* Tests constructor.
*/
public function testConstructor()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$this->assertInstanceOf(ApplicationInterface::class, $app);
}
/**
* Test run with no error.
*/
public function testRun()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$environmentManager->setSelectedTheme('test_theme');
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerServiceInstance(DependencyInjectionInterface::class, $diAdapter)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$app->run();
$expectedPipelineTrace = [
'pipe2',
'pipe3',
'pipe1',
'pipe4',
'final'
];
$this->assertSame(count($expectedPipelineTrace), TestMiddleware::$counter);
$this->assertArraysAreSimilar($expectedPipelineTrace, TestMiddleware::$trace);
$this->assertSame(200, TestMiddleware::$responseStatus);
//
// $expectedBody = [
// 'message' => 'Hello World!',
// 'template_resource_path' => '/resources/vendor_themes/test_theme/static'
// ];
// $actualBody = json_decode(TestMiddleware::$responseBody, true);
// $this->assertArraysAreSimilar($expectedBody, $actualBody);
}
/**
* Test run with error.
*/
public function testRunError()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/error/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files,
[]
);
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$app->run();
$expectedPipelineTrace = [
'pipe2',
'pipe3',
'pipe1',
'final'
];
$this->assertSame(count($expectedPipelineTrace), TestMiddleware::$counter);
$this->assertArraysAreSimilar($expectedPipelineTrace, TestMiddleware::$trace);
$this->assertSame(500, TestMiddleware::$responseStatus);
$this->assertEmpty(TestMiddleware::$responseBody);
}
/**
* Test run with 403 forbidden error.
*/
public function testRunForbiddenError()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/restricted/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$app->run();
$expectedPipelineTrace = [
'pipe2',
'pipe3',
'pipe1',
'final'
];
$this->assertSame(count($expectedPipelineTrace), TestMiddleware::$counter);
$this->assertArraysAreSimilar($expectedPipelineTrace, TestMiddleware::$trace);
$this->assertSame(403, TestMiddleware::$responseStatus);
$this->assertEmpty(TestMiddleware::$responseBody);
}
/**
* Test run with error 2.
*/
public function testRunForNonExistsPage()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/page-not-exists/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$app->run();
$expectedPipelineTrace = [
'pipe2',
'final'
];
$this->assertSame(count($expectedPipelineTrace), TestMiddleware::$counter);
$this->assertArraysAreSimilar($expectedPipelineTrace, TestMiddleware::$trace);
$this->assertSame(404, TestMiddleware::$responseStatus);
$this->assertEmpty(TestMiddleware::$responseBody);
}
/**
* Test run with bad method request.
*/
public function testRunForBadMethod()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/login',
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$app->run();
$expectedPipelineTrace = [
'pipe2',
'final'
];
$this->assertSame(count($expectedPipelineTrace), TestMiddleware::$counter);
$this->assertArraysAreSimilar($expectedPipelineTrace, TestMiddleware::$trace);
$this->assertSame(405, TestMiddleware::$responseStatus);
$this->assertEmpty(TestMiddleware::$responseBody);
}
/**
* Data provider for the tests.
*
* @return array
*/
public function dataProvider()
{
return [
['Some headerName','Some-HeaderName'],
['some header-name','Some-Header-Name'],
['some-header-Name','Some-Header-Name'],
['SomeHeaderName','SomeHeaderName'],
['Some_Header_Name','Some_Header_Name'],
];
}
/**
* Test header filter.
*
* @param string $inputData
* @param string $expectedResult
*
* @dataProvider dataProvider
*/
public function testFilterHeaderName($inputData, $expectedResult)
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/page-not-exists/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$pipelineManager = new PipelineManager($config);
$diAdapter = new DependencyInjectionAdapter($config);
$diAdapter->registerServiceInstance(ConfigInterface::class, $config)
->registerServiceInstance(EnvironmentInterface::class, $environmentManager)
->registerServiceInstance(PipelineInterface::class, $pipelineManager)
->registerModuleServices('Global');
$app = new Application($diAdapter);
$actualResult = $this->invokePrivateMethod($app, 'filterHeaderName', [$inputData]);
$this->assertSame($expectedResult, $actualResult);
}
}
<file_sep>/src/WebHemi/Renderer/Helper/FileExistsHelper.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Helper;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Renderer\HelperInterface;
/**
* Class FileExistsHelper.
*/
class FileExistsHelper implements HelperInterface
{
/**
* @var string
*/
private $applicationRoot;
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'fileExists';
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{% if fileExists("fileName") %}';
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Checks if the given filepath exists under the application root.';
}
/**
* Gets helper options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* DefinedHelper constructor.
*
* @param EnvironmentInterface $environmentManager
*/
public function __construct(EnvironmentInterface $environmentManager)
{
$this->applicationRoot = $environmentManager->getApplicationRoot();
}
/**
* A renderer helper should be called with its name.
*
* @return bool
*/
public function __invoke() : bool
{
$fileName = trim(func_get_args()[0], '/');
return file_exists($this->applicationRoot.'/'.$fileName);
}
}
<file_sep>/tests/WebHemiTest/Application/ProgressTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Application;
use PHPUnit\Framework\TestCase;
use WebHemi\Application\Progress;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use WebHemiTest\TestService\EmptyEnvironmentManager;
use WebHemiTest\TestService\EmptySessionManager;
/**
* Class ProgressTest
*/
class ProgressTest extends TestCase
{
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
/** @var EmptyEnvironmentManager */
protected $environmentManager;
/** @var EmptySessionManager */
protected $sessionManager;
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$configData = require __DIR__ . '/../test_config.php';
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$config = new Config($configData);
$this->environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$this->sessionManager = new EmptySessionManager($config);
$this->sessionManager->start('unittest');
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*/
public function tearDown()
{
parent::tearDown();
$path = $this->environmentManager->getApplicationRoot().'/data/progress/*.json';
$files = glob($path);
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
/**
* Tests constructor.
*/
public function testConstructor()
{
$expectedSessionId = $this->sessionManager->getSessionId();
$progress = new Progress($this->environmentManager, $this->sessionManager);
$this->assertAttributeInstanceOf(EnvironmentInterface::class, 'environmentManager', $progress);
$this->assertAttributeEquals($expectedSessionId, 'sessionId', $progress);
}
/*
* Tests start() method with no specific name given.
*/
public function testStartWithNoCallerName()
{
$progress = new Progress($this->environmentManager, $this->sessionManager);
$progress->start(3);
$expectedProgressId = md5($this->sessionManager->getSessionId()).'_ProgressTest';
$expectedProgressFile = $this->environmentManager->getApplicationRoot()
.'/data/progress/'.$expectedProgressId.'.json';
$this->assertAttributeEquals('ProgressTest', 'callerName', $progress);
$this->assertAttributeEquals(3, 'totalSteps', $progress);
$this->assertAttributeEquals(1, 'currentStep', $progress);
$this->assertAttributeEquals($expectedProgressId, 'progressId', $progress);
$this->assertEquals($expectedProgressId, $progress->getProgressId());
$this->assertTrue(file_exists($expectedProgressFile));
}
/*
* Tests start() method with specific name given.
*/
public function testStartWithCallerName()
{
$progress = new Progress($this->environmentManager, $this->sessionManager);
$progress->start(3, 'ProgressTestInDaHouse');
$expectedProgressId = md5($this->sessionManager->getSessionId()).'_ProgressTestInDaHouse';
$expectedProgressFile = $this->environmentManager->getApplicationRoot()
.'/data/progress/'.$expectedProgressId.'.json';
$this->assertAttributeEquals('ProgressTestInDaHouse', 'callerName', $progress);
$this->assertAttributeEquals(3, 'totalSteps', $progress);
$this->assertAttributeEquals(1, 'currentStep', $progress);
$this->assertAttributeEquals($expectedProgressId, 'progressId', $progress);
$this->assertEquals($expectedProgressId, $progress->getProgressId());
$this->assertTrue(file_exists($expectedProgressFile));
}
/**
* Tests the next() method.
*/
public function testNext()
{
$progress = new Progress($this->environmentManager, $this->sessionManager);
$progress->start(3);
$this->assertAttributeEquals(3, 'totalSteps', $progress);
$this->assertAttributeEquals(1, 'currentStep', $progress);
$progress->next();
$this->assertAttributeEquals(2, 'currentStep', $progress);
$progress->next();
$this->assertAttributeEquals(3, 'currentStep', $progress);
}
}
<file_sep>/src/WebHemi/Middleware/Action/Admin/ControlPanel/Groups/ListAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Admin\ControlPanel\Groups;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Data\Entity\UserGroupEntity;
use WebHemi\Data\Storage\UserStorage;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class ListAction
*/
class ListAction extends AbstractMiddlewareAction
{
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* @var EnvironmentInterface
*/
protected $environmentManager;
/**
* @var UserStorage
*/
protected $userStorage;
/**
* GroupManagementAction constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param UserStorage $userStorage
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
UserStorage $userStorage
) {
$this->configuration = $configuration;
$this->environmentManager = $environmentManager;
$this->userStorage = $userStorage;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-control-panel-groups-list';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$data = $this->getUserGroupList();
return [
'data' => $data
];
}
/**
* Gets the whole user group record list.
*
* @return array
*/
protected function getUserGroupList() : array
{
$dataList = [];
/**
* @var array $entityList
*/
$entityList = $this->userStorage->getUserGroupList();
/**
* @var UserGroupEntity $userGroupEntity
*/
foreach ($entityList as $userGroupEntity) {
$dataList[] = [
'id' => $userGroupEntity->getUserGroupId(),
'name' => $userGroupEntity->getName(),
'title' => $userGroupEntity->getTitle(),
'description' => $userGroupEntity->getDescription()
];
}
return $dataList;
}
}
<file_sep>/tests/WebHemiTest/TestExtension/AssertArraysAreSimilarTrait.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestExtension;
/**
* Trait AssertArraysAreSimilarTrait.
*/
trait AssertArraysAreSimilarTrait
{
/**
* {@inheritDoc}
*
* @param $expected
* @param $actual
* @param string $message
* @return mixed
*/
abstract public static function assertSame($expected, $actual, $message = '');
/**
* Compares two arrays.
*
* @param array $arrayOne
* @param array $arrayTwo
* @param string $message
*
* @return bool
*/
protected function assertArraysAreSimilar(array $arrayOne, array $arrayTwo, string $message = '')
{
$result = strcmp(serialize($arrayOne), serialize($arrayTwo));
$this->assertSame($result, 0, $message);
}
}
<file_sep>/bin/setup.sh
#!/bin/sh
dir="$(dirname "$0")"
parentdir="$(dirname "$dir")"
publicIp=$(curl ipinfo.io/ip)
cd $dir
if [ -n "$(type -t mysql)" ] ; then
echo "Initialize database"
mysql --host=$publicIp -u root -prootpass webhemi < ../build/webhemi_schema.sql
if [ -n "$(type -t mysqldump)" ] && [ -n "$(type -t sqlite3)" ]; then
echo "Create SQLite copy for the unit test"
file="../build/webhemi_schema.sqlite3"
if [ -f $file ] ; then
rm $file
fi
./mysql2sqlite.sh --host=$publicIp -u root -prootpass webhemi | sqlite3 $file
fi
fi
if [ -n "$(type -t php)" ] ; then
cd $parentdir
echo "Install composer"
curl -L -o /usr/bin/composer https://getcomposer.org/composer.phar
chmod +x /usr/bin/composer
echo "Install composer packages"
if [ -f "composer.lock" ] ; then
rm composer.lock
fi
composer install --prefer-source --no-interaction
fi
<file_sep>/tests/WebHemiTest/TestService/EmptyLogger.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemiTest\TestService;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Logger\ServiceInterface;
/**
* Class EmptyLogger.
*/
class EmptyLogger implements ServiceInterface
{
/**
* EmptyLogger constructor.
*
* @param ConfigurationInterface $configuration
* @param string $section
*/
public function __construct(ConfigurationInterface $configuration, string $section)
{
unset($configuration, $section);
}
/**
* It will do nothing just avoid the `Scalar type declaration` fatal error for the void return type.
*
* @param mixed $level
* @param string $message
* @param array $context
* @return void
*/
public function log($level, string $message, array $context = []) : void
{
unset($level, $message, $context);
return;
}
}
<file_sep>/tests/WebHemiTest/GeneralLibTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest;
use Throwable;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use WebHemi\GeneralLib;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
/**
* Class StringLibTest
*/
class GeneralLibTest extends TestCase
{
use AssertTrait;
/**
* Tests the mergeArrayOverwrite method.
*/
public function testMerge()
{
try {
$paramA = [];
GeneralLib::mergeArrayOverwrite($paramA);
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1000, $exception->getCode());
}
try {
$paramA = [];
$paramB = 1;
GeneralLib::mergeArrayOverwrite($paramA, $paramB);
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1001, $exception->getCode());
}
$paramA = [
'level1A' => 'value1',
'level1B' => [
'old' => 'not new',
'test' => 'value'
]
];
$paramB = [
'level1B' => [
'test' => false,
'new' => 'not old'
]
];
$expectedResult = [
'level1A' => 'value1',
'level1B' => [
'old' => 'not new',
'test' => false,
'new' => 'not old'
]
];
$actualResult = GeneralLib::mergeArrayOverwrite($paramA, $paramB);
$this->assertArraysAreSimilar($expectedResult, $actualResult);
}
}
<file_sep>/README.md
# WebHemi #
[](https://github.com/Gixx/WebHemi)
[](https://github.com/Gixx/WebHemi/releases/latest)
[](https://php.net/)
[](mailto:<EMAIL>)
[](https://packagist.org/packages/gixx/web-hemi)
[](LICENSE)
[](https://scrutinizer-ci.com/g/Gixx/WebHemi/build-status/master)
[](https://scrutinizer-ci.com/g/Gixx/WebHemi/?branch=master)
[](https://scrutinizer-ci.com/g/Gixx/WebHemi/?branch=master)
## Introduction ##
After many years of [endless development of a big, robust, super-universal blog engine](https://github.com/Gixx/WebHemi-legacy-v2)
which was suppose to build on a well known framework, I decided to re-think my goals and the way I want to reach them.
With the very helpful guidance of the [owner](https://github.com/janoszen) of the [refaktormagazin/blog](https://github.com/refaktormagazin/blog)
repository, now I try to create a small, fast and 'only as much as necessary', clean-code blog engine.
**BE AWARE! THIS IS ONLY AN EXPERIMENTAL PROJECT WITH LIMITED TIME, RESOURCE AND SUPPORT CAPABILITIES.**
Use it at your own will.
## BEHIND THE SCENES ##
The WebHemi is a simple blog engine that tries to completely apply the S.O.L.I.D. principles, uses the PSR-7 HTTP Messages Interfaces and the Middleware concept.
Figure 1: The basic execution flow of the application.

Figure 2: The queue of the Middleware Pipeline

## FAQ ##
**Q**: Why don't you use Wordpress?
**A**: I tried. It didn't fit to me.
**Q**: Why don't you use a Framework?
**A**: I tried. It didn't fit to me.
**Q**: Why don't you wear business suit?
**A**: I tried. It didn't fit to me.
**Q**: Who asks these questions so frequently?
**A**: Nobody. I just try to avoid them to be asked.
## License ##
Check the [License](LICENSE) for details.
## Change Log ##
Check [Change log](CHANGELOG.md)
<file_sep>/tests/WebHemiTest/Data/Entity/FilesystemDirectoryEntityTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use WebHemi\Data\Entity\FilesystemDirectoryEntity;
use WebHemi\DateTime;
/**
* Class FilesystemDirectoryEntityTest
*/
class FilesystemDirectoryEntityTest extends AbstractEntityTestCase
{
/** @var array */
protected $testData = [
'id_filesystem_directory' => 1,
'description' => 'test description',
'directory_type' => 'test dir type',
'proxy' => 'test proxy',
'is_autoindex' => 1,
'date_created' => '2016-04-26 23:21:19',
'date_modified' => '2016-04-26 23:21:19',
];
/** @var array */
protected $expectedGetters = [
'getFilesystemDirectoryId' => 1,
'getDescription' => 'test description',
'getDirectoryType' => 'test dir type',
'getProxy' => 'test proxy',
'getIsAutoIndex' => true,
'getDateCreated' => null,
'getDateModified' => null,
];
/** @var array */
protected $expectedSetters = [
'setFilesystemDirectoryId' => 1,
'setDescription' => 'test description',
'setDirectoryType' => 'test dir type',
'setProxy' => 'test proxy',
'setIsAutoIndex' => true,
'setDateCreated' => null,
'setDateModified' => null,
];
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$dateTime = new DateTime('2016-04-26 23:21:19');
$this->expectedGetters['getDateCreated'] = $dateTime;
$this->expectedGetters['getDateModified'] = $dateTime;
$this->expectedSetters['setDateCreated'] = $dateTime;
$this->expectedSetters['setDateModified'] = $dateTime;
$this->entity = new FilesystemDirectoryEntity();
}
}
<file_sep>/src/WebHemi/Middleware/Action/Admin/ControlPanel/Groups/ViewAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Admin\ControlPanel\Groups;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Data\Entity\UserGroupEntity;
use WebHemi\Data\Storage\UserStorage;
use WebHemi\DateTime;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class ViewAction
*/
class ViewAction extends AbstractMiddlewareAction
{
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* @var EnvironmentInterface
*/
protected $environmentManager;
/**
* @var UserStorage
*/
protected $userStorage;
/**
* GroupManagementAction constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param UserStorage $userStorage
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
UserStorage $userStorage
) {
$this->configuration = $configuration;
$this->environmentManager = $environmentManager;
$this->userStorage = $userStorage;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-control-panel-groups-view';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$data = null;
$params = $this->getRoutingParameters();
if (isset($params['userGroupId'])) {
$data = $this->getUserGroupDetails((int) $params['userGroupId']);
}
return [
'data' => $data,
];
}
/**
* Gets user group details.
*
* @param int $userGroupId
* @return array
* @throws RuntimeException
*/
protected function getUserGroupDetails(int $userGroupId) : array
{
$userGroupEntity = $this->userStorage->getUserGroupById($userGroupId);
if (!$userGroupEntity instanceof UserGroupEntity) {
throw new RuntimeException(
sprintf(
'The requested user group entity with the given ID not found: %s',
(string) $userGroupId
),
404
);
}
$dateCreated = $userGroupEntity->getDateCreated();
$data = [
'readonly' => $userGroupEntity->getIsReadOnly(),
'group' => [
'Id' => $userGroupEntity->getUserGroupId(),
'Name' => $userGroupEntity->getName(),
'Title' => $userGroupEntity->getTitle(),
'Description' => $userGroupEntity->getDescription(),
'Is read-only?' => $userGroupEntity->getIsReadOnly() ? 'Yes' : 'No',
'Date created' => $dateCreated instanceof DateTime ?
$dateCreated->format('Y-m-d H:i:s')
: 'unknown',
],
];
$dateModified = $userGroupEntity->getDateModified();
if (!$userGroupEntity->getIsReadOnly() && $dateModified instanceof DateTime) {
$data['group']['Date modified'] = $dateModified->format('Y-m-d H:i:s');
}
return $data;
}
}
<file_sep>/src/WebHemi/Middleware/Action/Admin/Applications/IndexAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Admin\Applications;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Data\Storage\ApplicationStorage;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class IndexAction.
*/
class IndexAction extends AbstractMiddlewareAction
{
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var ApplicationStorage
*/
private $applicationStorage;
/**
* IndexAction constructor.
*
* @param ConfigurationInterface $configuration
* @param AuthInterface $authAdapter
* @param EnvironmentInterface $environmentManager
* @param ApplicationStorage $applicationStorage
*/
public function __construct(
ConfigurationInterface $configuration,
AuthInterface $authAdapter,
EnvironmentInterface $environmentManager,
ApplicationStorage $applicationStorage
) {
$this->configuration = $configuration;
$this->authAdapter = $authAdapter;
$this->environmentManager = $environmentManager;
$this->applicationStorage = $applicationStorage;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-applications-list';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$applications = $this->applicationStorage->getApplicationList();
return [
'applications' => $applications,
];
}
}
<file_sep>/src/WebHemi/DependencyInjection/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\DependencyInjection\ServiceAdapter\Base;
use ReflectionClass;
use ReflectionException;
use InvalidArgumentException;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\DependencyInjection\ServiceInterface;
use WebHemi\DependencyInjection\ServiceAdapter\AbstractAdapter;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter extends AbstractAdapter
{
/**
* @var array
*/
private $container = [];
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
parent::__construct($configuration);
}
/**
* Returns true if the given service is registered.
*
* @param string $identifier
* @return bool
*/
public function has(string $identifier) : bool
{
return isset($this->container[$identifier])
|| isset($this->serviceLibrary[$identifier])
|| class_exists($identifier);
}
/**
* Gets a service.
*
* @param string $identifier
* @throws RuntimeException
* @throws ReflectionException
* @return object
*/
public function get(string $identifier)
{
// Not registered but valid class name, so register it
if (!isset($this->serviceLibrary[$identifier]) && class_exists($identifier)) {
$this->registerService($identifier);
}
// The service is registered in the library but not in the container, so register it into the container too.
if (!isset($this->container[$identifier])) {
$this->registerServiceToContainer($identifier);
}
$service = $this->serviceLibrary[$identifier][self::SERVICE_SHARE]
? $this->container[$identifier]
: clone $this->container[$identifier];
return $service;
}
/**
* Registers the service into the container AKA create the instance.
*
* @param string $identifier
* @throws ReflectionException
* @return ServiceAdapter
*/
private function registerServiceToContainer(string $identifier) : ServiceAdapter
{
// At this point the service must be in the library
if (!isset($this->serviceLibrary[$identifier])) {
throw new InvalidArgumentException(
sprintf('Invalid service name: %s, service is not in the library.', $identifier),
1000
);
}
// Check arguments.
$argumentList = $this
->setArgumentListReferences($this->serviceLibrary[$identifier][self::SERVICE_ARGUMENTS]);
// Create new instance.
$className = $this->serviceLibrary[$identifier][self::SERVICE_CLASS];
$reflectionClass = new ReflectionClass($className);
$serviceInstance = $reflectionClass->newInstanceArgs($argumentList);
// Perform post init method calls.
foreach ($this->serviceLibrary[$identifier][self::SERVICE_METHOD_CALL] as $methodCallList) {
$method = $methodCallList[0];
$argumentList = $this->setArgumentListReferences($methodCallList[1] ?? []);
call_user_func_array([$serviceInstance, $method], $argumentList);
}
// Register sevice.
$this->container[$identifier] = $serviceInstance;
// Mark as initialized.
$this->serviceLibrary[$identifier][self::SERVICE_INITIALIZED] = true;
return $this;
}
/**
* Tries to identify referce services in the argument list.
*
* @param array $argumentList
* @throws ReflectionException
* @return array
*/
private function setArgumentListReferences(array $argumentList) : array
{
foreach ($argumentList as $key => &$value) {
// Associative array keys marks literal values
if (!is_numeric($key)) {
continue;
}
$value = $this->get($value);
}
return $argumentList;
}
/**
* Register the service object instance.
*
* @param string $identifier
* @param object $serviceInstance
* @return ServiceInterface
*/
public function registerServiceInstance(string $identifier, $serviceInstance) : ServiceInterface
{
// Check if the service is not initialized yet.
if (!$this->serviceIsInitialized($identifier)) {
$instanceType = gettype($serviceInstance);
// Register synthetic services
if ('object' !== $instanceType) {
throw new InvalidArgumentException(
sprintf('The second parameter must be an object instance, %s given.', $instanceType),
1001
);
}
// Register sevice.
$this->container[$identifier] = $serviceInstance;
// Overwrite any previous settings.
$this->serviceLibrary[$identifier] = [
self::SERVICE_INITIALIZED => true,
self::SERVICE_ARGUMENTS => [],
self::SERVICE_METHOD_CALL => [],
self::SERVICE_SHARE => true,
self::SERVICE_CLASS => get_class($serviceInstance),
];
}
return $this;
}
}
<file_sep>/src/WebHemi/Acl/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Acl;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\UserEntity;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* Checks if a User can access to a Resource in an Application
*
* @param UserEntity $userEntity
* @param ResourceEntity|null $resourceEntity
* @param ApplicationEntity|null $applicationEntity
* @return bool
*/
public function isAllowed(
UserEntity $userEntity,
? ResourceEntity $resourceEntity = null,
? ApplicationEntity $applicationEntity = null
) : bool;
}
<file_sep>/src/WebHemi/Data/Query/QueryInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Query;
use InvalidArgumentException;
use WebHemi\Data\Driver\DriverInterface;
/**
* Interface QueryInterface
*/
interface QueryInterface
{
const MAX_ROW_LIMIT = 1500;
/**
* QueryInterface constructor.
*
* @param DriverInterface $driverAdapter
*/
public function __construct(DriverInterface $driverAdapter);
/**
* Returns the Data Driver instance.
*
* @return DriverInterface
*/
public function getDriver() : DriverInterface;
/**
* Fetches data buy executing a query identified by ID.
*
* @param string $query
* @param array $parameters
* @throws InvalidArgumentException
* @return array
*/
public function fetchData(string $query, array $parameters = []) : array;
}
<file_sep>/src/WebHemi/Auth/CredentialInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth;
/**
* Interface CredentialInterface
*/
interface CredentialInterface
{
/**
* Set a credential.
*
* @param string $key
* @param string $value
* @return CredentialInterface
*/
public function setCredential(string $key, string $value) : CredentialInterface;
/**
* Returns the credentials in a key => value array.
*
* @return array
*/
public function getCredentials() : array;
}
<file_sep>/src/WebHemi/DependencyInjection/ServiceAdapter/Symfony/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\DependencyInjection\ServiceAdapter\Symfony;
use Exception;
use Throwable;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\DependencyInjection\ServiceInterface;
use WebHemi\DependencyInjection\ServiceAdapter\AbstractAdapter;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter extends AbstractAdapter
{
/**
* @var ContainerBuilder
*/
private $container;
/**
* @var int
*/
private static $parameterIndex = 0;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
parent::__construct($configuration);
$this->container = new ContainerBuilder();
}
/**
* Returns true if the given service is registered.
*
* @param string $identifier
* @return bool
*/
public function has(string $identifier) : bool
{
return $this->container->has($identifier)
|| isset($this->serviceLibrary[$identifier])
|| class_exists($identifier);
}
/**
* Gets a service.
*
* @param null|string $identifier
* @throws RuntimeException
* @return null|object
*/
public function get(? string $identifier)
{
if (is_null($identifier)) {
return null;
}
// Not registered but valid class name, so register it
if (!isset($this->serviceLibrary[$identifier]) && class_exists($identifier)) {
$this->registerService($identifier);
}
// The service is registered in the library but not in the container, so register it into the container too.
if (!$this->container->has($identifier)) {
$this->registerServiceToContainer($identifier);
}
try {
$service = $this->container->get($identifier);
$this->serviceLibrary[$identifier][self::SERVICE_INITIALIZED] = true;
} catch (Throwable $exception) {
throw new RuntimeException(
sprintf('There was an issue during creating the object: %s', $exception->getMessage()),
1000,
$exception
);
}
return $service;
}
/**
* Registers the service into the container.
*
* @param string $identifier
* @return ServiceAdapter
*/
private function registerServiceToContainer(string $identifier) : ServiceAdapter
{
// At this point the service must be in the library
if (!isset($this->serviceLibrary[$identifier])) {
throw new InvalidArgumentException(
sprintf('Invalid service name: %s', $identifier),
1000
);
}
// Create the definition.
$definition = new Definition($this->serviceLibrary[$identifier][self::SERVICE_CLASS]);
$definition->setShared($this->serviceLibrary[$identifier][self::SERVICE_SHARE]);
// Register the service in the container.
$service = $this->container->setDefinition($identifier, $definition);
// Add arguments.
$argumentList = $this->setArgumentListReferences($this->serviceLibrary[$identifier][self::SERVICE_ARGUMENTS]);
foreach ($argumentList as $parameter) {
// Create a normalized name for the argument.
$serviceClass = $this->serviceLibrary[$identifier][self::SERVICE_CLASS];
$normalizedName = $this->getNormalizedName($serviceClass, $parameter);
$this->container->setParameter($normalizedName, $parameter);
$service->addArgument('%'.$normalizedName.'%');
}
// Register method callings.
foreach ($this->serviceLibrary[$identifier][self::SERVICE_METHOD_CALL] as $methodCallList) {
$method = $methodCallList[0];
$argumentList = $this->setArgumentListReferences($methodCallList[1] ?? []);
$service->addMethodCall($method, $argumentList);
}
return $this;
}
/**
* Tries to identify referce services in the argument list.
*
* @param array $argumentList
* @return array
*/
private function setArgumentListReferences(array $argumentList) : array
{
foreach ($argumentList as $key => &$value) {
// Associative array keys marks literal values
if (!is_numeric($key)) {
continue;
}
$this->get($value);
$value = new Reference($value);
}
return $argumentList;
}
/**
* Creates a safe normalized name.
*
* @param string $className
* @param mixed $parameter
* @return string
*/
private function getNormalizedName(string $className, $parameter) : string
{
$parameterName = !is_scalar($parameter) ? self::$parameterIndex++ : $parameter;
$className = 'C_'.preg_replace('/[^a-z0-9]/', '', strtolower($className));
$parameterName = 'A_'.preg_replace('/[^a-z0-9]/', '', strtolower((string) $parameterName));
return $className.'.'.$parameterName;
}
/**
* Register the service object instance.
*
* @param string $identifier
* @param object $serviceInstance
* @return ServiceInterface
*/
public function registerServiceInstance(string $identifier, $serviceInstance) : ServiceInterface
{
// Check if the service is not initialized yet.
if (!$this->serviceIsInitialized($identifier)) {
$instanceType = gettype($serviceInstance);
// Register synthetic services
if ('object' !== $instanceType) {
throw new InvalidArgumentException(
sprintf('The second parameter must be an object instance, %s given.', $instanceType),
1001
);
}
$this->container->register($identifier)
->setShared(true)
->setSynthetic(true);
$this->container->set($identifier, $serviceInstance);
// Overwrite any previous settings.
$this->serviceLibrary[$identifier] = [
self::SERVICE_INITIALIZED => true,
self::SERVICE_ARGUMENTS => [],
self::SERVICE_METHOD_CALL => [],
self::SERVICE_SHARE => true,
self::SERVICE_CLASS => get_class($serviceInstance),
];
}
return $this;
}
}
<file_sep>/src/WebHemi/Ftp/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Ftp\ServiceAdapter\Base;
use RuntimeException;
use WebHemi\Ftp\ServiceInterface;
use WebHemi\Ftp\ServiceAdapter\AbstractServiceAdapter;
/**
* Class ServiceAdapter.
*
* @codeCoverageIgnore - don't test third party library.
*/
class ServiceAdapter extends AbstractServiceAdapter
{
/**
* @var null|resource
*/
private $connectionId = null;
/**
* Disconnected by garbage collection.
*/
public function __destruct()
{
$this->disconnect();
}
/**
* Connect and login to remote host.
*
* @return ServiceInterface
*/
public function connect() : ServiceInterface
{
if ($this->getOption('secure', true)) {
$this->connectionId = @ftp_ssl_connect($this->getOption('host'));
} else {
$this->connectionId = @ftp_connect($this->getOption('host'));
}
if (!$this->connectionId) {
throw new RuntimeException(
sprintf('Cannot establish connection to server: %s', $this->getOption('host')),
1000
);
}
$loginResult = @ftp_login($this->connectionId, $this->getOption('username'), $this->getOption('password'));
if (!$loginResult) {
throw new RuntimeException('Cannot connect to remote host: invalid credentials', 1001);
}
return $this;
}
/**
* Disconnect from remote host.
*
* @return ServiceInterface
*/
public function disconnect() : ServiceInterface
{
if (!empty($this->connectionId)) {
ftp_close($this->connectionId);
$this->connectionId = null;
}
}
/**
* Toggles connection security level.
*
* @param bool $state
* @return ServiceInterface
*/
public function setSecureConnection(bool $state) : ServiceInterface
{
$this->setOption('secure', $state);
if (!empty($this->connectionId)) {
ftp_close($this->connectionId);
$this->connectionId = null;
$this->connect();
}
return $this;
}
/**
* Toggles connection passive mode.
*
* @param bool $state
* @return ServiceInterface
*/
public function setPassiveMode(bool $state) : ServiceInterface
{
ftp_pasv($this->connectionId, $state);
return $this;
}
/**
* Sets remote path.
*
* @param string $path
* @return ServiceInterface
*/
public function setRemotePath(string $path) : ServiceInterface
{
if (trim($this->getRemotePath(), '/') == trim($path, '/')) {
return $this;
}
if (strpos($path, '/') !== 0) {
$path = $this->getRemotePath().$path;
}
$chdirResult = @ftp_chdir($this->connectionId, $path);
if (!$chdirResult) {
throw new RuntimeException(sprintf('No such directory on remote host: %s', $path), 1002);
}
return $this;
}
/**
* Gets remote path.
*
* @return string
*/
public function getRemotePath() : string
{
return ftp_pwd($this->connectionId).'/';
}
/**
* Lists remote path.
*
* @param null|string $path
* @param bool|null $changeToDirectory
* @return array
*/
public function getRemoteFileList(? string $path, ? bool $changeToDirectory) : array
{
$fileList = [];
if (!empty($path) && $changeToDirectory) {
$this->setRemotePath($path);
$path = '.';
}
$result = @ftp_rawlist($this->connectionId, $path);
if (!is_array($result)) {
throw new RuntimeException('Cannot retrieve file list', 1006);
}
foreach ($result as $fileRawData) {
$fileData = [];
preg_match(
'/^(?P<rights>(?P<type>(-|d))[^\s]+)\s+(?P<symlinks>\d+)\s+(?P<user>[^\s]+)\s+(?P<group>[^\s]+)\s+'
.'(?P<size>\d+)\s+(?P<date>(?P<month>[^\s]+)\s+(?P<day>[^\s]+)\s+'
.'(?P<time>[^\s]+))\s+(?P<filename>.+)$/',
$fileRawData,
$fileData
);
$fileInfo = pathinfo($fileData['filename']);
$fileList[] = [
'type' => $this->getFileType($fileData['type']),
'chmod' => $this->getOctalChmod($fileData['rights']),
'symlinks' => $fileData['symlinks'],
'user' => $fileData['user'],
'group' => $fileData['group'],
'size' => $fileData['size'],
'date' => $this->getFileDate($fileData),
'basename' => $fileInfo['basename'],
'filename' => $fileInfo['filename'],
'extension' => $fileInfo['extension'] ?? '',
];
}
return $fileList;
}
/**
* @param string $fileData
* @return string
*/
private function getFileType(string $fileData) : string
{
switch ($fileData) {
case 'd':
$fileType = 'directory';
break;
case 'l':
$fileType = 'symlink';
break;
default:
$fileType = 'file';
}
return $fileType;
}
/**
* @param array $fileData
* @return string
*/
private function getFileDate(array $fileData) : string
{
if (strpos($fileData['time'], ':') !== false) {
$date = $fileData['month'].' '.$fileData['day'].' '.date('Y').' '.$fileData['time'];
} else {
$date = $fileData['date'].' 12:00:00';
}
$time = strtotime($date);
return date('Y-m-d H:i:s', $time);
}
/**
* Uploads file to remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $sourceFileName
* @param string $destinationFileName
* @param int $fileMode
* @return ServiceInterface
*/
public function upload(
string $sourceFileName,
string $destinationFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface {
$this->checkLocalFile($sourceFileName);
$this->checkRemoteFile($destinationFileName);
if (!file_exists($this->localPath.'/'.$sourceFileName)) {
throw new RuntimeException(sprintf('File not found: %s', $this->localPath.'/'.$sourceFileName), 1007);
}
$uploadResult = @ftp_put(
$this->connectionId,
$destinationFileName,
$this->localPath.'/'.$sourceFileName,
$fileMode
);
if (!$uploadResult) {
throw new RuntimeException(sprintf('There was a problem while uploading file: %s', $sourceFileName), 1008);
}
return $this;
}
/**
* Downloads file from remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $remoteFileName
* @param string $localFileName
* @param int $fileMode
* @return ServiceInterface
*/
public function download(
string $remoteFileName,
string&$localFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface {
$this->checkRemoteFile($remoteFileName);
$this->checkLocalFile($localFileName, true);
$downloadResult = @ftp_get(
$this->connectionId,
$this->localPath.'/'.$localFileName,
$remoteFileName,
$fileMode
);
if (!$downloadResult) {
throw new RuntimeException(
sprintf('There was a problem while downloading file: %s', $remoteFileName),
1010
);
}
return $this;
}
/**
* Check remote file name.
*
* @param string $remoteFileName
*/
protected function checkRemoteFile(string&$remoteFileName) : void
{
$pathInfo = pathinfo($remoteFileName);
if ($pathInfo['dirname'] != '.') {
$this->setRemotePath($pathInfo['dirname']);
$remoteFileName = $pathInfo['basename'];
}
}
/**
* Moves file on remote host.
*
* @param string $currentPath
* @param string $newPath
* @return ServiceInterface
*/
public function moveRemoteFile(string $currentPath, string $newPath) : ServiceInterface
{
$result = @ftp_rename($this->connectionId, $currentPath, $newPath);
if (!$result) {
throw new RuntimeException(
sprintf('Unable to move/rename file from %s to %s', $currentPath, $newPath),
1011
);
}
return $this;
}
/**
* Deletes file on remote host.
*
* @param string $path
* @return ServiceInterface
*/
public function deleteRemoteFile(string $path) : ServiceInterface
{
$result = @ftp_delete($this->connectionId, $path);
if (!$result) {
throw new RuntimeException(sprintf('Unable to delete file on remote host: %s', $path), 1012);
}
return $this;
}
}
<file_sep>/tests/WebHemiTest/Renderer/Helper/FileExistsHelperTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Renderer\Helper;
use PHPUnit\Framework\TestCase;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
use WebHemi\Renderer\Helper\FileExistsHelper;
use WebHemiTest\TestService\EmptyEnvironmentManager;
/**
* Class FileExistsHelperTest.
*/
class FileExistsHelperTest extends TestCase
{
/** @var ConfigInterface */
private $config;
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
/** @var string */
protected $documentRoot;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../../test_config.php';
$this->config = new Config($config);
$this->documentRoot = realpath(__DIR__ . '/../../TestDocumentRoot/');
}
/**
* Tests the helper
*/
public function testHelper()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$environmentManager = new EmptyEnvironmentManager(
$this->config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$environmentManager->setDocumentRoot($this->documentRoot);
$helper = new FileExistsHelper($environmentManager);
$this->assertTrue($helper('/testfile.txt'));
$this->assertFalse($helper('some/non/existing/file.txt'));
}
}
<file_sep>/tests/WebHemiTest/Http/GuzzleHttpAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Http;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ServerRequest;
use WebHemi\Http\ServiceInterface as HttpAdapterInterface;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\ServiceAdapter as GuzzleHttpAdapter;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use WebHemiTest\TestService\EmptyEnvironmentManager;
use PHPUnit\Framework\TestCase;
/**
* Class GuzzleHttpAdapterTest.
*/
class GuzzleHttpAdapterTest extends TestCase
{
/** @var array */
protected $config = [];
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
}
/**
* Tests constructor.
*/
public function testConstructor()
{
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$testObj = new GuzzleHttpAdapter($environmentManager);
$this->assertInstanceOf(HttpAdapterInterface::class, $testObj);
$this->assertInstanceOf(ServerRequest::class, $testObj->getRequest());
$this->assertInstanceOf(Response::class, $testObj->getResponse());
}
/**
* Tests if can determine the right scheme.
*/
public function testGetScheme()
{
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$testObj = new GuzzleHttpAdapter($environmentManager);
$result = $this->invokePrivateMethod($testObj, 'getScheme');
$this->assertEquals('http', $result);
$server = $this->server;
$server['HTTPS'] = 'on';
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$server,
$this->cookie,
$this->files
);
$testObj = new GuzzleHttpAdapter($environmentManager);
$result = $this->invokePrivateMethod($testObj, 'getScheme');
$this->assertEquals('https', $result);
}
/**
* Tests if can determine the right host.
*/
public function testGetHost()
{
$server = $this->server;
$server['HTTP_HOST'] = '';
$server['SERVER_NAME'] = 'unittest.dev:8080';
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$server,
$this->cookie,
$this->files
);
$testObj = new GuzzleHttpAdapter($environmentManager);
$result = $this->invokePrivateMethod($testObj, 'getHost');
$this->assertEquals('unittest.dev', $result);
}
/**
* Tests if can determine the right protocol.
*/
public function testGetProtocol()
{
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$testObj = new GuzzleHttpAdapter($environmentManager);
$result = $this->invokePrivateMethod($testObj, 'getProtocol');
$this->assertEquals('1.1', $result);
$server = $this->server;
$server['SERVER_PROTOCOL'] = 'HTTP/1.0';
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$server,
$this->cookie,
$this->files
);
$testObj = new GuzzleHttpAdapter($environmentManager);
$result = $this->invokePrivateMethod($testObj, 'getProtocol');
$this->assertEquals('1.0', $result);
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemPublishedDocumentList.sql
SELECT
fs.`id_filesystem`,
fsd.`id_filesystem_document`,
fs.`fk_application`,
fs.`fk_category`,
fs.`path`,
fs.`basename`,
REPLACE(CONCAT(fs.`path`,'/',fs.`basename`), '//', '/') AS uri,
fs.`title`,
fs.`description`,
fsd.`fk_author`,
fsd.`content_lead`,
fsd.`content_body`,
fs.`date_published`
FROM
`webhemi_filesystem` AS fs
INNER JOIN `webhemi_filesystem_document` AS fsd ON fs.`fk_filesystem_document` = fsd.`id_filesystem_document`
WHERE
fs.`fk_application` = :idApplication AND
fs.`fk_filesystem_document` IS NOT NULL AND
fs.`is_hidden` = 0 AND
fs.`is_deleted` = 0 AND
fs.`date_published` IS NOT NULL
ORDER BY
:orderBy
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getResourceById.sql
SELECT
r.`id_resource`,
r.`name`,
r.`title`,
r.`description`,
r.`type`,
r.`is_read_only`,
r.`date_created`,
r.`date_modified`
FROM
`webhemi_resource` AS r
WHERE
r.`id_resource` = :idResource
ORDER BY
r.`name`
<file_sep>/src/WebHemi/Middleware/Common/DispatcherMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Common;
use RuntimeException;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Middleware\MiddlewareInterface;
use WebHemi\Middleware\ActionMiddlewareInterface;
/**
* Class DispatcherMiddleware.
*/
class DispatcherMiddleware implements MiddlewareInterface
{
/**
* From the request data renders an output for the response, or sets an error status code.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @throws RuntimeException
* @return void
*/
public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void
{
/**
* @var MiddlewareInterface $actionMiddleware
*/
$actionMiddleware = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_ACTION_MIDDLEWARE);
// If there is a valid action Middleware, then dispatch it.
if ($actionMiddleware instanceof ActionMiddlewareInterface) {
/**
* @var ResponseInterface $response
*/
$actionMiddleware($request, $response);
} else {
throw new RuntimeException(sprintf('The given attribute is not a valid Action Middleware.'), 1000);
}
}
}
<file_sep>/src/WebHemi/Renderer/Helper/IsAllowedHelper.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Helper;
use WebHemi\Acl\ServiceInterface as AclInterface;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\ResourceStorage;
use WebHemi\Data\Storage\ApplicationStorage;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Renderer\HelperInterface;
/**
* Class IsAllowedHelper
*/
class IsAllowedHelper implements HelperInterface
{
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var AclInterface
*/
private $aclAdapter;
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var ResourceStorage
*/
private $resourceStorage;
/**
* @var ApplicationStorage
*/
private $applicationStorage;
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'isAllowed';
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{% if isAllowed("resource_name", ["POST"[, "application_name"]]) %}';
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Checks if the given user has access to the given resource.';
}
/**
* Gets helper options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* IsAllowedHelper constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param AclInterface $aclAdapter
* @param AuthInterface $authAdapter
* @param ResourceStorage $resourceStorage
* @param ApplicationStorage $applicationStorage
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
AclInterface $aclAdapter,
AuthInterface $authAdapter,
ResourceStorage $resourceStorage,
ApplicationStorage $applicationStorage
) {
$this->configuration = $configuration;
$this->environmentManager = $environmentManager;
$this->aclAdapter = $aclAdapter;
$this->authAdapter = $authAdapter;
$this->resourceStorage = $resourceStorage;
$this->applicationStorage = $applicationStorage;
}
/**
* A renderer helper should be called with its name.
*
* @return bool
*/
public function __invoke() : bool
{
/**
* @var UserEntity $userEntity
*/
$userEntity = $this->authAdapter->getIdentity();
// Without user, access should be denied.
if (!$userEntity) {
return false;
}
$arguments = func_get_args();
$applicationName = $arguments[2] ?? $this->environmentManager->getSelectedApplication();
/**
* @var null|ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->applicationStorage->getApplicationByName($applicationName);
// For invalid applications the path will be checked against the current (valid) application
if (!$applicationEntity instanceof ApplicationEntity) {
$applicationName = $this->environmentManager->getSelectedApplication();
/**
* @var null|ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->applicationStorage->getApplicationByName($applicationName);
}
$resourceName = $arguments[0] ?? '';
/**
* @var null|ResourceEntity $resourceEntity
*/
$resourceEntity = $this->resourceStorage->getResourceByName($resourceName);
return $this->aclAdapter->isAllowed($userEntity, $resourceEntity, $applicationEntity);
}
}
<file_sep>/tests/WebHemiTest/Renderer/Filter/TranslateFilterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Renderer\Filter;
use PHPUnit\Framework\TestCase;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Renderer\Filter\TranslateFilter;
use WebHemiTest\TestService\EmptyEnvironmentManager;
use WebHemiTest\TestService\EmptyI18nDriver;
use WebHemiTest\TestService\EmptyI18nService;
/**
* Class TranslateFilterTest.
*/
class TranslateFilterTest extends TestCase
{
/** @var EmptyI18nDriver */
protected $i18nDriver;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$configFile = require __DIR__ . '/../../test_config.php';
$config = new Config($configFile);
$server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$environmentManager = new EmptyEnvironmentManager($config, [], [], $server, [], []);
$i18nService = new EmptyI18nService($config, $environmentManager);
$this->i18nDriver = new EmptyI18nDriver($i18nService);
$this->i18nDriver->dictionary = [
'nothing' => 'something',
'something' => 'anything',
'%d + %d = %d' => '%d plus %d is %d',
'Freedom is %s' => 'Word is %s'
];
}
/**
* @return array
*/
public function dataProvider()
{
return [
['nothing', 'something', null, null, null],
['something', 'anything', null, null, null],
['anything', 'anything', null, null, null],
['%d + %d = %d', '%d plus %d is %d', 1, 2, 3],
['Freedom is %s', 'Word is %s', 'speech', null, null]
];
}
/**
* Test the filter class.
*
* @dataProvider dataProvider
*/
public function testFilter($input, $output, $param1, $param2, $param3)
{
$filter = new TranslateFilter($this->i18nDriver);
if (!empty($param3)) {
$expectedResult = sprintf($output, $param1, $param2, $param3);
$actualResult = $filter($input, $param1, $param2, $param3);
} elseif (!empty($param2)) {
$expectedResult = sprintf($output, $param1, $param2);
$actualResult = $filter($input, $param1, $param2);
} elseif (!empty($param1)) {
$expectedResult = sprintf($output, $param1);
$actualResult = $filter($input, $param1);
} else {
$expectedResult = sprintf($output);
$actualResult = $filter($input);
}
$this->assertSame($expectedResult, $actualResult);
}
}
<file_sep>/src/WebHemi/Data/Storage/AbstractStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use InvalidArgumentException;
use WebHemi\Data\Query\QueryInterface;
use WebHemi\Data\Entity\EntityInterface;
use WebHemi\Data\Entity\EntitySet;
/**
* Class AbstractStorage.
* Suppose to hide Data Service Adapter and Data Entity instances from children Storage objects.
*/
abstract class AbstractStorage implements StorageInterface
{
/**
* @var QueryInterface
*/
private $queryAdapter;
/**
* @var EntitySet
*/
private $entitySetPrototype;
/**
* @var EntityInterface[]
*/
private $entityPrototypes;
/**
* @var bool
*/
protected $initialized = false;
/**
* AbstractStorage constructor.
*
* @param QueryInterface $queryAdapter
* @param EntitySet $entitySetPrototype
* @param EntityInterface[] ...$entityPrototypes
*/
public function __construct(
QueryInterface $queryAdapter,
EntitySet $entitySetPrototype,
EntityInterface ...$entityPrototypes
) {
$this->queryAdapter = $queryAdapter;
$this->entitySetPrototype = $entitySetPrototype;
foreach ($entityPrototypes as $entity) {
$this->entityPrototypes[get_class($entity)] = $entity;
}
}
/**
* @return QueryInterface
*/
public function getQueryAdapter() : QueryInterface
{
return $this->queryAdapter;
}
/**
* Creates a clean instance of the Entity.
*
* @param string $entityClass
* @throws InvalidArgumentException
* @return EntityInterface
*/
public function createEntity(string $entityClass) : EntityInterface
{
if (!isset($this->entityPrototypes[$entityClass])) {
throw new InvalidArgumentException(
sprintf('Entity class reference "%s" is not defined in this class.', $entityClass),
1000
);
}
return clone $this->entityPrototypes[$entityClass];
}
/**
* Get an entity instance with data.
*
* @param string $entityClass
* @param array $data
* @throws InvalidArgumentException
* @return null|EntityInterface
*/
protected function getEntity(string $entityClass, array $data) : ? EntityInterface
{
if (!empty($data)) {
$entity = $this->createEntity($entityClass);
$entity->fromArray($data);
return $entity;
}
return null;
}
/**
* Creates an empty entity set.
*
* @return EntitySet
*/
public function createEntitySet() : EntitySet
{
return clone $this->entitySetPrototype;
}
/**
* Creates and fills and EntitySet
*
* @param string $entityClass
* @param array|null $data
* @throws InvalidArgumentException
* @return EntitySet
*/
protected function getEntitySet(string $entityClass, ? array $data) : EntitySet
{
$entitySet = $this->createEntitySet();
if (is_null($data)) {
$data = [];
}
foreach ($data as $row) {
$entity = $this->getEntity($entityClass, $row);
if (!empty($entity)) {
$entitySet[] = $entity;
}
}
return $entitySet;
}
/**
* Checks and corrects values to stay within the limits.
*
* @param int $limit
* @param int $offset
*/
protected function normalizeLimitAndOffset(int&$limit, int&$offset) : void
{
$limit = min(QueryInterface::MAX_ROW_LIMIT, abs($limit));
$offset = abs($offset);
}
}
<file_sep>/src/WebHemi/Middleware/Action/Website/Directory/ArchiveAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Website\Directory;
use RuntimeException;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity;
use WebHemi\DateTime;
use WebHemi\Middleware\Action\Website\IndexAction;
/**
* Class ArchiveAction.
*/
class ArchiveAction extends IndexAction
{
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'website-post-list';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$blogPosts = [];
$parameters = $this->getRoutingParameters();
$date = $parameters['basename'] ?? null;
if ($parameters['path'] == '/' || empty($date)) {
throw new RuntimeException('Forbidden', 403);
}
$dateParts = explode('-', $date);
if (!preg_match('/^\d{4}\-\d{2}$/', $date) || !checkdate((int) ($dateParts[1] ?? 13), 1, (int) $dateParts[0])) {
throw new RuntimeException('Bad Request', 400);
}
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->getApplicationStorage()
->getApplicationByName($this->environmentManager->getSelectedApplication());
/**
* @var Entity\EntitySet $publications
*/
$publications = $this->getFilesystemStorage()
->getFilesystemPublishedDocumentListByDate(
(int) $applicationEntity->getApplicationId(),
(int) $dateParts[0],
(int) $dateParts[1]
);
if (empty($publications)) {
throw new RuntimeException('Not Found', 404);
}
/**
* @var DateTime $titleDate
*/
$titleDate = $publications[0]->getDatePublished();
/**
* @var Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
*/
foreach ($publications as $publishedDocumentEntity) {
$blogPosts[] = $this->getBlobPostData($applicationEntity, $publishedDocumentEntity);
}
return [
'page' => [
'title' => $titleDate->format('Y4B'),
'type' => 'Archive',
],
'activeMenu' => $date,
'application' => $this->getApplicationData($applicationEntity),
'blogPosts' => $blogPosts,
];
}
}
<file_sep>/src/WebHemi/Middleware/Security/AccessLogMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Security;
use WebHemi\Auth\ServiceInterface as AuthServiceInterface;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Logger\ServiceInterface as LoggerInterface;
use WebHemi\Middleware\MiddlewareInterface;
/**
* Class AccessLogMiddleware.
*/
class AccessLogMiddleware implements MiddlewareInterface
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var AuthServiceInterface
*/
private $authAdapter;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* AccessLogMiddleware constructor.
*
* @param LoggerInterface $logger
* @param AuthServiceInterface $authAdapter
* @param EnvironmentInterface $environmentManager
*/
public function __construct(
LoggerInterface $logger,
AuthServiceInterface $authAdapter,
EnvironmentInterface $environmentManager
) {
$this->logger = $logger;
$this->authAdapter = $authAdapter;
$this->environmentManager = $environmentManager;
}
/**
* A middleware is a callable. It can do whatever is appropriate with the Request and Response objects.
* The only hard requirement is that a middleware MUST return an instance of \Psr\Http\Message\ResponseInterface.
* Each middleware SHOULD invoke the next middleware and pass it Request and Response objects as arguments.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return void
*/
public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void
{
$identity = 'Unauthenticated user';
$requestAttributes = $request->getAttributes();
$actionMiddleware = $requestAttributes[ServerRequestInterface::REQUEST_ATTR_RESOLVED_ACTION_CLASS] ?? 'N/A';
if ($this->authAdapter->hasIdentity()) {
/**
* @var UserEntity $userEntity
*/
$userEntity = $this->authAdapter->getIdentity();
$identity = $userEntity->getEmail();
}
$data = [
'User' => $identity,
'IP' => $this->environmentManager->getClientIp(),
'RequestUri' => $request->getUri()->getPath().'?'.$request->getUri()->getQuery(),
'RequestMethod' => $request->getMethod(),
'Action' => $actionMiddleware,
'Parameters' => $request->getParsedBody()
];
$response = $response->withStatus(ResponseInterface::STATUS_PROCESSING);
$this->logger->log('info', json_encode($data));
}
}
<file_sep>/src/WebHemi/I18n/TimeZone/Europe_Budapest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
return [
'Y4M' => '%Y. %m.',
'Y4B' => '%Y. %B',
'Y4b' => '%Y. %b',
'Y2MD' => '%y. %m. %d.',
'Y2BD' => '%y. %B %Q',
'Y2bD' => '%y. %b %Q',
'Y4MD' => '%Y. %m. %d.',
'Y4BD' => '%Y. %B %Q',
'Y4bD' => '%Y. %b %Q',
'MD' => '%m. %d.',
'BD' => '%B %Q',
'bD' => '%b %Q',
'T' => '%H:%M',
'TS' => '%H:%M:%S',
'MDT' => '%m. %d. %H:%M',
'BDT' => '%B %Q %H:%M',
'bDT' => '%b %Q %H:%M',
'Y4MDT' => '%Y. %m. %d., %H:%M',
'Y4BDT' => '%Y. %B %Q, %H:%M',
'Y4bDT' => '%Y. %b %Q, %H:%M',
'Y4MDTS' => '%Y. %m. %d., %H:%M:%S',
'Y4BDTS' => '%Y. %B %Q, %H:%M:%S',
'Y4bDTS' => '%Y. %b %Q, %H:%M:%S',
'ordinals' => false
];
<file_sep>/config/settings/_global/db.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Data;
return [
'dependencies' => [
'Global' => [
Data\Driver\DriverInterface::class => [
'class' => Data\Driver\PDO\SQLite\DriverAdapter::class,
'arguments' => [
'dsn' => 'sqlite:'.realpath(__DIR__ . '/../../../build/webhemi_schema.sqlite3'),
],
'shared' => true
],
Data\Query\QueryInterface::class => [
'class' => Data\Query\SQLite\QueryAdapter::class,
'arguments' => [
Data\Driver\DriverInterface::class
]
]
],
],
];
<file_sep>/tests/WebHemiTest/TestService/EmptyI18nDriver.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\I18n\ServiceInterface;
use WebHemi\I18n\DriverInterface;
/**
* Class EmptyI18nDriver
*/
class EmptyI18nDriver implements DriverInterface
{
/** @var ServiceInterface */
private $i18nService;
/** @var array */
public $dictionary = [];
/**
* DriverInterface constructor.
*
* @param ServiceInterface $i18nService
*/
public function __construct(ServiceInterface $i18nService)
{
$this->i18nService = $i18nService;
}
/**
* Translates the given text.
*
* @param string $text
* @return string
*/
public function translate(string $text) : string
{
return $this->dictionary[$text] ?? $text;
}
}
<file_sep>/src/WebHemi/Http/ServiceAdapter/GuzzleHttp/Response.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http\ServiceAdapter\GuzzleHttp;
use GuzzleHttp\Psr7\Response as GuzzleResponse;
use WebHemi\Http\ResponseInterface;
/**
* Class Response.
*/
class Response extends GuzzleResponse implements ResponseInterface
{
// The only purpose of this extension is to be able to implement the WebHemi's ResponseInterface.
}
<file_sep>/build/webhemi_schema.sql
/*!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 */;
/*!40103 SET @OLD_TIME_ZONE = @@TIME_ZONE */;
/*!40103 SET TIME_ZONE = '+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS = @@UNIQUE_CHECKS, UNIQUE_CHECKS = 0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0 */;
/*!40101 SET @OLD_SQL_MODE = @@SQL_MODE, SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES = @@SQL_NOTES, SQL_NOTES = 0 */;
--
-- Create database `webhemi`
--
UNLOCK TABLES;
CREATE DATABASE IF NOT EXISTS `webhemi`;
USE `webhemi`;
--
-- Cleanup old stuff
--
DROP TABLE IF EXISTS `webhemi_lock`;
DROP TABLE IF EXISTS `webhemi_filesystem_content`;
DROP TABLE IF EXISTS `webhemi_filesystem_content_attachment`;
DROP TABLE IF EXISTS `webhemi_filesystem_folder`;
DROP TABLE IF EXISTS `webhemi_am_policy`;
DROP TABLE IF EXISTS `webhemi_am_resource`;
DROP TABLE IF EXISTS `webhemi_user_to_am_policy`;
DROP TABLE IF EXISTS `webhemi_user_group_to_am_policy`;
--
-- Table structure for table `webhemi_application`
--
DROP TABLE IF EXISTS `webhemi_application`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_application` (
`id_application` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(30) NOT NULL,
`title` VARCHAR(255) NOT NULL,
-- introduction can be a fixed content on the index page
`introduction` TEXT DEFAULT NULL,
`subject` VARCHAR(255) NOT NULL DEFAULT '',
`description` VARCHAR(255) NOT NULL DEFAULT '',
`keywords` VARCHAR(255) NOT NULL DEFAULT '',
`copyright` VARCHAR(255) NOT NULL DEFAULT '',
`path` VARCHAR(20) NOT NULL,
`theme` VARCHAR(20) NOT NULL DEFAULT 'deafult',
`type` ENUM ('domain', 'directory') NOT NULL DEFAULT 'directory',
`locale` VARCHAR(20) NOT NULL DEFAULT 'en_GB.UTF-8',
`timezone` VARCHAR(100) NOT NULL DEFAULT 'Europe/London',
`is_read_only` TINYINT(1) NOT NULL DEFAULT 0,
`is_enabled` TINYINT(1) NOT NULL DEFAULT 0,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_application`),
UNIQUE KEY `unq_application_name` (`name`),
UNIQUE KEY `unq_application_title` (`title`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_application`
--
LOCK TABLES `webhemi_application` WRITE;
/*!40000 ALTER TABLE `webhemi_application`
DISABLE KEYS */;
INSERT INTO `webhemi_application` VALUES
(1, 'admin', 'Admin', '', '', '', '', '', 'admin', 'default', 'directory', 'en_GB.UTF-8', 'Europe/London', 1, 1, NOW(), NULL),
(2, 'website', 'Website', '<h1>Welcome to the WebHemi!</h1><p>After many years of endless development of a big, robust, super-universal blog engine which was suppose to build on a well known framework, I decided to re-think my goals and the way I want to reach them. Now I try to create a small, fast and "only as much as necessary", clean-code blog engine that tries to completely apply the S.O.L.I.D. principles, uses the PSR-7 HTTP Messages Interfaces and the Middleware concept.</p>', 'Technical stuff', 'The default application for the `www` subdomain.', 'php,html,javascript,css', 'Copyright © 2017. WebHemi', 'www', 'default', 'domain', 'en_GB.UTF-8', 'Europe/London', 1, 1, NOW(), NULL);
/*!40000 ALTER TABLE `webhemi_application`
ENABLE KEYS */;
UNLOCK TABLES;
-- AM - Access Management
--
-- Table structure for table `webhemi_resource`
--
DROP TABLE IF EXISTS `webhemi_resource`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_resource` (
`id_resource` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`description` TEXT NOT NULL,
`type` ENUM ('route', 'custom') NOT NULL,
`is_read_only` TINYINT(1) NOT NULL DEFAULT 0,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_resource`),
UNIQUE KEY `unq_resource_name` (`name`),
UNIQUE KEY `unq_resource_title` (`title`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_resource`
--
LOCK TABLES `webhemi_resource` WRITE;
/*!40000 ALTER TABLE `webhemi_resource`
DISABLE KEYS */;
INSERT INTO `webhemi_resource` VALUES
(1, 'admin-dashboard', 'Dashboard', '', 'route', 1, NOW(), NULL),
(2, 'admin-applications-list', 'List applications', '', 'route', 1, NOW(), NULL),
(3, 'admin-applications-add', 'Add application', '', 'route', 1, NOW(), NULL),
(4, 'admin-applications-view', 'View application', '', 'route', 1, NOW(), NULL),
(5, 'admin-applications-preferences', 'Edit application', '', 'route', 1, NOW(), NULL),
(6, 'admin-applications-save', 'Save application', '', 'route', 1, NOW(), NULL),
(7, 'admin-applications-delete', 'Delete application', '', 'route', 1, NOW(), NULL),
(8, 'manage-application-admin', 'Manage the admin app', '', 'custom', 1, NOW(), NULL),
(9, 'manage-application-website', 'Manage the website app', '', 'custom', 1, NOW(), NULL),
(10, 'admin-control-panel-index', 'List Control Panel items', '', 'route', 1, NOW(), NULL),
(11, 'admin-control-panel-themes-list', 'List themes', '', 'route', 1, NOW(), NULL),
(12, 'admin-control-panel-themes-add', 'Add theme', '', 'route', 1, NOW(), NULL),
(13, 'admin-control-panel-themes-view', 'View theme', '', 'route', 1, NOW(), NULL),
(14, 'admin-control-panel-themes-delete', 'Delete theme', '', 'route', 1, NOW(), NULL);
/*!40000 ALTER TABLE `webhemi_resource`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_policy`
--
DROP TABLE IF EXISTS `webhemi_policy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_policy` (
`id_policy` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
-- If key is NULL, then the policy is applied to all resources
`fk_resource` INT(10) UNSIGNED DEFAULT NULL,
-- If key is NULL, then the policy is applied to all applications
`fk_application` INT(10) UNSIGNED DEFAULT NULL,
`name` VARCHAR(255) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`description` TEXT NOT NULL DEFAULT '',
`method` ENUM ('GET', 'POST') DEFAULT NULL,
`is_read_only` TINYINT(1) NOT NULL DEFAULT 0,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_policy`),
UNIQUE KEY `unq_policy` (`fk_resource`, `fk_application`, `method`),
UNIQUE KEY `unq_policy_title` (`title`),
KEY `idx_policy_fk_resource` (`fk_resource`),
KEY `idx_policy_fk_application` (`fk_application`),
CONSTRAINT `fkx_policy_fk_resource` FOREIGN KEY (`fk_resource`) REFERENCES `webhemi_resource` (`id_resource`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_policy_fk_application` FOREIGN KEY (`fk_application`) REFERENCES `webhemi_application` (`id_application`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_policy`
--
LOCK TABLES `webhemi_policy` WRITE;
/*!40000 ALTER TABLE `webhemi_policy`
DISABLE KEYS */;
INSERT INTO `webhemi_policy` VALUES
(1, NULL, NULL, 'supervisor', 'Supervisor access',
'Allow access to all resources in every application with any request method.', NULL, 1, NOW(), NULL),
(2, 1, 1, 'dashboard', 'Dashborad access', 'Allow to view the dashboard.', NULL, 1, NOW(), NULL),
(3, 2, 1, 'applications-list', 'Application access', 'Allow to list the applications.', NULL, 1, NOW(), NULL),
(4, 3, 1, 'applications-add', 'Application creator', 'Allow to create new application. Doesn\'t include "save".', NULL, 1, NOW(), NULL),
(5, 4, 1, 'applications-view', 'Application viewer', 'Allow to access application detail page.', NULL, 1, NOW(), NULL),
(6, 5, 1, 'applications-edit', 'Application editor (view)', 'Allow to edit the application preferences. Doesn\'t include "save".', NULL, 1, NOW(), NULL),
(7, 6, 1, 'applications-save', 'Application editor (save)', 'Allow to save the changes on the application preferences.', NULL, 1, NOW(), NULL),
(8, 7, 1, 'applications-delete-review', 'Application remover (review)', 'Allow to review the application that is about to be deleted. Doesn\'t include "confirm".', 'GET', 1, NOW(), NULL),
(9, 7, 1, 'applications-delete-confirm', 'Application remover (confirm)', 'Allow to delete application permanently.', 'POST', 1, NOW(), NULL),
(10, 8, 1, 'manage-application-admin', 'Manage Admin', 'Allow to manage the Admin application. Use along with other Application policies.', NULL, 1, NOW(), NULL),
(11, 9, 1, 'manage-application-website', 'Manage Website', 'Allow to manage the Website application. Use along with other Application policies.', NULL, 1, NOW(), NULL),
(12, 10, 1, 'control-panel-index', 'Control panel access', 'Allow to view the Control Panel page.', NULL, 1, NOW(), NULL),
(13, 11, 1, 'themes-list', 'Theme Manager access', 'Allow to list the installed themes.', NULL, 1, NOW(), NULL),
(14, 12, 1, 'themes-add', 'Theme uploader', 'Allow to upload new theme. Doesn\'t include "save".', 'GET', 1, NOW(), NULL),
(15, 12, 1, 'themes-add-save', 'Theme uploader (save)', 'Allow to save the uploaded theme.', 'POST', 1, NOW(), NULL),
(16, 13, 1, 'themes-view', 'Theme viewer', 'Allow to view theme properties.', NULL, 1, NOW(), NULL),
(17, 14, 1, 'themes-delete-review', 'Theme remover (review)', 'Allow to review the theme that is about to be deleted. Doesn\'t include "confirm".', 'GET', 1, NOW(), NULL),
(18, 14, 1, 'themes-delete-confirm', 'Theme remover (confirm)', 'Allow to delete theme permanently.', 'POST', 1, NOW(), NULL);
/*!40000 ALTER TABLE `webhemi_policy`
ENABLE KEYS */;
UNLOCK TABLES;
-- IM - Identity Management
--
-- Table structure for table `webhemi_user`
--
DROP TABLE IF EXISTS `webhemi_user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_user` (
`id_user` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) DEFAULT NULL,
-- Hashed password. MD5 and SHA1 are not recommended.
`password` VARCHAR(60) NOT NULL,
-- Hash is used in emails and auto-login cookie to identify user without credentials. Once used a new one should be generated.
`hash` VARCHAR(32) DEFAULT NULL,
`is_active` TINYINT(1) NOT NULL DEFAULT '0',
`is_enabled` TINYINT(1) NOT NULL DEFAULT '0',
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_user`),
UNIQUE KEY `unq_user_username` (`username`),
UNIQUE KEY `unq_user_email` (`email`),
UNIQUE KEY `unq_user_hash` (`hash`),
KEY `idx_user_password` (`<PASSWORD>`),
KEY `idx_user_is_active` (`is_active`),
KEY `idx_user_is_enabled` (`is_enabled`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_user`
--
LOCK TABLES `webhemi_user` WRITE;
/*!40000 ALTER TABLE `webhemi_user`
DISABLE KEYS */;
INSERT INTO `webhemi_user` VALUES
(1, 'admin', '<EMAIL>', '$2y$09$dmrDfcYZt9jORA4vx9MKpeyRt0ilCH/gxSbSHcfBtGaghMJ30tKzS', 'hash-admin', 1, 1, NOW(), NULL),
(2, 'demo', '<EMAIL>', '$2y$09$dmrDfcYZt9jORA4vx9MKpeyRt0ilCH/gxSbSHcfBtGaghMJ30tKzS', 'hash-demo', 1, 1, NOW(), NULL);
/*!40000 ALTER TABLE `webhemi_user`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_user_meta`
--
DROP TABLE IF EXISTS `webhemi_user_meta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_user_meta` (
`id_user_meta` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_user` INT(10) UNSIGNED NOT NULL,
`meta_key` VARCHAR(255) NOT NULL,
`meta_data` LONGTEXT NOT NULL,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_user_meta`),
UNIQUE KEY `unq_user_meta` (`fk_user`, `meta_key`),
CONSTRAINT `fkx_user_meta_fk_user` FOREIGN KEY (`fk_user`) REFERENCES `webhemi_user` (`id_user`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_user_meta`
--
LOCK TABLES `webhemi_user_meta` WRITE;
/*!40000 ALTER TABLE `webhemi_user_meta`
DISABLE KEYS */;
INSERT INTO `webhemi_user_meta` VALUES
(NULL, 1, 'display_name', '<NAME>', NOW(), NULL),
(NULL, 1, 'gender', 'male', NOW(), NULL),
(NULL, 1, 'avatar', '/img/avatars/suit_man.svg', NOW(), NULL),
(NULL, 1, 'avatar_type', 'file', NOW(), NULL),
(NULL, 1, 'email_visible', '0', NOW(), NULL),
(NULL, 1, 'location', '', NOW(), NULL),
(NULL, 1, 'instant_messengers', '', NOW(), NULL),
(NULL, 1, 'phone_numbers', '', NOW(), NULL),
(NULL, 1, 'social_networks', '', NOW(), NULL),
(NULL, 1, 'websites', '', NOW(), NULL),
(NULL, 1, 'introduction', '', NOW(), NULL),
(NULL, 2, 'display_name', 'Demo user', NOW(), NULL),
(NULL, 2, 'gender', 'male', NOW(), NULL),
(NULL, 2, 'avatar', '/img/avatars/tie_man.svg', NOW(), NULL),
(NULL, 2, 'avatar_type', 'file', NOW(), NULL),
(NULL, 2, 'email_visible', '0', NOW(), NULL),
(NULL, 2, 'location', '', NOW(), NULL),
(NULL, 2, 'instant_messengers', '', NOW(), NULL),
(NULL, 2, 'phone_numbers', '', NOW(), NULL),
(NULL, 2, 'social_networks', '', NOW(), NULL),
(NULL, 2, 'websites', '', NOW(), NULL),
(NULL, 2, 'introduction', '', NOW(), NULL);
/*!40000 ALTER TABLE `webhemi_user_meta`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_user_policy`
--
DROP TABLE IF EXISTS `webhemi_user_to_policy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_user_to_policy` (
`id_user_to_policy` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_user` INT(10) UNSIGNED NOT NULL,
`fk_policy` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id_user_to_policy`),
UNIQUE KEY `unq_user_to_policy` (`fk_user`, `fk_policy`),
KEY `idx_user_to_policy_fk_user` (`fk_user`),
KEY `idx_user_to_policy_fk_policy` (`fk_policy`),
CONSTRAINT `fkx_user_to_policy_fk_user` FOREIGN KEY (`fk_user`) REFERENCES `webhemi_user` (`id_user`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_user_to_policy_fk_policy` FOREIGN KEY (`fk_policy`) REFERENCES `webhemi_policy` (`id_policy`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Users can be assigned to policies dierectly --
--
-- Dumping data for table `webhemi_user_policy`
--
LOCK TABLES `webhemi_user_to_policy` WRITE;
/*!40000 ALTER TABLE `webhemi_user_to_policy`
DISABLE KEYS */;
/*!40000 ALTER TABLE `webhemi_user_to_policy`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_user_group`
--
DROP TABLE IF EXISTS `webhemi_user_group`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_user_group` (
`id_user_group` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`title` VARCHAR(30) NOT NULL,
`description` TEXT NOT NULL DEFAULT '',
`is_read_only` TINYINT(1) NOT NULL DEFAULT 0,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_user_group`),
UNIQUE KEY `unq_user_group_title` (`title`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_user_group`
--
LOCK TABLES `webhemi_user_group` WRITE;
/*!40000 ALTER TABLE `webhemi_user_group`
DISABLE KEYS */;
INSERT INTO `webhemi_user_group` VALUES
(1, 'admin', 'Administrators', 'Group for global administrators', 1, NOW(), NULL),
(2, 'demo', 'Demo group', 'Read-only access for test/demo purposes.', 1, NOW(), NULL);
/*!40000 ALTER TABLE `webhemi_user_group`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_user_to_user_group`
--
DROP TABLE IF EXISTS `webhemi_user_to_user_group`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_user_to_user_group` (
`id_user_to_user_group` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_user` INT(10) UNSIGNED NOT NULL,
`fk_user_group` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id_user_to_user_group`),
UNIQUE KEY `unq_user_to_user_group` (`fk_user`, `fk_user_group`),
KEY `idx_user_to_user_group_fk_user` (`fk_user`),
KEY `idx_user_to_user_group_fk_user_group` (`fk_user_group`),
CONSTRAINT `fkx_user_to_user_group_fk_user` FOREIGN KEY (`fk_user`) REFERENCES `webhemi_user` (`id_user`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_user_to_user_group_fk_user_group` FOREIGN KEY (`fk_user_group`) REFERENCES `webhemi_user_group` (`id_user_group`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_user_to_user_group`
--
LOCK TABLES `webhemi_user_to_user_group` WRITE;
/*!40000 ALTER TABLE `webhemi_user_to_user_group`
DISABLE KEYS */;
INSERT INTO `webhemi_user_to_user_group` VALUES
(NULL, 1, 1),
(NULL, 2, 2);
/*!40000 ALTER TABLE `webhemi_user_to_user_group`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_user_group_to_policy`
--
DROP TABLE IF EXISTS `webhemi_user_group_to_policy`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_user_group_to_policy` (
`id_user_group_to_policy` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_user_group` INT(10) UNSIGNED NOT NULL,
`fk_policy` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id_user_group_to_policy`),
UNIQUE KEY `unq_user_group_to_policy` (`fk_user_group`, `fk_policy`),
KEY `idx_user_group_to_policy_fk_user_group` (`fk_user_group`),
KEY `idx_user_group_to_policy_fk_policy` (`fk_policy`),
CONSTRAINT `fkx_user_group_to_policy_fk_user_group` FOREIGN KEY (`fk_user_group`) REFERENCES `webhemi_user_group` (`id_user_group`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_user_group_to_policy_fk_policy` FOREIGN KEY (`fk_policy`) REFERENCES `webhemi_policy` (`id_policy`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_user_group_to_policy`
--
LOCK TABLES `webhemi_user_group_to_policy` WRITE;
/*!40000 ALTER TABLE `webhemi_user_group_to_policy`
DISABLE KEYS */;
INSERT INTO `webhemi_user_group_to_policy` VALUES
(NULL, 1, 1),
(NULL, 2, 2),
(NULL, 2, 3),
(NULL, 2, 5),
(NULL, 2, 11);
/*!40000 ALTER TABLE `webhemi_user_group_to_policy`
ENABLE KEYS */;
UNLOCK TABLES;
-- FS - Filesystem
--
-- Table structure for table `webhemi_filesystem_directory`
--
DROP TABLE IF EXISTS `webhemi_filesystem_directory`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_directory` (
`id_filesystem_directory` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) DEFAULT '',
-- Directory types:
-- * document: the index.html should display a list of the edited (HTML) contents under the given uri. Other contents should not be displayed directly.
-- * gallery: the index.html should provide gallery functionality for the images under the given uri. Other contents should not be displayed directly.
-- * binary: the index.html should display a list of links for all the contents under the given uri.
`directory_type` ENUM ('document', 'gallery', 'binary') NOT NULL,
`proxy` ENUM ('list-category', 'list-tag', 'list-archive', 'list-gallery', 'list-binary', 'list-user') DEFAULT NULL,
-- If auto indexing is 0 the application should lead to 404 or 403 when requesting the given uri
`is_autoindex` TINYINT(1) UNSIGNED NOT NULL DEFAULT 1,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_filesystem_directory`),
UNIQUE KEY `unq_filesystem_directory_proxy` (`proxy`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_filesystem_directory`
--
LOCK TABLES `webhemi_filesystem_directory` WRITE;
/*!40000 ALTER TABLE `webhemi_filesystem_directory`
DISABLE KEYS */;
INSERT INTO `webhemi_filesystem_directory` VALUES
(1, 'Categories post collection', 'document', 'list-category', 1, NOW(), NOW()),
(2, 'Tags post collection', 'document', 'list-tag', 1, NOW(), NOW()),
(3, 'Archive post collection', 'document', 'list-archive', 1, NOW(), NOW()),
(4, 'All uploaded images collection', 'gallery', 'list-gallery', 1, NOW(), NOW()),
(5, 'All uploaded files collection', 'binary', 'list-binary', 1, NOW(), NOW()),
(6, 'User page and post collection', 'document', 'list-user', 1, NOW(), NOW());
/*!40000 ALTER TABLE `webhemi_filesystem_directory`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_filesystem_file`
--
DROP TABLE IF EXISTS `webhemi_filesystem_file`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_file` (
`id_filesystem_file` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`file_hash` VARCHAR(255) NOT NULL,
-- Typically a temporary filename with absolute path
`path` VARCHAR(255) NOT NULL,
`file_type` ENUM ('image', 'video', 'audio', 'binary') NOT NULL,
`mime_type` VARCHAR(255) NOT NULL,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_filesystem_file`),
UNIQUE KEY `unq_filesystem_file_file_hash` (`file_hash`),
UNIQUE KEY `unq_filesystem_file_path` (`path`)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `webhemi_filesystem_document`
--
DROP TABLE IF EXISTS `webhemi_filesystem_document`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_document` (
`id_filesystem_document` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_parent_revision` INT(10) UNSIGNED DEFAULT NULL,
`fk_author` INT(10) UNSIGNED DEFAULT NULL,
`content_revision` INT(10) UNSIGNED NOT NULL DEFAULT 1,
`content_lead` TEXT NOT NULL,
`content_body` TEXT NOT NULL,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_filesystem_document`),
KEY `idx_filesystem_document_content_revision` (`content_revision`),
KEY `idx_filesystem_document_fk_parent_revision` (`fk_parent_revision`),
KEY `id_filesystem_document_fk_author` (`fk_author`),
CONSTRAINT `fkx_filesystem_document_fk_parent_revision` FOREIGN KEY (`fk_parent_revision`) REFERENCES `webhemi_filesystem_document` (`id_filesystem_document`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_document_fk_author` FOREIGN KEY (`fk_author`) REFERENCES `webhemi_user` (`id_user`)
ON DELETE SET NULL
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `webhemi_filesystem_category`
--
DROP TABLE IF EXISTS `webhemi_filesystem_category`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_category` (
`id_filesystem_category` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_application` INT(10) UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
`title` VARCHAR(30) NOT NULL,
`description` TEXT NOT NULL DEFAULT '',
`item_order` ENUM('ASC','DESC') NOT NULL DEFAULT 'DESC',
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_filesystem_category`),
UNIQUE KEY `unq_filesystem_file_file_hash` (`fk_application`, `name`),
KEY `idx_filesystem_category_fk_application` (`fk_application`),
CONSTRAINT `fkx_filesystem_category_fk_application` FOREIGN KEY (`fk_application`) REFERENCES `webhemi_application` (`id_application`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `webhemi_filesystem_tag`
--
DROP TABLE IF EXISTS `webhemi_filesystem_tag`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_tag` (
`id_filesystem_tag` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_application` INT(10) UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
`title` VARCHAR(30) NOT NULL,
`description` TEXT NOT NULL DEFAULT '',
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_filesystem_tag`),
UNIQUE KEY `unq_filesystem_file_file_hash` (`fk_application`, `name`),
KEY `idx_filesystem_tag_fk_application` (`fk_application`),
CONSTRAINT `fkx_filesystem_tag_fk_application` FOREIGN KEY (`fk_application`) REFERENCES `webhemi_application` (`id_application`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `webhemi_filesystem`
--
DROP TABLE IF EXISTS `webhemi_filesystem`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem` (
`id_filesystem` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_application` INT(10) UNSIGNED NOT NULL,
`fk_category` INT(10) UNSIGNED DEFAULT NULL,
`fk_parent_node` INT(10) UNSIGNED DEFAULT NULL,
-- The application should handle to (compulsorily) set only one of these at a time
`fk_filesystem_document` INT(10) UNSIGNED DEFAULT NULL,
`fk_filesystem_file` INT(10) UNSIGNED DEFAULT NULL,
`fk_filesystem_directory` INT(10) UNSIGNED DEFAULT NULL,
`fk_filesystem_link` INT(10) UNSIGNED DEFAULT NULL,
`path` VARCHAR(255) NOT NULL DEFAULT '/',
`basename` VARCHAR(255) NOT NULL,
`title` VARCHAR(255) NOT NULL,
-- Image caption, article summary, file description
`description` TEXT,
-- If the record is marked as hidden the application should exclude it from data sets
`is_hidden` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
-- It marks that the record cannot be deleted (or marked as deleted) or change visibility, but can be renamed according to the application's language
`is_read_only` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
`is_deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`date_published` DATETIME DEFAULT NULL,
PRIMARY KEY (`id_filesystem`),
UNIQUE KEY `unq_uri` (`fk_application`, `path`, `basename`),
KEY `idx_filesystem_fk_application` (`fk_application`),
KEY `idx_filesystem_fk_category` (`fk_category`),
KEY `idx_filesystem_fk_parent_node` (`fk_parent_node`),
KEY `idx_filesystem_fk_filesystem_document` (`fk_filesystem_document`),
KEY `idx_filesystem_fk_filesystem_file` (`fk_filesystem_file`),
KEY `idx_filesystem_fk_filesystem_directory` (`fk_filesystem_directory`),
KEY `idx_filesystem_fk_filesystem_link` (`fk_filesystem_link`),
KEY `idx_filesystem_path` (`path`),
KEY `idx_filesystem_file_basename` (`basename`),
KEY `idx_filesystem_is_hidden` (`is_hidden`),
KEY `idx_filesystem_is_read_only` (`is_read_only`),
KEY `idx_filesystem_is_deleted` (`is_deleted`),
CONSTRAINT `fkx_filesystem_fk_application` FOREIGN KEY (`fk_application`) REFERENCES `webhemi_application` (`id_application`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_fk_category` FOREIGN KEY (`fk_category`) REFERENCES `webhemi_filesystem_category` (`id_filesystem_category`)
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_fk_parent_node` FOREIGN KEY (`fk_parent_node`) REFERENCES `webhemi_filesystem` (`id_filesystem`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_fk_filesystem_document` FOREIGN KEY (`fk_filesystem_document`) REFERENCES `webhemi_filesystem_document` (`id_filesystem_document`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_fk_filesystem_file` FOREIGN KEY (`fk_filesystem_file`) REFERENCES `webhemi_filesystem_file` (`id_filesystem_file`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_fk_filesystem_directory` FOREIGN KEY (`fk_filesystem_directory`) REFERENCES `webhemi_filesystem_directory` (`id_filesystem_directory`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_fk_filesystem_link` FOREIGN KEY (`fk_filesystem_link`) REFERENCES `webhemi_filesystem` (`id_filesystem`)
ON DELETE RESTRICT
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `webhemi_filesystem`
--
LOCK TABLES `webhemi_filesystem` WRITE;
/*!40000 ALTER TABLE `webhemi_filesystem`
DISABLE KEYS */;
INSERT INTO `webhemi_filesystem` VALUES
(1, 2, NULL, NULL, NULL, NULL, 1, NULL, '/', 'category', 'Categories', '', 1, 1, 0, NOW(), NULL, NOW()),
(2, 2, NULL, NULL, NULL, NULL, 2, NULL, '/', 'tag', 'Tags', '', 1, 1, 0, NOW(), NULL, NOW()),
(3, 2, NULL, NULL, NULL, NULL, 3, NULL, '/', 'archive', 'Archive', '', 1, 1, 0, NOW(), NULL, NOW()),
(4, 2, NULL, NULL, NULL, NULL, 4, NULL, '/', 'media', 'Uploaded images', '', 1, 1, 0, NOW(), NULL, NOW()),
(5, 2, NULL, NULL, NULL, NULL, 5, NULL, '/', 'uploads', 'Uploaded files', '', 1, 1, 0, NOW(), NULL, NOW()),
(6, 2, NULL, NULL, NULL, NULL, 6, NULL, '/', 'user', 'User', '', 1, 1, 0, NOW(), NULL, NOW());
/*!40000 ALTER TABLE `webhemi_filesystem`
ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `webhemi_filesystem_meta`
--
DROP TABLE IF EXISTS `webhemi_filesystem_meta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_meta` (
`id_filesystem_meta` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_filesystem` INT(10) UNSIGNED NOT NULL,
`meta_key` VARCHAR(255) NOT NULL,
`meta_data` LONGTEXT NOT NULL,
`date_created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_modified` DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id_filesystem_meta`),
UNIQUE KEY `unq_filesystem_meta` (`fk_filesystem`, `meta_key`),
CONSTRAINT `fkx_filesystem_meta_fk_filesystem` FOREIGN KEY (`fk_filesystem`) REFERENCES `webhemi_filesystem` (`id_filesystem`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `webhemi_filesystem_to_tag`
--
DROP TABLE IF EXISTS `webhemi_filesystem_to_filesystem_tag`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_to_filesystem_tag` (
`id_filesystem_to_filesystem_tag` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_filesystem` INT(10) UNSIGNED NOT NULL,
`fk_filesystem_tag` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id_filesystem_to_filesystem_tag`),
UNIQUE KEY `unq_filesystem_to_filesystem_tag` (`fk_filesystem_tag`, `fk_filesystem`),
KEY `idx_filesystem_to_filesystem_tag_filesystem_tag` (`fk_filesystem_tag`),
KEY `idx_filesystem_to_filesystem_tag_filesystem` (`fk_filesystem`),
CONSTRAINT `fkx_filesystem_to_filesystem_tag_fk_filesystem_tag` FOREIGN KEY (`fk_filesystem_tag`) REFERENCES `webhemi_filesystem_tag` (`id_filesystem_tag`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_to_filesystem_tag_fk_filesystem` FOREIGN KEY (`fk_filesystem`) REFERENCES `webhemi_filesystem` (`id_filesystem`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
--
-- Table structure for table `webhemi_filesystem_document_attachment`
--
DROP TABLE IF EXISTS `webhemi_filesystem_document_attachment`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `webhemi_filesystem_document_attachment` (
`id_filesystem_document_attachment` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`fk_filesystem_document` INT(10) UNSIGNED NOT NULL,
`fk_filesystem` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id_filesystem_document_attachment`),
UNIQUE KEY `unq_filesystem_document_attachment` (`fk_filesystem_document`, `fk_filesystem`),
KEY `idx_filesystem_document_attachment_filesystem_document` (`fk_filesystem_document`),
KEY `idx_filesystem_document_attachment_filesystem` (`fk_filesystem`),
CONSTRAINT `fkx_filesystem_document_attachment_fk_filesystem_document` FOREIGN KEY (`fk_filesystem_document`) REFERENCES `webhemi_filesystem_document` (`id_filesystem_document`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fkx_filesystem_document_attachment_fk_filesystem` FOREIGN KEY (`fk_filesystem`) REFERENCES `webhemi_filesystem` (`id_filesystem`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE = @OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE = @OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS = @OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS = @OLD_UNIQUE_CHECKS */;
/*!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 */;
/*!40111 SET SQL_NOTES = @OLD_SQL_NOTES */;
<file_sep>/src/WebHemi/I18n/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\I18n\ServiceAdapter\Base;
use InvalidArgumentException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\I18n\ServiceInterface;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* @var EnvironmentInterface
*/
protected $environmentManager;
/**
* @var string
*/
protected $language;
/**
* @var string
*/
protected $territory;
/**
* @var string
*/
protected $codeSet;
/**
* @var string
*/
protected $locale;
/**
* @var string
*/
protected $timeZone;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager
) {
$this->configuration = $configuration;
$this->environmentManager = $environmentManager;
$currentApplicationConfig = $configuration
->getConfig('applications')
->getData($environmentManager->getSelectedApplication());
$this->setLocale($currentApplicationConfig['locale']);
$this->setTimeZone($currentApplicationConfig['timezone']);
}
/**
* Gets the language.
*
* @return string
*/
public function getLanguage() : string
{
return $this->language;
}
/**
* Sets the language.
*
* @param string $language
*/
protected function setLanguage(string $language) : void
{
$this->language = $language;
putenv('LANGUAGE='.$language);
putenv('LANG='.$language);
setlocale(LC_TIME, '');
}
/**
* Gets the territory.
*
* @return string
*/
public function getTerritory() : string
{
return $this->territory;
}
/**
* Gets the Locale.
*
* @return string
*/
public function getLocale() : string
{
return $this->locale;
}
/**
* Gets the code set.
*
* @return string
*/
public function getCodeSet() : string
{
return $this->codeSet;
}
/**
* Sets the locale.
*
* @param string $locale
* @throws InvalidArgumentException
* @return ServiceAdapter
*/
public function setLocale(string $locale) : ServiceAdapter
{
$matches = [];
if (preg_match('/^(?P<language>[a-z]+)_(?P<territory>[A-Z]+)(?:\.(?P<codeSet>.*))?/', $locale, $matches)) {
$language = $matches['language'];
$this->setLanguage($language);
$this->territory = $matches['territory'];
$this->codeSet = $matches['codeSet'] ?? 'UTF-8';
$localeCodeSet = strtolower(str_replace('-', '', $this->codeSet));
$composedLocale = $language.'_'.$this->territory.'.'.$localeCodeSet;
putenv('LC_ALL='.$composedLocale);
setlocale(LC_ALL, $composedLocale);
setlocale(LC_MESSAGES, $composedLocale);
setlocale(LC_CTYPE, $composedLocale);
$this->locale = $composedLocale;
} else {
throw new InvalidArgumentException(sprintf('Invalid locale: %s', $locale), 1000);
}
return $this;
}
/**
* Sets the time zone.
*
* @param string $timeZone
* @return ServiceAdapter
*/
public function setTimeZone(string $timeZone) : ServiceAdapter
{
$this->timeZone = $timeZone;
date_default_timezone_set($timeZone);
return $this;
}
/**
* Gets the time zone.
*
* @return string
*/
public function getTimeZone() : string
{
return $this->timeZone;
}
}
<file_sep>/src/WebHemi/Auth/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\UserStorage;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
* @param ResultInterface $authResultPrototype
* @param StorageInterface $authStorage
* @param UserStorage $dataStorage
*/
public function __construct(
ConfigurationInterface $configuration,
ResultInterface $authResultPrototype,
StorageInterface $authStorage,
UserStorage $dataStorage
);
/**
* Authenticates the user.
*
* @param CredentialInterface $credential
* @return ResultInterface
*/
public function authenticate(CredentialInterface $credential) : ResultInterface;
/**
* Sets the authenticated user.
*
* @param UserEntity $dataEntity
* @return ServiceInterface
*/
public function setIdentity(UserEntity $dataEntity) : ServiceInterface;
/**
* Checks whether the user is authenticated or not.
*
* @return bool
*/
public function hasIdentity() : bool;
/**
* Gets the authenticated user's entity.
*
* @return UserEntity|null
*/
public function getIdentity() : ? UserEntity;
/**
* Clears the session.
*
* @return ServiceInterface
*/
public function clearIdentity() : ServiceInterface;
}
<file_sep>/tests/WebHemiTest/DependencyInjection/GeneralAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\DependencyInjection;
use InvalidArgumentException;
use RuntimeException;
use ArrayObject;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestService\EmptyDependencyInjectionContainer;
use WebHemiTest\TestService\EmptyService;
use WebHemiTest\TestService\TestMiddleware;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use PHPUnit\Framework\TestCase;
/**
* Class GeneralAdapterTest.
*/
class GeneralAdapterTest extends TestCase
{
/** @var Config */
private $config;
use AssertTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
}
/**
* Tests the registerModuleServices() method.
*/
public function testRegisterModuleServices()
{
$serviceCount = 0;
$adapter = new EmptyDependencyInjectionContainer($this->config);
$this->assertAttributeCount($serviceCount, 'serviceLibrary', $adapter);
$globalServices = $this->config->getData('dependencies/Global');
$serviceCount += count(array_keys($globalServices));
$adapter->registerModuleServices('Global');
$this->assertAttributeCount($serviceCount, 'serviceLibrary', $adapter);
$websiteServices = $this->config->getData('dependencies/Website');
$serviceCount += count(array_keys($websiteServices));
$adapter->registerModuleServices('Website');
$this->assertAttributeCount($serviceCount, 'serviceLibrary', $adapter);
$someAppServices = $this->config->getData('dependencies/SomeApp');
$serviceCount += count(array_keys($someAppServices));
$adapter->registerModuleServices('SomeApp');
$this->assertAttributeCount($serviceCount, 'serviceLibrary', $adapter);
$this->expectException(InvalidArgumentException::class);
$adapter->registerModuleServices('NonExistingModule');
}
/**
* Tests the serviceIsInitialized() method.
*/
public function testServiceIsInitialized()
{
$adapter = new EmptyDependencyInjectionContainer($this->config);
$adapter->registerModuleServices('SomeApp');
$this->assertTrue($adapter->has('moreAlias'));
$this->assertFalse($adapter->callServiceIsInitialized('moreAlias'));
$adapter->get('moreAlias');
$this->assertTrue($adapter->callServiceIsInitialized('moreAlias'));
}
/**
* Data provider for the tests.
*
* @return array
*/
public function dataProvider()
{
return [
['alias', ArrayObject::class, ['input' => ['something', 2]], false],
['otherAlias', ArrayObject::class, ['input' => ['something', 2]], false],
['moreAlias', ArrayObject::class, ['input' => ['something', 2]], true],
['lastInherit', ArrayObject::class, ['input' => ['something', 2]], true],
[EmptyService::class, EmptyService::class, ['input' => ['something', 2]], false],
];
}
/**
* Tests how the adapter resolves the inheritance
*
* @param string $identifier
* @param string $expectedClass
*
* @dataProvider dataProvider
*/
public function testInheritance($identifier, $expectedClass, $expectedArgs, $expectedShared)
{
$moduleName = 'SomeApp';
$adapter = new EmptyDependencyInjectionContainer($this->config);
$adapter->registerModuleServices($moduleName);
$actualClass = $adapter->callResolveServiceClassName($identifier, $moduleName);
$actualArgs = $adapter->callResolveServiceArguments($identifier, $moduleName);
$actualShared = $adapter->callResolveShares($identifier, $moduleName);
$this->assertSame($expectedClass, $actualClass);
$this->assertArraysAreSimilar($expectedArgs, $actualArgs);
$this->assertSame($expectedShared, $actualShared);
}
/**
* Tests the resolveServiceClassName() method.
*/
public function testResolveServiceClassName()
{
$moduleName = 'Global';
$adapter = new EmptyDependencyInjectionContainer($this->config);
$adapter->registerModuleServices($moduleName);
$expectedResult = TestMiddleware::class;
$actualResult = $adapter->callResolveServiceClassName('pipe4', $moduleName);
$this->assertSame($expectedResult, $actualResult);
$this->expectException(RuntimeException::class);
$adapter->callResolveServiceClassName('non-registered-service', $moduleName);
}
}
<file_sep>/src/WebHemi/Application/Progress.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Application;
use Exception;
use WebHemi\Environment\ServiceInterface as EnvironmentManager;
use WebHemi\Session\ServiceInterface as SessionManager;
/**
* Class Progress
*/
class Progress
{
/**
* @var EnvironmentManager
*/
private $environmentManager;
/**
* @var string
*/
private $sessionId;
/**
* @var string
*/
private $callerName;
/**
* @var string
*/
private $progressId;
/**
* @var int
*/
private $totalSteps;
/**
* @var int
*/
private $currentStep;
/**
* Progress constructor.
*
* @param EnvironmentManager $environmentManager
* @param SessionManager $sessionManager
*/
public function __construct(EnvironmentManager $environmentManager, SessionManager $sessionManager)
{
$this->environmentManager = $environmentManager;
$this->sessionId = $sessionManager->getSessionId();
}
/**
* Starts the progress.
*
* @param int $totalSteps
* @param string $callerName
*/
public function start(int $totalSteps, string $callerName = null) : void
{
$this->callerName = $callerName ?? $this->getCallerName();
$this->totalSteps = $totalSteps;
$this->currentStep = 0;
$this->progressId = md5($this->sessionId).'_'.$this->callerName;
$this->next();
}
/**
* Gets the Class name where the progress was called from.
*
* @return string
*/
private function getCallerName() : string
{
if (!isset($this->callerName)) {
try {
throw new Exception('Get Trace');
} catch (Exception $exception) {
$trace = $exception->getTrace()[1]['file'] ?? rand(0, 10000);
$trace = explode('/', $trace);
$this->callerName = str_replace('.php', '', array_pop($trace));
}
}
return $this->callerName;
}
/**
* Increments the progress and writes to file.
*/
public function next() : void
{
$handler = fopen(
$this->environmentManager->getApplicationRoot().'/data/progress/'.$this->progressId.'.json',
'w'
);
if ($handler) {
$data = [
'total' => $this->totalSteps,
'current' => $this->currentStep
];
fwrite($handler, json_encode($data));
fclose($handler);
$this->currentStep++;
}
}
/**
* Returns the progress identifier.
*
* @return string
*/
public function getProgressId() : string
{
return $this->progressId;
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemDirectoryDataByApplicationAndProxy.sql
SELECT
fs.`id_filesystem`,
fs.`fk_application` AS id_application,
fsd.`id_filesystem_directory`,
fsd.`description`,
fsd.`directory_type` AS type,
fsd.`proxy`,
fsd.`is_autoindex`,
fs.`path`,
fs.`basename`,
REPLACE(CONCAT(fs.`path`,'/',fs.`basename`), '//', '/') AS uri,
fs.`title`
FROM
`webhemi_filesystem_directory` AS fsd
INNER JOIN `webhemi_filesystem` AS fs ON fsd.`id_filesystem_directory` = fs.`fk_filesystem_directory`
WHERE
fs.`fk_application` = :idApplication AND
fsd.`proxy` = :proxy
<file_sep>/src/WebHemi/Data/Storage/FilesystemStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\FilesystemCategoryEntity;
use WebHemi\Data\Entity\FilesystemDirectoryDataEntity;
use WebHemi\Data\Entity\FilesystemDirectoryEntity;
use WebHemi\Data\Entity\FilesystemDocumentEntity;
use WebHemi\Data\Entity\FilesystemEntity;
use WebHemi\Data\Entity\FilesystemMetaEntity;
use WebHemi\Data\Entity\FilesystemPublishedDocumentEntity;
use WebHemi\Data\Entity\FilesystemTagEntity;
use WebHemi\Data\Query\QueryInterface;
/**
* Class FilesystemStorage.
*
* @SuppressWarnings(PHPMD.TooManyFields)
*/
class FilesystemStorage extends AbstractStorage
{
/**
* Returns a set of filesystem data accroding to the application and directory ID.
*
* @param int $applicationId
* @param int $directoryId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemListByApplicationAndDirectory(
int $applicationId,
int $directoryId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemListByApplicationAndDirectory',
[
':idApplication' => $applicationId,
':idDirectory' => $directoryId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemEntity::class, $data);
}
/**
* Returns filesystem information identified by (unique) ID.
*
* @param int $identifier
* @return null|FilesystemEntity
*/
public function getFilesystemById(int $identifier) : ? FilesystemEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemById',
[
':idFilesystem' => $identifier
]
);
/** @var null|FilesystemEntity $entity */
$entity = $this->getEntity(FilesystemEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns filesystem information by application, basename and path.
*
* @param int $applicationId
* @param string $path
* @param string $baseName
* @return null|FilesystemEntity
*/
public function getFilesystemByApplicationAndPath(
int $applicationId,
string $path,
string $baseName
) : ? FilesystemEntity {
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemByApplicationAndPath',
[
':idApplication' => $applicationId,
':path' => $path,
':baseName' => $baseName
]
);
/** @var null|FilesystemEntity $entity */
$entity = $this->getEntity(FilesystemEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns filesystem meta list identified by filesystem ID.
*
* @param int $identifier
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemMetaListByFilesystem(
int $identifier,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemMetaListByFilesystem',
[
':idFilesystem' => $identifier,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemMetaEntity::class, $data);
}
/**
* Returns a simplified form of the filesystem meta list.
*
* @param int $identifier
* @param int $limit
* @param int $offset
* @return null|array
*/
public function getSimpleFilesystemMetaListByFilesystem(
int $identifier,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : ? array {
$metaInfo = [];
$entitySet = $this->getFilesystemMetaListByFilesystem($identifier, $limit, $offset);
/** @var FilesystemMetaEntity $filesystemMetaEntity */
foreach ($entitySet as $filesystemMetaEntity) {
$metaInfo[$filesystemMetaEntity->getMetaKey()] = $filesystemMetaEntity->getMetaData();
}
return $metaInfo;
}
/**
* Returns the full filesystem document data set.
*
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemDocumentList(
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemDocumentList',
[
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemDocumentEntity::class, $data);
}
/**
* Returns filesystem document information identified by (unique) ID.
*
* @param int $identifier
* @return null|FilesystemDocumentEntity
*/
public function getFilesystemDocumentById(int $identifier) : ? FilesystemDocumentEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemDocumentById',
[
':idDocument' => $identifier
]
);
/** @var null|FilesystemDocumentEntity $entity */
$entity = $this->getEntity(FilesystemDocumentEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns published filesystem data along with the document data.
*
* @param int $applicationId
* @param string|null $order
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemPublishedDocumentList(
int $applicationId,
string $order = null,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
if (empty($order)) {
$order = 'fs.`date_published` DESC';
}
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentList',
[
':idApplication' => $applicationId,
':orderBy' => $order,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemPublishedDocumentEntity::class, $data);
}
/**
* Returns published filesystem data along with the document data.
*
* @param int $applicationId
* @param int $year
* @param int $month
* @param string|null $order
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemPublishedDocumentListByDate(
int $applicationId,
int $year,
int $month,
string $order = null,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
if (empty($order)) {
$order = 'fs.`date_published` DESC';
}
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentListByDate',
[
':idApplication' => $applicationId,
':year' => $year,
':month' => $month,
':orderBy' => $order,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemPublishedDocumentEntity::class, $data);
}
/**
* Returns published filesystem data along with the document data.
*
* @param int $applicationId
* @param int $categoryId
* @param string|null $order
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemPublishedDocumentListByCategory(
int $applicationId,
int $categoryId,
string $order = null,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
if (empty($order)) {
$order = 'fs.`date_published` DESC';
}
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentListByCategory',
[
':idApplication' => $applicationId,
':idCategory' => $categoryId,
':orderBy' => $order,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemPublishedDocumentEntity::class, $data);
}
/**
* Returns published filesystem data according to a user ID along with the document data.
*
* @param int $applicationId
* @param int $userId
* @param string|null $order
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemPublishedDocumentListByAuthor(
int $applicationId,
int $userId,
string $order = null,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
if (empty($order)) {
$order = 'fs.`date_published` DESC';
}
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentListByAuthor',
[
':idApplication' => $applicationId,
':idUser' => $userId,
':orderBy' => $order,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemPublishedDocumentEntity::class, $data);
}
/**
* Returns published filesystem data according to a tag ID along with the document data.
*
* @param int $applicationId
* @param int $tagId
* @param string|null $order
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemPublishedDocumentListByTag(
int $applicationId,
int $tagId,
string $order = null,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
if (empty($order)) {
$order = 'fs.`date_published` DESC';
}
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentListByTag',
[
':idApplication' => $applicationId,
':idTag' => $tagId,
':orderBy' => $order,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemPublishedDocumentEntity::class, $data);
}
/**
* Returns filesystem information by application, basename and path.
*
* @param int $applicationId
* @param string $path
* @param string $baseName
* @return null|FilesystemPublishedDocumentEntity
*/
public function getFilesystemPublishedDocumentByApplicationAndPath(
int $applicationId,
string $path,
string $baseName
) : ? FilesystemPublishedDocumentEntity {
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentByApplicationAndPath',
[
':idApplication' => $applicationId,
':path' => $path,
':baseName' => $baseName
]
);
/** @var null|FilesystemPublishedDocumentEntity $entity */
$entity = $this->getEntity(FilesystemPublishedDocumentEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns a simplified list of publication dates.
*
* @param int $applicationId
* @param int $limit
* @param int $offset
* @return array
*/
public function getFilesystemPublishedDocumentDateList(
int $applicationId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : array {
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemPublishedDocumentDateList',
[
':idApplication' => $applicationId,
':limit' => $limit,
':offset' => $offset
]
);
return $data ?? [];
}
/**
* Returns the tags for a filesystem record.
*
* @param int $filesystemId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemTagListByFilesystem(
int $filesystemId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemTagListByFilesystem',
[
':idFilesystem' => $filesystemId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemTagEntity::class, $data);
}
/**
* Returns the tags for an application.
*
* @param int $applicationId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemTagListByApplication(
int $applicationId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemTagListByApplication',
[
':idApplication' => $applicationId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemTagEntity::class, $data);
}
/**
* Returns filesystem tag information identified by (unique) ID.
*
* @param int $identifier
* @return null|FilesystemTagEntity
*/
public function getFilesystemTagById(int $identifier) : ? FilesystemTagEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemTagById',
[
':idTag' => $identifier
]
);
/** @var null|FilesystemTagEntity $entity */
$entity = $this->getEntity(FilesystemTagEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns filesystem tag information identified by (unique) ID.
*
* @param int $applicationId
* @param string $name
* @return null|FilesystemTagEntity
*/
public function getFilesystemTagByApplicationAndName(
int $applicationId,
string $name
) : ? FilesystemTagEntity {
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemTagByApplicationAndName',
[
':idApplication' => $applicationId,
':name' => $name
]
);
/** @var null|FilesystemTagEntity $entity */
$entity = $this->getEntity(FilesystemTagEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns the categories for an application.
*
* @param int $applicationId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getFilesystemCategoryListByApplication(
int $applicationId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemCategoryListByApplication',
[
':idApplication' => $applicationId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(FilesystemCategoryEntity::class, $data);
}
/**
* Returns filesystem category information identified by (unique) ID.
*
* @param int $identifier
* @return null|FilesystemCategoryEntity
*/
public function getFilesystemCategoryById(int $identifier) : ? FilesystemCategoryEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemCategoryById',
[
':idCategory' => $identifier
]
);
/** @var null|FilesystemCategoryEntity $entity */
$entity = $this->getEntity(FilesystemCategoryEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns filesystem category information identified by application ID and category name.
*
* @param int $applicationId
* @param string $categoryName
* @return null|FilesystemCategoryEntity
*/
public function getFilesystemCategoryByApplicationAndName(
int $applicationId,
string $categoryName
) : ? FilesystemCategoryEntity {
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemCategoryByApplicationAndName',
[
':idApplication' => $applicationId,
':categoryName' => $categoryName
]
);
/** @var null|FilesystemCategoryEntity $entity */
$entity = $this->getEntity(FilesystemCategoryEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns filesystem directory information identified by (unique) ID.
*
* @param int $identifier
* @return null|FilesystemDirectoryEntity
*/
public function getFilesystemDirectoryById(int $identifier) : ? FilesystemDirectoryEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemDirectoryById',
[
':idDirectory' => $identifier
]
);
/** @var null|FilesystemDirectoryEntity $entity */
$entity = $this->getEntity(FilesystemDirectoryEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns filesystem directory information identified by its proxy.
*
* @param string $proxy
* @return null|FilesystemDirectoryEntity
*/
public function getFilesystemDirectoryByProxy(string $proxy) : ? FilesystemDirectoryEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemDirectoryByProxy',
[
':proxy' => $proxy
]
);
/** @var null|FilesystemDirectoryEntity $entity */
$entity = $this->getEntity(FilesystemDirectoryEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns a combined information of the filesystem and directory according to the application and the proxy.
*
* @param int $applicationId
* @param string $proxy
* @return null|FilesystemDirectoryDataEntity
*/
public function getFilesystemDirectoryDataByApplicationAndProxy(
int $applicationId,
string $proxy
) : ? FilesystemDirectoryDataEntity {
$data = $this->getQueryAdapter()->fetchData(
'getFilesystemDirectoryDataByApplicationAndProxy',
[
':idApplication' => $applicationId,
':proxy' => $proxy
]
);
/** @var null|FilesystemDirectoryDataEntity $entity */
$entity = $this->getEntity(FilesystemDirectoryDataEntity::class, $data[0] ?? []);
return $entity;
}
}
<file_sep>/src/WebHemi/Middleware/Action/Admin/ControlPanel/Themes/DeleteAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Admin\ControlPanel\Themes;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class DeleteAction
*/
class DeleteAction extends AbstractMiddlewareAction
{
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-control-panel-themes-delete';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
return [];
}
}
<file_sep>/src/WebHemi/Renderer/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer;
use Psr\Http\Message\StreamInterface;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\I18n\ServiceInterface as I18nService;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param I18nService $i18nService
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
I18nService $i18nService
);
/**
* Renders the template for the output.
*
* @param string $template
* @param array $parameters
* @return StreamInterface
*/
public function render(string $template, array $parameters = []) : StreamInterface;
}
<file_sep>/config/settings/_global/session.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
return [
'session' => [
'namespace' => 'WebHemi',
'cookie_prefix' => 'atsn',
'session_name_salt' => 'Web<PASSWORD>',
'hash_function' => 'sha256',
'use_only_cookies' => true,
'use_cookies' => true,
'use_trans_sid' => false,
'cookie_http_only' => true,
'save_path' => __DIR__.'/../../../data/session/',
],
];
<file_sep>/src/WebHemi/Form/Preset/ApplicationEditForm.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form\Preset;
use WebHemi\Form\Element\Html\HtmlElement;
/**
* Class ApplicationEditForm
*
* @codeCoverageIgnore - only composes an object.
*/
class ApplicationEditForm extends AbstractPreset
{
/**
* Initialize the adapter
*/
protected function initAdapter()
{
$this->formAdapter->initialize('application', '[URL]/save', 'POST');
}
/**
* Initialize and add elements to the form.
*
* @return void
*
* @codeCoverageIgnore - only composes an object.
*/
protected function init() : void
{
$this->initAdapter();
$name = $this->createElement(
HtmlElement::class,
HtmlElement::HTML_ELEMENT_INPUT_TEXT,
'name',
'Application name'
);
$title = $this->createElement(
HtmlElement::class,
HtmlElement::HTML_ELEMENT_INPUT_TEXT,
'title',
'Display name (title)'
);
$description = $this->createElement(
HtmlElement::class,
HtmlElement::HTML_ELEMENT_TEXTAREA,
'description',
'Description'
);
$enabled = $this->createElement(
HtmlElement::class,
HtmlElement::HTML_ELEMENT_INPUT_CHECKBOX,
'is_enabled',
'Activated ?'
);
$submit = $this->createElement(
HtmlElement::class,
HtmlElement::HTML_ELEMENT_SUBMIT,
'submit',
'Save'
);
$this->formAdapter->addElement($name)
->addElement($title)
->addElement($description)
->addElement($enabled)
->addElement($submit);
}
}
<file_sep>/config/modules/_global/dependencies.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Acl;
use WebHemi\Application;
use WebHemi\Auth;
use WebHemi\Configuration;
use WebHemi\Data;
use WebHemi\DependencyInjection;
use WebHemi\Environment;
use WebHemi\Http;
use WebHemi\I18n;
use WebHemi\Logger;
use WebHemi\Middleware;
use WebHemi\MiddlewarePipeline;
use WebHemi\Parser;
use WebHemi\Renderer;
use WebHemi\Router;
use WebHemi\Session;
return [
'dependencies' => [
'Global' => [
// Core objects
Configuration\ServiceInterface::class => [
'class' => Configuration\ServiceAdapter\Base\ServiceAdapter::class,
],
DependencyInjection\ServiceInterface::class => [
'class' => DependencyInjection\ServiceAdapter\Base\ServiceAdapter::class,
],
Environment\ServiceInterface::class => [
'class' => Environment\ServiceAdapter\Base\ServiceAdapter::class,
],
MiddlewarePipeline\ServiceInterface::class => [
'class' => MiddlewarePipeline\ServiceAdapter\Base\ServiceAdapter::class,
],
Session\ServiceInterface::class => [
'class' => Session\ServiceAdapter\Base\ServiceAdapter::class,
],
Application\ServiceInterface::class => [
'class' => Application\ServiceAdapter\Base\ServiceAdapter::class,
'arguments' => [
DependencyInjection\ServiceInterface::class
],
'shared' => true,
],
// Services
Acl\ServiceInterface::class => [
'class' => Acl\ServiceAdapter\Base\ServiceAdapter::class,
'arguments' => [
Environment\ServiceInterface::class,
Data\Storage\UserStorage::class,
Data\Storage\PolicyStorage::class,
],
'shared' => true,
],
Auth\CredentialInterface::class => [
'class' => Auth\Credential\NameAndPasswordCredential::class,
'shared' => false,
],
Auth\ResultInterface::class => [
'class' => Auth\Result\Result::class,
'shared' => false,
],
Auth\ServiceInterface::class => [
'class' => Auth\ServiceAdapter\Base\ServiceAdapter::class,
'arguments' => [
Configuration\ServiceInterface::class,
Auth\ResultInterface::class,
Auth\StorageInterface::class,
Data\Storage\UserStorage::class,
],
'shared' => true,
],
Auth\StorageInterface::class => [
'class' => Auth\Storage\Session::class,
'arguments' => [
Session\ServiceInterface::class
],
'shared' => true,
],
Http\ServiceInterface::class => [
'class' => Http\ServiceAdapter\GuzzleHttp\ServiceAdapter::class,
'arguments' => [
Environment\ServiceInterface::class,
],
'shared' => true,
],
I18n\ServiceInterface::class => [
'class' => I18n\ServiceAdapter\Base\ServiceAdapter::class,
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class
],
'shared' => true,
],
I18n\DriverInterface::class => [
'class' => I18n\DriverAdapter\Gettext\DriverAdapter::class,
'arguments' => [
I18n\ServiceInterface::class
],
],
Parser\ServiceInterface::class => [
'class' => Parser\ServiceAdapter\Parsedown\ServiceAdapter::class,
'shared' => true,
],
Renderer\ServiceInterface::class => [
'class' => Renderer\ServiceAdapter\Twig\ServiceAdapter::class,
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class,
I18n\ServiceInterface::class
],
'shared' => true,
],
Router\ServiceInterface::class => [
'class' => Router\ServiceAdapter\Base\ServiceAdapter::class,
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class,
Router\Result\Result::class
],
'shared' => true,
],
// Logger
'AccessLog' => [
'class' => Logger\ServiceAdapter\Klogger\ServiceAdapter::class,
'arguments' => [
Configuration\ServiceInterface::class,
'logType' => 'access'
]
],
'EventLog' => [
'class' => Logger\ServiceAdapter\Klogger\ServiceAdapter::class,
'arguments' => [
Configuration\ServiceInterface::class,
'logType' => 'event'
]
],
// Middleware
Middleware\Common\RoutingMiddleware::class => [
'arguments' => [
Router\ServiceInterface::class,
]
],
Middleware\Common\DispatcherMiddleware::class => [
'arguments' => []
],
Middleware\Common\FinalMiddleware::class => [
'arguments' => [
Auth\ServiceInterface::class,
Environment\ServiceInterface::class,
'AccessLog'
]
],
// DataStorage
Data\Storage\ApplicationStorage::class => [
'arguments' => [
Data\Query\QueryInterface::class,
Data\Entity\EntitySet::class,
Data\Entity\ApplicationEntity::class
],
'shared' => true,
],
Data\Storage\UserStorage::class => [
'arguments' => [
Data\Query\QueryInterface::class,
Data\Entity\EntitySet::class,
Data\Entity\UserEntity::class,
Data\Entity\UserGroupEntity::class,
Data\Entity\UserMetaEntity::class
],
'shared' => true,
],
Data\Storage\PolicyStorage::class => [
'arguments' => [
Data\Query\QueryInterface::class,
Data\Entity\EntitySet::class,
Data\Entity\PolicyEntity::class,
],
'shared' => true,
],
Data\Storage\ResourceStorage::class => [
'arguments' => [
Data\Query\QueryInterface::class,
Data\Entity\EntitySet::class,
Data\Entity\ResourceEntity::class,
],
'shared' => true,
],
Data\Storage\FilesystemStorage::class => [
'arguments' => [
Data\Query\QueryInterface::class,
Data\Entity\EntitySet::class,
Data\Entity\FilesystemCategoryEntity::class,
Data\Entity\FilesystemDirectoryEntity::class,
Data\Entity\FilesystemDirectoryDataEntity::class,
Data\Entity\FilesystemDocumentEntity::class,
Data\Entity\FilesystemEntity::class,
Data\Entity\FilesystemMetaEntity::class,
Data\Entity\FilesystemPublishedDocumentEntity::class,
Data\Entity\FilesystemTagEntity::class,
],
'shared' => true,
],
// Renderer Filter
Renderer\Filter\MarkDownFilter::class => [
'arguments' => [
Parser\ServiceInterface::class
],
'shared' => true,
],
Renderer\Filter\TranslateFilter::class => [
'arguments' => [
I18n\DriverInterface::class
],
'shared' => true,
],
Renderer\Filter\Tags\Url::class => [
'arguments' => [
Environment\ServiceInterface::class
],
'shared' => true,
],
Renderer\Filter\TagParserFilter::class => [
'arguments' => [
Renderer\Filter\Tags\Url::class
],
'shared' => true,
],
// Renderer Helper
Renderer\Helper\DefinedHelper::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class
],
'shared' => true,
],
Renderer\Helper\FileExistsHelper::class => [
'arguments' => [
Environment\ServiceInterface::class
],
'shared' => true,
],
Renderer\Helper\GetStatHelper::class => [
'shared' => true,
],
Renderer\Helper\IsAllowedHelper::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class,
Acl\ServiceInterface::class,
Auth\ServiceInterface::class,
Data\Storage\ResourceStorage::class,
Data\Storage\ApplicationStorage::class
],
'shared' => true,
]
],
],
];
<file_sep>/src/WebHemi/Form/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form;
/**
* Interface ServiceInterface
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param string $name
* @param string $action
* @param string $method
*/
public function __construct(string $name = '', string $action = '', string $method = 'POST');
/**
* Initializes the form if it didn't happen in the constructor. (Used mostly in presets).
*
* @param string $name
* @param string $action
* @param string $method
* @return ServiceInterface
*/
public function initialize(string $name, string $action, string $method = 'POST') : ServiceInterface;
/**
* Gets form name.
*
* @return string
*/
public function getName() : string;
/**
* Gets form action.
*
* @return string
*/
public function getAction() : string;
/**
* Gets form method.
*
* @return string
*/
public function getMethod() : string;
/**
* Adds an element to the form.
*
* @param ElementInterface $formElement
* @return ServiceInterface
*/
public function addElement(ElementInterface $formElement) : ServiceInterface;
/**
* Returns an element
*
* @param string $elementName
* @return ElementInterface
*/
public function getElement(string $elementName) : ElementInterface;
/**
* Returns all the elements assigned.
*
* @return ElementInterface[]
*/
public function getElements() : array;
/**
* Loads data into the form.
*
* @param array $data
* @return ServiceInterface
*/
public function loadData(array $data) : ServiceInterface;
/**
* Validates the form.
*
* @return bool
*/
public function validate() : bool;
}
<file_sep>/CHANGELOG.md
# Change log #
## Version 4.0.0-6.1 ##
* Further code improvements: PHPStan now passes level 7
* Fix HTTP Client request parameters
* Minor fixes
## Version 4.0.0-6.0 ##
* Refactor the data module: rethink the way the PHP works in the end, and realize that it's absolutely no need for special
abstraction to build SQL queries, when I can build and test and use them by their own.
* No more database table representation: reduce complexity, improve readability,
* Easier configuration,
* Introduce query representation: each query is in their own `.sql` file, which can be executed by the IDE (like PHPStorm),
* Entities now reflects the results of the queries,
* Introduce EntitySet as a replace of a normal array of Entities.
* Improve code quality: PHPStan now passes level 2 (previous version passed only level 0).
* TODO: add unit tests for the new Data module.
## Version 4.0.0-5.3 ##
* Changes in rendering and output:
* Remove rendering from Dispatcher and Final Middleware. It's not their job.
* Add centralized rendering and output responsibility to the Application.
* Allow to send output without rendering.
* Fix Router and RouterProxy: it gave false status code for non-autoindex directories.
* Add initInternationalization() to Application to avoid translation errors when dealing with DateTime information before the rendering.
* Adopt unit tests for the new codes.
## Version 4.0.0-5.2 ##
* Replace the Symfony Dependency Injection Container with a WebHemi solution with keep the performance (speed) but reduce
the memory consumption
* Change copyright information to 2018
## Version 4.0.0-5.1 ##
* Refactor the Environment module to truely support multiple domains that points to the same document root.
* Add HTTP Clien module (just in case)
* Add FTP module (I have plans to use it)
* Add Mailer module
* TODO: I should really write some unit tests... It's the lowest coverage EVER :(
## Version 4.0.0-5.0 ##
* Huge improvement in codebase:
* Add Filesystem classes (DataStorage, DataEntity, Actions)
* Add final version of some helpers: GetCategoriesHelper, GetTagsHelper and GetDatesHelper
* Improvement in Router: finally found a solution how to handle dynamic content
* Get rid of FastRoute since it was unable to fulfill complex regular expressions like `^(?P<path>\/[\w\/\-]*\w)?\/(?P<basename>(?!index\..?html$)[\w\-]+\.[a-z0-9]{2,5})$`
* Develop a simple Router
* Introduce RouteProxy to handle dynamic contents
* Add/rename some database tables
* Extend database tables with new fields where they were necessary
* Update unit tests to work also with the new codes
## Version 4.0.0-4.6 ##
* Improvements in the default theme.
* Add I18n module:
* Service to set language, locale and timezone
* Driver to handle `.po` translations (currently only via the `gettext` PHP extension)
* The `WebHemi\DateTime` also uses the I18n module to get the correct date format
* Fix composer package versions to avoid errors upon accidental update.
* Increase unit test coverage.
* Minor fixes (documentation, typos etc.)
## Version 4.0.0-4.5 ##
* Add ValidatorInterface with basic validators:
* _NotEmptyValidator_ - to check if an element's value is empty (including the multi-select elements)
* _RangeValidator_ - to check if an element's value is within the range set up
## Version 4.0.0-4.4 ##
* Add support of CLI applications (e.g.: cronjobs)
* Fix config inheritance and Dependency Injection issues
* Typehints:
* Fix missing parameter typehints
* Fix typo issues
* Add better PHPDoc typehints (e.g.: in index.php)
* Update packages to fix Code Coverage issues
## Version 4.0.0-4.3 ##
* Add support for connecting to multiple databases
* Add support for service configuration inheritance
* Refactor the Dependency Injection Container Service:
* Add abstract class for the internal operation (init, resolve inheritance etc)
* Change the way of registering services and service instances
* The Symfony adapter implements only the library-specific methods
~~**NOTE: There's an issue with the PHPUnit Code Coverage: partially covers some array assignments**~~
## Version 4.0.0-4.2 ##
* Add Application function skeletons
* Add Control Panel categories
* Add Theme manager function skeletons
* A bit simplify the ACL: the policy has no use the isAllowed field, since if a policy is not defined for a resource, than that resource is not allowed to view...
## Version 4.0.0-4.1 ##
* Add support for form presets.
* Add Markdown parser and renderer filter.
* Minor fixes
## Version 4.0.0-4.0 ##
* I had an idea, so I refactored the whole WebHemi namespace:
* moved the adapters to their module's namespace,
* add `ServiceInterface` to almost every module,
* rename the adapters to `ServiceAdapter` and use namespace aliases,
* own solution for a module is moved under `<Module>\ServiceAdapter\Base` namespace.
* Made the `index.php` to be independent from the implementation: use `ServiceInterface` declarations for the core objects.
* Refactor the unit tests as well, but in the easiest possible way: change the `use` statements and used aliases.
* Update the README diagrams for a better and more precize overview.
* Minor fixes regarding to the refactor process.
## Version 4.0.0-3.3 ##
* Refactor UnitTests to PHPUnit 6.
* Add/fix unit tests, increase coverage.
* Refactor trait used by the renderer and helper:
* rename ThemeCheckTrait to GetSelectedThemeResourcePathTrait since that is what it does,
* hide properties and methods used by this trait from the descendant classes,
* make it to be independent of descendant classes (inject dependencies).
## Version 4.0.0-3.2 ##
* Restructure Config.
* Add WebHemi\Acl to be able to reuse validation.
* Add RendererFilterInterface and RendererHelperInterface.
* Make the renderer helpers and filters configurable.
* Refactor the TwigRendererAdapter and TwigExtension to use the renderer configuration.
* Add basic renderer helpers (getStat(), defined(file), isAllowed(url))
* Minor fixes in Auth-related codes.
* Add/fix unit tests. TODO: reach 100% coverage again.
## Version 4.0.0-3.1 ##
* Refactor the WebHemi\Data to PHP 7.1 and fix the Unit Tests.
* Add missing functionality of loading data back into the form after submit.
* Fix issues with WebHemi\Form.
* Add unit tests to WebHemi\Form.
## Version 4.0.0-3.0 ##
* Refactor almost the complete WebHemi namespace to PHP 7.1.
* Refactor the WebHemi\Form to be more simple but still be flexible (experimental) - TODO: Unit Tests needed.
* Refactor the WebHemi\Form view templates to let user take the render process into their hands.
* Introduce SQLiteDriver and SQLiteAdapter to be more proper in Unit Tests.
* Refactor Middleware classes to change Request and Response via parameter reference (no need return value).
* Fix codes with 'mixed' argument and return type to be more consistent where possible.
## Version 4.0.0-2.2 ##
* Create the [Docker Builder](https://github.com/Gixx/docker-builder) project to provide a PHP 7.1 dev environment:
* with nginx
* with https (self-signed)
* with PHP 7.1
* with MySQL 5.7
* Plan to refactor the codebase to PHP 7.1:
* will use strict type mode if possible
* will add parameter type hinting (try to eliminate "mixed" type),
* will add return types (also nullable),
* will refactor classes to use only interface declarations for parameters and return types.
## Version 4.0.0-2.1 ##
* Add AuthAdapterInterface.
* Add a very basic Auth adapter and ACL Middleware implementations.
* Refactor config structure and Application parameters.
* Solved to add core Services to the DI, so they can be injected into other services if needed.
## Version 4.0.0-2.0 ##
* Add brand new WebHemi\Form support
* Add Twig templates for generating semantic WebHemi\Form markup
* Solve Twig template inheritance (when no custom found use the default one)
* Minor fixes
* Move all continuous integration tools to Scrutinizer
## Version 4.0.0-1.2 ##
* Continue on cleaning up the configuration
* Clean up unnecessary Exception classes
* Http adapter:
* Extend Psr\Http\Message interfaces to link as less external resources as possible
* Standardize Request object attributes in the new (extended) Http interfaces
* Middleware Actions:
* Add new interface to be able to distinguish its instances form other middleware classes
* Add an AbstractMiddlewareAction class with finalized invoke method
* Routing:
* Fix issues with URLs without tailing slash
* Add ability of route config parameters (regex)
* Application:
* Finalize web application execution process (managing the pipeline)
* Add Unit test
* Unit Test:
* Add traits and new fixtures
* Follow up changes
## Version 4.0.0-1.1 ##
* Add RouterAdapter implemtation
* Add RendererAdapterInterface implementation
* Add Environment management
* Clean up configuration
* Add custom theme support
* Add application support for both sub-domain and sub-directory types
## Version 4.0.0-1.0 ##
* Plan, document and implement Middleware Pipeline system
* Define and implement base middleware classes: Routing-, Dispatcher-, FinalMiddleware
* Add InMemoryAdapter implementation
* Connect repository to Scrutinizer CI and improve code quality
* Add Unit tests, improve code coverage
* Minor changes in code
## Version 4.0.0-0.5 ##
* According to a [DI benchmark](https://github.com/TomBZombie/php-dependency-injection-benchmarks) switched to SymfonyDI
* Add ConfigInterface and implementation
* Add DependencyInjectionAdapterInterface implementation
* Add basic DI configuration
* Fix DataStorage::$dataGroup names
## Version 4.0.0-0.4 ##
* Applied code style changes suggested by StyleCI
* Fixed all PHP MD issues
* Fix filename typo issues
* Change the way of using the Entities
## Version 4.0.0-0.3 ##
* Add first/fake unit test
* Fix NPath complexity
## Version 4.0.0-0.2 ##
* Building basic application framework
* Define Interfaces
* Basic Implementations of some Interfaces
## Version 4.0.0-0.1 ##
* Initial commit
<file_sep>/tests/WebHemiTest/Data/Entity/EntitySetTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Throwable;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\EntitySet;
/**
* Class EntitySetTest
*/
class EntitySetTest extends TestCase
{
/**
* Tests the offsetExists
*/
public function testOffsetExists()
{
$entityA = new ApplicationEntity();
$entityA->setApplicationId(1);
$entitySet = new EntitySet();
$entitySet->offsetSet(1, $entityA);
$this->assertFalse($entitySet->offsetExists(0));
$this->assertTrue(isset($entitySet[1]));
try {
$result = isset($entitySet['index']);
unset($result);
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1000, $exception->getCode());
}
}
/**
* Tests the offsetGet
*/
public function testOffsetGet()
{
$entityA = new ApplicationEntity();
$entityA->setApplicationId(1);
$entitySet = new EntitySet();
$entitySet[] = $entityA;
$actualResult = $entitySet[0];
$this->assertTrue($entityA === $actualResult);
try {
$result = $entitySet['index'];
unset($result);
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1001, $exception->getCode());
}
}
/**
* Tests the offsetSet method
*/
public function testOffsetSet()
{
$entityA = new ApplicationEntity();
$entityA->setApplicationId(1);
$entityB = new ApplicationEntity();
$entityB->setApplicationId(2);
$entitySet = new EntitySet();
$entitySet->offsetSet(0, $entityA);
$entitySet[] = $entityB;
try {
$entitySet->offsetSet('index', $entityA);
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1002, $exception->getCode());
}
try {
$entitySet[] = 'test text';
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1003, $exception->getCode());
}
}
/**
* Tests the offsetUnset method
*/
public function testOffsetUnset()
{
$entityA = new ApplicationEntity();
$entityA->setApplicationId(1);
$entityB = new ApplicationEntity();
$entityB->setApplicationId(2);
$entitySet = new EntitySet();
$entitySet->offsetSet(0, $entityA);
$entitySet[] = $entityB;
$this->assertTrue(isset($entitySet[1]));
$entitySet->offsetUnset(1);
$this->assertFalse(isset($entitySet[1]));
$this->assertFalse(isset($entitySet[100]));
unset($entitySet[100]);
try {
unset($entitySet['cat']);
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1004, $exception->getCode());
}
}
/**
* Tests the key method
*/
public function testKey()
{
$entityA = new ApplicationEntity();
$entityA->setApplicationId(1);
$entityB = new ApplicationEntity();
$entityB->setApplicationId(2);
$entitySet = new EntitySet();
$entitySet->offsetSet(0, $entityA);
$entitySet[] = $entityB;
foreach ($entitySet as $index => $data) {
$this->assertTrue(is_int($index));
$this->assertInstanceOf(ApplicationEntity::class, $data);
}
}
/**
* Tests the toArray and merge methods
*/
public function testArray()
{
$entityA = new ApplicationEntity();
$entityA->setApplicationId(1);
$entityB = new ApplicationEntity();
$entityB->setApplicationId(2);
$entityC = new ApplicationEntity();
$entityC->setApplicationId(3);
$entityD = new ApplicationEntity();
$entityD->setApplicationId(4);
$entitySetA = new EntitySet();
$entitySetA[] = $entityA;
$entitySetA[] = $entityB;
$entitySetB = new EntitySet();
$entitySetB[] = $entityC;
$entitySetB[] = $entityD;
$entitySetA->merge($entitySetB);
$actualArray = $entitySetA->toArray();
$expectedArray = [
$entityA,
$entityB,
$entityC,
$entityD
];
$this->assertSame(count($actualArray), count($expectedArray));
foreach ($actualArray as $index => $actualEntity) {
$actual = var_export($actualEntity, true);
$expected = var_export($expectedArray[$index], true);
$this->assertSame($actual, $expected);
}
}
}
<file_sep>/src/WebHemi/Data/Storage/PolicyStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\PolicyEntity;
use WebHemi\Data\Query\QueryInterface;
/**
* Class PolicyStorage.
*/
class PolicyStorage extends AbstractStorage
{
/**
* Returns a full set of policy data.
*
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getPolicyList(
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getPolicyList',
[
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(PolicyEntity::class, $data);
}
/**
* Returns a set of policy data identified by resource ID.
*
* @param int $resourceId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getPolicyListByResource(
int $resourceId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getPolicyListByResource',
[
':idResource' => $resourceId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(PolicyEntity::class, $data);
}
/**
* Returns a set of policy data identified by application ID.
*
* @param int $applicationId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getPolicyListByApplication(
int $applicationId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getPolicyListByApplication',
[
':idApplication' => $applicationId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(PolicyEntity::class, $data);
}
/**
* Returns a set of policy data identified by user ID.
*
* @param int $userId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getPolicyListByUser(
int $userId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getPolicyListByUser',
[
':idUser' => $userId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(PolicyEntity::class, $data);
}
/**
* Returns a set of policy data identified by user group ID.
*
* @param int $userGroupId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getPolicyListByUserGroup(
int $userGroupId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getPolicyListByUserGroup',
[
':idUserGroup' => $userGroupId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(PolicyEntity::class, $data);
}
/**
* Returns a set of policy data identified by both resource and application IDs.
*
* @param int $resourceId
* @param int $applicationId
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getPolicyListByResourceAndApplication(
int $resourceId,
int $applicationId,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getPolicyListByResourceAndApplication',
[
':idResource' => $resourceId,
':idApplication' => $applicationId,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(PolicyEntity::class, $data);
}
/**
* Returns policy data identified by (unique) ID.
*
* @param int $identifier
* @return null|PolicyEntity
*/
public function getPolicyById(int $identifier) : ? PolicyEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getPolicyById',
[
':idPolicy' => $identifier
]
);
/** @var null|PolicyEntity $entity */
$entity = $this->getEntity(PolicyEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns policy data by name.
*
* @param string $name
* @return null|PolicyEntity
*/
public function getPolicyByName(string $name) : ? PolicyEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getPolicyByName',
[
':name' => $name
]
);
/** @var null|PolicyEntity $entity */
$entity = $this->getEntity(PolicyEntity::class, $data[0] ?? []);
return $entity;
}
}
<file_sep>/src/WebHemi/Renderer/Traits/GetSelectedThemeResourcePathTrait.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Traits;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
/**
* Class GetSelectedThemeResourcePathTrait
*/
trait GetSelectedThemeResourcePathTrait
{
/**
* @var EnvironmentInterface
*/
private $environment;
/**
* @var ConfigurationInterface
*/
private $themeConfig;
/**
* Checks if the selected theme supports the current state and returns the correct resource path.
*
* @param string $selectedTheme
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @return string
*/
protected function getSelectedThemeResourcePath(
string&$selectedTheme,
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager
) : string {
$this->environment = $environmentManager;
//$selectedTheme = $this->environment->getSelectedTheme();
$selectedThemeResourcePath = $this->environment->getResourcePath();
// Reset selected theme, if it's not found.
if (!$configuration->has('themes/'.$selectedTheme)) {
$selectedTheme = EnvironmentInterface::DEFAULT_THEME;
$selectedThemeResourcePath = EnvironmentInterface::DEFAULT_THEME_RESOURCE_PATH;
}
// Temporary, only can access by this trait.
$this->themeConfig = $configuration->getConfig('themes/'.$selectedTheme);
// Reset selected theme, if it doesn't support the currenct application/page.
if (!$this->checkSelectedThemeFeatures()) {
$selectedTheme = EnvironmentInterface::DEFAULT_THEME;
$selectedThemeResourcePath = EnvironmentInterface::DEFAULT_THEME_RESOURCE_PATH;
}
return $selectedThemeResourcePath;
}
/**
* Checks if the selected theme can be used with the current application.
*
* @return bool
*/
private function checkSelectedThemeFeatures() : bool
{
$canUseThisTheme = true;
// check the theme settings
// If no theme support for the application, then use the default theme
if (($this->isAdminApplication() && !$this->isFeatureSupported('admin'))
|| ($this->isAdminLoginPage() && !$this->isFeatureSupported('admin_login'))
|| ($this->isWebsiteApplication() && !$this->isFeatureSupported('website'))
) {
$canUseThisTheme = false;
}
return $canUseThisTheme;
}
/**
* Checks whether the current application belongs to the Admin module and the request calls the login page.
*
* @return bool
*/
private function isAdminLoginPage() : bool
{
return strpos($this->environment->getRequestUri(), '/auth/login') !== false;
}
/**
* Checks whether the current application belongs to the Admin module or not.
*
* @return bool
*/
private function isAdminApplication() : bool
{
return !$this->isAdminLoginPage() && 'Admin' == $this->environment->getSelectedModule();
}
/**
* Checks whether the current application belongs to any Website module application.
*
* @return bool
*/
private function isWebsiteApplication() : bool
{
return 'Website' == $this->environment->getSelectedModule();
}
/**
* Checks the config for feature settings.
*
* @param string $feature
* @return bool
*/
private function isFeatureSupported(string $feature) : bool
{
return $this->themeConfig->has('features/'.$feature.'_support')
&& (bool) $this->themeConfig->getData('features/'.$feature.'_support')[0];
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemPublishedDocumentDateList.sql
SELECT
fs.`date_published`,
COUNT(*) AS number_of_publications
FROM
`webhemi_filesystem` AS fs
WHERE
fs.`fk_application` = :idApplication AND
fs.`fk_filesystem_document` IS NOT NULL AND
fs.`is_hidden` = 0 AND
fs.`is_deleted` = 0 AND
fs.`date_published` IS NOT NULL
GROUP BY
YEAR(fs.`date_published`),
MONTH(fs.`date_published`)
ORDER BY
fs.`date_published` DESC
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Data/Entity/FilesystemTagEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemTagEntity
*/
class FilesystemTagEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_filesystem_tag' => null,
'fk_application' => null,
'name' => null,
'title' => null,
'description' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return FilesystemTagEntity
*/
public function setFilesystemTagId(int $identifier) : FilesystemTagEntity
{
$this->container['id_filesystem_tag'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemTagId() : ? int
{
return !is_null($this->container['id_filesystem_tag'])
? (int) $this->container['id_filesystem_tag']
: null;
}
/**
* @param int $applicationIdentifier
* @return FilesystemTagEntity
*/
public function setApplicationId(int $applicationIdentifier) : FilesystemTagEntity
{
$this->container['fk_application'] = $applicationIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getApplicationId() : ? int
{
return !is_null($this->container['fk_application'])
? (int) $this->container['fk_application']
: null;
}
/**
* @param string $name
* @return FilesystemTagEntity
*/
public function setName(string $name) : FilesystemTagEntity
{
$this->container['name'] = $name;
return $this;
}
/**
* @return null|string
*/
public function getName() : ? string
{
return $this->container['name'];
}
/**
* @param string $title
* @return FilesystemTagEntity
*/
public function setTitle(string $title) : FilesystemTagEntity
{
$this->container['title'] = $title;
return $this;
}
/**
* @return null|string
*/
public function getTitle() : ? string
{
return $this->container['title'];
}
/**
* @param string $description
* @return FilesystemTagEntity
*/
public function setDescription(string $description) : FilesystemTagEntity
{
$this->container['description'] = $description;
return $this;
}
/**
* @return null|string
*/
public function getDescription() : ? string
{
return $this->container['description'];
}
/**
* @param DateTime $dateTime
* @return FilesystemTagEntity
*/
public function setDateCreated(DateTime $dateTime) : FilesystemTagEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return FilesystemTagEntity
*/
public function setDateModified(DateTime $dateTime) : FilesystemTagEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/tests/WebHemiTest/Data/Entity/FilesystemEntityTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use WebHemi\Data\Entity\FilesystemEntity;
use WebHemi\DateTime;
/**
* Class FilesystemEntityTest
*/
class FilesystemEntityTest extends AbstractEntityTestCase
{
/** @var array */
protected $testData = [
'id_filesystem' => 1,
'fk_application' => 1,
'fk_category' => 1,
'fk_parent_node' => 1,
'fk_filesystem_document' => 1,
'fk_filesystem_file' => 1,
'fk_filesystem_directory' => 1,
'fk_filesystem_link' => 1,
'path' => 'test path',
'basename' => 'test basename',
'uri' => 'test uri',
'title' => 'test title',
'description' => 'test description',
'is_hidden' => 0,
'is_read_only' => 1,
'is_deleted' => 0,
'date_created' => '2016-04-26 23:21:19',
'date_modified' => '2016-04-26 23:21:19',
'date_published' => '2016-04-26 23:21:19',
];
/** @var array */
protected $expectedGetters = [
'getFilesystemId' => 1,
'getApplicationId' => 1,
'getCategoryId' => 1,
'getParentNodeId' => 1,
'getFilesystemDocumentId' => 1,
'getFilesystemFileId' => 1,
'getFilesystemDirectoryId' => 1,
'getFilesystemLinkId' => 1,
'getPath' => 'test path',
'getBaseName' => 'test basename',
'getUri' => 'test uri',
'getTitle' => 'test title',
'getDescription' => 'test description',
'getIsHidden' => false,
'getIsReadOnly' => true,
'getIsDeleted' => false,
'getDateCreated' => null,
'getDateModified' => null,
'getDatePublished' => null,
];
/** @var array */
protected $expectedSetters = [
'setFilesystemId' => 1,
'setApplicationId' => 1,
'setCategoryId' => 1,
'setParentNodeId' => 1,
'setFilesystemDocumentId' => 1,
'setFilesystemFileId' => 1,
'setFilesystemDirectoryId' => 1,
'setFilesystemLinkId' => 1,
'setPath' => 'test path',
'setBaseName' => 'test basename',
'setUri' => 'test uri',
'setTitle' => 'test title',
'setDescription' => 'test description',
'setIsHidden' => false,
'setIsReadOnly' => true,
'setIsDeleted' => false,
'setDateCreated' => null,
'setDateModified' => null,
'setDatePublished' => null,
];
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$dateTime = new DateTime('2016-04-26 23:21:19');
$this->expectedGetters['getDateCreated'] = $dateTime;
$this->expectedGetters['getDateModified'] = $dateTime;
$this->expectedGetters['getDatePublished'] = $dateTime;
$this->expectedSetters['setDateCreated'] = $dateTime;
$this->expectedSetters['setDateModified'] = $dateTime;
$this->expectedSetters['setDatePublished'] = $dateTime;
$this->entity = new FilesystemEntity();
}
/**
* Data provider for the testGetType();
*
* @return array
*/
public function dataProvider()
{
return [
[null, null, null, null, FilesystemEntity::TYPE_DOCUMENT],
[1, null, null, null, FilesystemEntity::TYPE_DOCUMENT],
[null, 1, null, null, FilesystemEntity::TYPE_BINARY],
[23, 3, null, null, FilesystemEntity::TYPE_BINARY],
[null, 43, 32, null, FilesystemEntity::TYPE_BINARY],
[null, 325, null, 543, FilesystemEntity::TYPE_BINARY],
[3, 45, 343, null, FilesystemEntity::TYPE_BINARY],
[78, 23, null, 2356, FilesystemEntity::TYPE_BINARY],
[23, 88, 463, 5345, FilesystemEntity::TYPE_BINARY],
[null, null, 1, null, FilesystemEntity::TYPE_DIRECTORY],
[1, null, 4, null, FilesystemEntity::TYPE_DIRECTORY],
[null, null, 4, 2, FilesystemEntity::TYPE_DIRECTORY],
[2, null, 567, 32, FilesystemEntity::TYPE_DIRECTORY],
[null, null, null, 3, FilesystemEntity::TYPE_SYMLINK],
[2, null, null, 32, FilesystemEntity::TYPE_SYMLINK],
];
}
/**
* Tests the getType method
*
* @param null|int $docId
* @param null|int $fileId
* @param null|int $dirId
* @param null|int $linkId
* @param string $expectedResult
*
* @dataProvider dataProvider
*/
public function testGetType($docId, $fileId, $dirId, $linkId, $expectedResult)
{
$this->testData['fk_filesystem_document'] = $docId;
$this->testData['fk_filesystem_file'] = $fileId;
$this->testData['fk_filesystem_directory'] = $dirId;
$this->testData['fk_filesystem_link'] = $linkId;
$entity = new FilesystemEntity();
$entity->fromArray($this->testData);
$this->assertSame($expectedResult, $entity->getType());
}
}
<file_sep>/src/WebHemi/Http/ResponseInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
/**
* Interface ResponseInterface.
*/
interface ResponseInterface extends PsrResponseInterface
{
public const STATUS_PROCESSING = 102;
public const STATUS_OK = 200;
public const STATUS_REDIRECT = 302;
public const STATUS_BAD_REQUEST = 400;
public const STATUS_UNAUTHORIZED = 401;
public const STATUS_FORBIDDEN = 403;
public const STATUS_NOT_FOUND = 404;
public const STATUS_BAD_METHOD = 405;
public const STATUS_INTERNAL_SERVER_ERROR = 500;
public const STATUS_NOT_IMPLEMENTED = 501;
}
<file_sep>/src/WebHemi/Data/Query/MySQL/QueryAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Query\MySQL;
use InvalidArgumentException;
use PDO;
use RuntimeException;
use WebHemi\Data\Driver\DriverInterface;
use WebHemi\Data\Driver\PDO\MySQL\DriverAdapter as SQLDriverAdapter;
use WebHemi\Data\Query\QueryInterface;
/**
* Class QueryAdapter
*/
class QueryAdapter implements QueryInterface
{
/**
* @var DriverInterface
*/
protected $driverAdapter;
/**
* @var array
*/
protected $identifierList;
/**
* @var string
*/
protected static $statementPath = __DIR__.'/../MySQL/statements/*.sql';
/**
* QueryInterface constructor.
*
* @param DriverInterface $driverAdapter
*/
public function __construct(DriverInterface $driverAdapter)
{
$this->driverAdapter = $driverAdapter;
$this->init();
}
/**
* Collects all the valid statements.
*/
protected function init() : void
{
$this->identifierList = [];
$statementFiles = glob(static::$statementPath, GLOB_BRACE);
foreach ($statementFiles as $file) {
$this->identifierList[basename($file, '.sql')] = $file;
}
}
/**
* Returns the Data Driver instance.
*
* @return DriverInterface
*/
public function getDriver() : DriverInterface
{
return $this->driverAdapter;
}
/**
* Fetches data buy executing a query identified by ID.
*
* @param string $query
* @param array $parameters
* @throws InvalidArgumentException
* @throws RuntimeException
* @return array
*/
public function fetchData(string $query, array $parameters = []) : array
{
if (isset($this->identifierList[$query])) {
$query = file_get_contents($this->identifierList[$query]);
}
// This nasty trick helps us to be able to parameterize the ORDER BY statement.
if (isset($parameters[':orderBy'])) {
$orderBy = $parameters[':orderBy'];
unset($parameters[':orderBy']);
$query = str_replace(':orderBy', $orderBy, $query);
}
/** @var SQLDriverAdapter $driver */
$driver = $this->getDriver();
$statement = $driver->prepare($query);
foreach ($parameters as $parameter => $value) {
$statement->bindValue($parameter, $value, $this->getValueType($value));
}
try {
$executedSuccessful = $statement->execute();
} catch (\Throwable $exception) {
throw new RuntimeException(
sprintf('Error executing query for "%s". %s', $query, $exception->getMessage()),
1000
);
}
if (!$executedSuccessful) {
throw new RuntimeException(
sprintf('Error running query: "%s"', $query),
1001
);
}
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
/**
* Returns the PDO type of the value.
*
* @param mixed $value
* @return int
*/
protected function getValueType($value) : int
{
$type = PDO::PARAM_STR;
if (is_numeric($value)) {
$type = PDO::PARAM_INT;
} elseif (is_null($value)) {
$type = PDO::PARAM_NULL;
} elseif (is_bool($value)) {
$type = PDO::PARAM_BOOL;
}
return $type;
}
}
<file_sep>/tests/WebHemiTest/Auth/SessionStorageTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Auth;
use WebHemi\Session\ServiceAdapter\Base\ServiceAdapter as SessionManager;
use WebHemi\Auth\Storage\Session as SessionStorage;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Data\Entity\UserEntity;
use PHPUnit\Framework\TestCase;
/**
* Class SessionStorageTest
*/
class SessionStorageTest extends TestCase
{
/** @var array */
private $config;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
}
/**
* Test storage
*/
public function testStorage()
{
$config = new Config($this->config);
$sessionManager = new SessionManager($config);
$userEntity = new UserEntity();
$storage = new SessionStorage($sessionManager);
$this->assertFalse($storage->hasIdentity());
$this->assertEmpty($storage->getIdentity());
$storage->setIdentity($userEntity);
$this->assertTrue($storage->hasIdentity());
$this->assertTrue($userEntity === $storage->getIdentity());
$storage->clearIdentity();
$this->assertEmpty($storage->getIdentity());
}
}
<file_sep>/tests/WebHemiTest/Form/HtmlFormTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Form;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use RuntimeException;
use WebHemi\Form\ElementInterface as FormElementInterface;
use WebHemi\Form\ServiceInterface as FormInterface;
use WebHemi\Form\ServiceAdapter\Base\ServiceAdapter as HtmlForm;
use WebHemi\Form\Element\Html\HtmlElement as HtmlFormElement;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestService\TestFalseValidator;
use WebHemiTest\TestService\TestTrueValidator;
/**
* Class FormTest
*/
class HtmlFormTest extends TestCase
{
use AssertTrait;
/**
* Tests HtmlForm constructor.
*/
public function testConstructor()
{
$name = 'someForm';
$action = 'some/action';
$form = new HtmlForm($name, $action);
$this->assertInstanceOf(FormInterface::class, $form);
$this->assertAttributeEquals($name, 'name', $form);
$this->assertAttributeEquals($action, 'action', $form);
$this->assertAttributeEquals('POST', 'method', $form);
$form = new HtmlForm($name, $action, 'GET');
$this->assertAttributeEquals('GET', 'method', $form);
}
/**
* Tests the initialize method.
*/
public function testInit()
{
$name = 'someForm';
$action = 'some/action';
$method = 'GET';
$form = new HtmlForm();
$this->assertInstanceOf(FormInterface::class, $form);
$this->assertAttributeEmpty('name', $form);
$this->assertAttributeEmpty('action', $form);
$this->assertAttributeEquals('POST', 'method', $form);
$form->initialize($name, $action, $method);
$this->assertAttributeEquals($name, 'name', $form);
$this->assertAttributeEquals($action, 'action', $form);
$this->assertAttributeEquals($method, 'method', $form);
$this->expectException(RuntimeException::class);
$form->initialize($name, $action, $method);
}
/**
* Tests HtmlForm getter methods.
*/
public function testGetters()
{
$name = 'someForm';
$action = 'some/action';
$form = new HtmlForm($name, $action);
$this->assertSame($name, $form->getName());
$this->assertSame($action, $form->getAction());
$this->assertSame('POST', $form->getMethod());
$this->assertEmpty($form->getElements());
$this->assertInternalType('array', $form->getElements());
}
/**
* Tests addElement method.
*/
public function testAddElement()
{
$name = 'someForm';
$action = 'some/action';
$form = new HtmlForm($name, $action);
$this->assertEmpty($form->getElements());
$element = $this->prophesize(FormElementInterface::class);
$element->getName()->willReturn('some_element');
$element->setName(Argument::type('string'))->willReturn($element->reveal());
/** @var FormElementInterface $elementInstance */
$elementInstance = $element->reveal();
$form->addElement($elementInstance);
$elements = $form->getElements();
$this->assertNotEmpty($elements);
$this->assertSame(1, count($elements));
$expectedName = $name.'[some_element]';
$this->assertTrue(isset($elements[$expectedName]));
$this->assertInstanceOf(FormElementInterface::class, $elements[$expectedName]);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionCode(1001);
$form->addElement($elementInstance);
}
/**
* Tests getElement method.
*/
public function testGetElement()
{
$name = 'someForm';
$action = 'some/action';
$form = new HtmlForm($name, $action);
$this->assertEmpty($form->getElements());
$element = $this->prophesize(FormElementInterface::class);
$element->getName()->willReturn('some_element');
$element->setName(Argument::type('string'))->willReturn($element->reveal());
/** @var FormElementInterface $elementInstance */
$elementInstance = $element->reveal();
$form->addElement($elementInstance);
$actualElement = $form->getElement('some_element');
$this->assertTrue($elementInstance === $actualElement);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionCode(1002);
$form->getElement('non_existing');
}
/**
* Tests loadData() method.
*/
public function testLoadData()
{
$name = 'someForm';
$action = 'some/action';
$form = new HtmlForm($name, $action);
$element1Instance = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'some_data');
$element2Instance = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'some_other_data');
$form->addElement($element1Instance)
->addElement($element2Instance);
$data1 = [];
$expectedJsonArrray = [
'name' => 'someForm',
'action' => 'some/action',
'method' => 'POST',
'data' => [
'id_some_form_some_data' => [],
'id_some_form_some_other_data' => []
],
'errors' => []
];
$data2 = [
'someForm' => [
'some_data' => 1,
'some_other_data' => [
'deep_index' => 2
],
'non_existing_data' => 'do not care'
]
];
$form->loadData($data1);
$elements = $form->getElements();
$this->assertEmpty($elements['someForm[some_data]']->getValues());
$this->assertEmpty($elements['someForm[some_other_data]']->getValues());
$this->assertSame(json_encode($expectedJsonArrray), json_encode($form));
$this->assertSame($expectedJsonArrray, $form->jsonSerialize());
$form->loadData($data2);
$elements = $form->getElements();
$this->assertArraysAreSimilar([1], $elements['someForm[some_data]']->getValues());
$this->assertArraysAreSimilar(['deep_index' => 2], $elements['someForm[some_other_data]']->getValues());
}
/**
* Tests the validate() method.
*/
public function testValidator()
{
$name = 'someForm';
$action = 'some/action';
$form = new HtmlForm($name, $action);
$trueValidator = new TestTrueValidator();
$falseValidator = new TestFalseValidator();
// Add element with validator
$firstElementInstance = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'some_data_1');
$firstElementInstance->addValidator($trueValidator);
$form->addElement($firstElementInstance);
$validateResult = $form->validate();
$this->assertTrue($validateResult);
// Add element without validator
$secondElementInstance = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'some_data_2');
$form->addElement($secondElementInstance);
$validateResult = $form->validate();
$this->assertTrue($validateResult);
// Add element with validator that will fail
$thirdElementInstance = new HtmlFormElement(HtmlFormElement::HTML_ELEMENT_INPUT_TEXT, 'some_data_3');
$thirdElementInstance->addValidator($falseValidator);
$form->addElement($thirdElementInstance);
$validateResult = $form->validate();
$this->assertFalse($validateResult);
}
}
<file_sep>/src/WebHemi/Auth/StorageInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth;
use WebHemi\Data\Entity\UserEntity;
/**
* Interface StorageInterface.
*/
interface StorageInterface
{
/**
* Sets the authenticated user.
*
* @param UserEntity $dataEntity
* @return StorageInterface
*/
public function setIdentity(UserEntity $dataEntity) : StorageInterface;
/**
* Checks if there is any authenticated user.
*
* @return bool
*/
public function hasIdentity() : bool;
/**
* Gets the authenticated user.
*
* @return UserEntity|null
*/
public function getIdentity() : ? UserEntity;
/**
* Clears the storage.
*
* @return StorageInterface
*/
public function clearIdentity() : StorageInterface;
}
<file_sep>/src/WebHemi/Http/ServiceAdapter/GuzzleHttp/Client.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http\ServiceAdapter\GuzzleHttp;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
use WebHemi\Http\ClientInterface;
/**
* Class HttpClient
*
* @codeCoverageIgnore - don't test third party library until this only a forwards the calls.
*/
class Client implements ClientInterface
{
/**
* @var GuzzleClient
*/
private $guzzleClient;
/**
* HttpClient constructor.
*/
public function __construct()
{
$this->guzzleClient = new GuzzleClient();
}
/**
* Get data.
*
* @param string $url
* @param array $data
* @return PsrResponseInterface
*/
public function get(string $url, array $data) : PsrResponseInterface
{
$queryData = empty($data)
? []
: [
'query' => $data
];
return $this->request('GET', $url, $queryData);
}
/**
* Posts data.
*
* @param string $url
* @param array $data
* @return PsrResponseInterface
*/
public function post(string $url, array $data) : PsrResponseInterface
{
$formData = [];
if (!empty($data)) {
$formData['multipart'] = [];
foreach ($data as $key => $value) {
$formData['multipart'][] = [
'name' => (string) $key,
'contents' => (string) $value
];
}
}
return $this->request('POST', $url, $formData);
}
/**
* Request an URL with data.
*
* @param string $method
* @param string $url
* @param array $options
* @return PsrResponseInterface
*/
private function request(string $method, string $url, array $options) : PsrResponseInterface
{
try {
$response = $this->guzzleClient->request($method, $url, $options);
} catch (RequestException $exception) {
$response = $exception->getResponse();
}
return $response;
}
}
<file_sep>/src/WebHemi/Middleware/Action/Website/Directory/UserAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Website\Directory;
use RuntimeException;
use WebHemi\Data\Entity;
use WebHemi\Middleware\Action\Website\IndexAction;
/**
* Class UserAction
*/
class UserAction extends IndexAction
{
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'website-user';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$blogPosts = [];
$parameters = $this->getRoutingParameters();
$userName = $parameters['basename'] ?? '';
if ($parameters['path'] == '/' || empty($userName)) {
throw new RuntimeException('Forbidden', 403);
}
/**
* @var Entity\UserEntity $userEntity
*/
$userEntity = $this->getUserStorage()
->getUserByUserName($userName);
/**
* @var array $userMeta
*/
$userMeta = $this->getUserStorage()
->getSimpleUserMetaListByUser((int) $userEntity->getUserId());
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->getApplicationStorage()
->getApplicationByName($this->environmentManager->getSelectedApplication());
/**
* @var Entity\EntitySet $publications
*/
$publications = $this->getFilesystemStorage()
->getFilesystemPublishedDocumentListByAuthor(
(int) $applicationEntity->getApplicationId(),
(int) $userEntity->getUserId()
);
/**
* @var Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
*/
foreach ($publications as $publishedDocumentEntity) {
$blogPosts[] = $this->getBlobPostData($applicationEntity, $publishedDocumentEntity);
}
return [
'activeMenu' => '',
'user' => [
'userId' => $userEntity->getUserId(),
'userName' => $userEntity->getUserName(),
'url' => $this->environmentManager->getRequestUri(),
'meta' => $userMeta,
],
'application' => $this->getApplicationData($applicationEntity),
'blogPosts' => $blogPosts,
];
}
}
<file_sep>/tests/WebHemiTest/Auth/AuthServiceTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Auth;
use Prophecy\Argument;
use WebHemi\Auth\ServiceInterface as AuthAdapterInterface;
use WebHemi\Auth\StorageInterface as AuthStorageInterface;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Query\QueryInterface as DataAdapterInterface;
use WebHemi\Auth\Result\Result;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\StorageInterface as DataStorageInterface;
use WebHemiTest\TestService\EmptyAuthAdapter;
use WebHemiTest\TestService\EmptyAuthStorage;
use WebHemiTest\TestService\EmptyCredential;
use WebHemiTest\TestService\EmptyEntity;
use WebHemiTest\TestService\EmptyUserStorage;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use PHPUnit\Framework\TestCase;
/**
* Class AuthServiceTest
*/
class AuthServiceTest extends TestCase
{
/** @var array */
private $config;
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
}
/**
* Tests class constructor.
*/
public function testConstructor()
{
$defaultAdapter = $this->prophesize(DataAdapterInterface::class);
/** @var DataAdapterInterface $defaultAdapterInstance */
$defaultAdapterInstance = $defaultAdapter->reveal();
$config = new Config($this->config);
$result = new Result();
$authStorage = new EmptyAuthStorage();
$dataEntity = new EmptyEntity();
$entitySet = new EntitySet();
$dataStorage = new EmptyUserStorage($defaultAdapterInstance, $entitySet, $dataEntity);
$adapter = new EmptyAuthAdapter(
$config,
$result,
$authStorage,
$dataStorage
);
$this->assertInstanceOf(AuthAdapterInterface::class, $adapter);
$actualObject = $this->invokePrivateMethod($adapter, 'getAuthStorage', []);
$this->assertInstanceOf(AuthStorageInterface::class, $actualObject);
$actualObject = $this->invokePrivateMethod($adapter, 'getDataStorage', []);
$this->assertInstanceOf(DataStorageInterface::class, $actualObject);
$actualObject = $this->invokePrivateMethod($adapter, 'getNewAuthResultInstance', []);
$this->assertInstanceOf(Result::class, $actualObject);
$this->assertFalse($result === $actualObject);
}
/**
* Tests authentication.
*/
public function testAuthenticate()
{
$defaultAdapter = $this->prophesize(DataAdapterInterface::class);
/** @var DataAdapterInterface $defaultAdapterInstance */
$defaultAdapterInstance = $defaultAdapter->reveal();
$config = new Config($this->config);
$result = new Result();
$authStorage = new EmptyAuthStorage();
$dataEntity = new UserEntity();
$entitySet = new EntitySet();
$dataStorage = new EmptyUserStorage($defaultAdapterInstance, $entitySet, $dataEntity);
$adapter = new EmptyAuthAdapter(
$config,
$result,
$authStorage,
$dataStorage
);
$this->assertFalse($adapter->hasIdentity());
$this->assertNull($adapter->getIdentity());
$emptyCredential = new EmptyCredential();
$emptyCredential->setCredential('authResultShouldBe', Result::FAILURE_OTHER);
$result = $adapter->authenticate($emptyCredential);
$this->assertSame(Result::FAILURE_OTHER, $result->getCode());
$this->assertNull($adapter->getIdentity());
$this->assertNotEmpty($result->getMessage());
$emptyCredential->setCredential('authResultShouldBe', Result::FAILURE_CREDENTIAL_INVALID);
$result = $adapter->authenticate($emptyCredential);
$this->assertSame(Result::FAILURE_CREDENTIAL_INVALID, $result->getCode());
$this->assertNull($adapter->getIdentity());
$this->assertNotEmpty($result->getMessage());
$emptyCredential->setCredential('authResultShouldBe', Result::FAILURE_IDENTITY_NOT_FOUND);
$result = $adapter->authenticate($emptyCredential);
$this->assertSame(Result::FAILURE_IDENTITY_NOT_FOUND, $result->getCode());
$this->assertNull($adapter->getIdentity());
$this->assertNotEmpty($result->getMessage());
$emptyCredential->setCredential('authResultShouldBe', Result::FAILURE);
$result = $adapter->authenticate($emptyCredential);
$this->assertSame(Result::FAILURE, $result->getCode());
$this->assertNull($adapter->getIdentity());
$this->assertNotEmpty($result->getMessage());
$emptyCredential->setCredential('authResultShouldBe', Result::SUCCESS);
$result = $adapter->authenticate($emptyCredential);
$this->assertSame(Result::SUCCESS, $result->getCode());
$this->assertInstanceOf(UserEntity::class, $adapter->getIdentity());
$this->assertSame('test', $adapter->getIdentity()->getUserName());
$adapter->clearIdentity();
$this->assertNull($adapter->getIdentity());
}
/**
* Tests setIdentity() method.
*/
public function testSetIdentity()
{
$defaultAdapter = $this->prophesize(DataAdapterInterface::class);
/** @var DataAdapterInterface $defaultAdapterInstance */
$defaultAdapterInstance = $defaultAdapter->reveal();
$config = new Config($this->config);
$result = new Result();
$authStorage = new EmptyAuthStorage();
$dataEntity = new UserEntity();
$dataEntity->setUserName('new entity');
$entitySet = new EntitySet();
$dataStorage = new EmptyUserStorage($defaultAdapterInstance, $entitySet, $dataEntity);
$adapter = new EmptyAuthAdapter(
$config,
$result,
$authStorage,
$dataStorage
);
$this->assertFalse($adapter->hasIdentity());
$this->assertNull($adapter->getIdentity());
$adapter->setIdentity($dataEntity);
$this->assertInstanceOf(UserEntity::class, $adapter->getIdentity());
$this->assertTrue($dataEntity === $adapter->getIdentity());
$this->assertSame('new entity', $adapter->getIdentity()->getUserName());
}
/**
* Tests auth adapter Result
*
* @covers \WebHemi\Auth\Result\Result
*/
public function testResult()
{
$defaultAdapter = $this->prophesize(DataAdapterInterface::class);
/** @var DataAdapterInterface $defaultAdapterInstance */
$defaultAdapterInstance = $defaultAdapter->reveal();
$config = new Config($this->config);
$result = new Result();
$authStorage = new EmptyAuthStorage();
$dataEntity = new UserEntity();
$entitySet = new EntitySet();
$dataStorage = new EmptyUserStorage($defaultAdapterInstance, $entitySet, $dataEntity);
$adapter = new EmptyAuthAdapter(
$config,
$result,
$authStorage,
$dataStorage
);
$emptyCredential = new EmptyCredential();
$emptyCredential->setCredential('authResultShouldBe', Result::SUCCESS);
$result = $adapter->authenticate($emptyCredential);
$this->assertTrue($result->isValid());
$this->assertSame(Result::SUCCESS, $result->getCode());
$emptyCredential->setCredential('authResultShouldBe', Result::FAILURE);
$result = $adapter->authenticate($emptyCredential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE, $result->getCode());
// set it to a non-valid result code
$emptyCredential->setCredential('authResultShouldBe', -100);
$result = $adapter->authenticate($emptyCredential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE_OTHER, $result->getCode());
}
}
<file_sep>/src/WebHemi/Form/Preset/AbstractPreset.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form\Preset;
use InvalidArgumentException;
use WebHemi\Form\ElementInterface;
use WebHemi\Form\PresetInterface;
use WebHemi\Form\ServiceInterface;
/**
* Class AbstractPreset
*/
abstract class AbstractPreset implements PresetInterface
{
/**
* @var ServiceInterface
*/
protected $formAdapter;
/**
* @var ElementInterface[]
*/
private $elementPrototypes;
/**
* LogSelector constructor.
*
* @param ServiceInterface $formAdapter
* @param ElementInterface[] ...$elementPrototypes
*/
public function __construct(ServiceInterface $formAdapter, ElementInterface ...$elementPrototypes)
{
$this->formAdapter = $formAdapter;
foreach ($elementPrototypes as $formElement) {
$this->elementPrototypes[get_class($formElement)] = $formElement;
}
$this->init();
}
/**
* Initialize and add elements to the form.
*
* @return void
*/
abstract protected function init() : void;
/**
* Create a certain type of element.
*
* @param string $class
* @param string $type
* @param string $name
* @param string $label
* @return ElementInterface
*/
protected function createElement(string $class, string $type, string $name, string $label) : ElementInterface
{
if (!isset($this->elementPrototypes[$class])) {
throw new InvalidArgumentException(
sprintf('%s is not injected into the %s preset', $class, get_called_class()),
1000
);
}
/**
* @var ElementInterface $element
*/
$element = clone $this->elementPrototypes[$class];
$element->setType($type)
->setName($name)
->setLabel($label);
return $element;
}
/**
* Returns the initialized form.
*
* @return ServiceInterface
*/
public function getPreset() : ServiceInterface
{
return $this->formAdapter;
}
}
<file_sep>/tests/WebHemiTest/Ftp/FtpAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Ftp;
use PHPUnit\Framework\TestCase;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestService\EmptyFtpAdapter;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
/**
* Class FtpAdapterTest
*/
class FtpAdapterTest extends TestCase
{
/** @var Config */
protected $config;
use AssertArraysAreSimilarTrait;
use InvokePrivateMethodTrait;
/**
* This method is called before the first test of this test class is run.
*/
public static function setUpBeforeClass()
{
$path = realpath(__DIR__ . '/../TestDocumentRoot/data/temp');
// generate files
for ($i = 0; $i < 19; $i++) {
if ($i == 0) {
$fileName = 'a.log';
} else {
$fileName = sprintf('a.(%d).log', $i);
}
if (!file_exists($path.'/'.$fileName)) {
file_put_contents($path.'/'.$fileName, 'test');
}
}
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
}
/**
* This method is called after the last test of this test class is run.
*/
public static function tearDownAfterClass()
{
$path = realpath(__DIR__ . '/../TestDocumentRoot/data/temp');
// Do some cleanup
$files = glob($path.'/*.log'); //get all file names
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
/**
* Tests the constructor
*/
public function testConstructor()
{
$adapter = new EmptyFtpAdapter($this->config);
$this->assertAttributeEmpty('options', $adapter);
$expectedPath = realpath(__DIR__.'/../../../src/WebHemi/Ftp/ServiceAdapter');
$this->assertAttributeSame($expectedPath, 'localPath', $adapter);
}
/**
* Tests option related methods.
*/
public function testOptions()
{
$adapter = new EmptyFtpAdapter($this->config);
$this->assertEmpty($adapter->getOption('not-exists'));
$this->assertSame('test', $adapter->getOption('not-exists', 'test'));
$adapter->setOption('not-exists', 'test2');
$this->assertSame('test2', $adapter->getOption('not-exists', 'test'));
$options = ['key1' => 'value1', 'key2' => 'value2'];
$adapter->setOptions($options);
$this->assertSame('value2', $adapter->getOption('key2', 'something'));
}
/**
* Tests the setLocalPath() method.
*/
public function testSetLocalPath()
{
$adapter = new EmptyFtpAdapter($this->config);
$expectedPath = realpath(__DIR__.'/../../../src/WebHemi/Ftp/ServiceAdapter').'/';
$adapter->setLocalPath('');
$this->assertAttributeSame($expectedPath, 'localPath', $adapter);
$this->assertSame($expectedPath, $adapter->getLocalPath());
$expectedPath = realpath(__DIR__.'/../../../src/WebHemi/Ftp/ServiceAdapter/Base');
$adapter->setLocalPath('Base');
$this->assertAttributeSame($expectedPath, 'localPath', $adapter);
$this->assertSame($expectedPath, $adapter->getLocalPath());
$expectedPath = '/tmp';
$adapter->setLocalPath('/tmp');
$this->assertAttributeSame($expectedPath, 'localPath', $adapter);
$this->assertSame($expectedPath, $adapter->getLocalPath());
}
/**
* Tests exception #1
*/
public function testLocalPathNotExists()
{
$adapter = new EmptyFtpAdapter($this->config);
$this->expectException(\RuntimeException::class);
$this->expectExceptionCode(1003);
$adapter->setLocalPath('/something');
}
/**
* Tests exception #2
*/
public function testLocalPathNotDirectory()
{
$adapter = new EmptyFtpAdapter($this->config);
$this->expectException(\RuntimeException::class);
$this->expectExceptionCode(1003);
$adapter->setLocalPath(__FILE__);
}
/**
* Tests exception #3
*/
public function testLocalPathNotReadable()
{
$system = exec('uname -a');
if (empty($system) || strpos($system, 'boot2docker') !== false || !is_dir('/root')) {
$this->markTestSkipped(
'This test is not available on this environment.'
);
}
$adapter = new EmptyFtpAdapter($this->config);
$this->expectException(\RuntimeException::class);
$this->expectExceptionCode(1004);
$adapter->setLocalPath('/root');
}
/**
* Tests exception #4
*/
public function testLocalPathNotWritable()
{
$system = exec('uname -a');
if (empty($system) || strpos($system, 'boot2docker') !== false || !is_dir('/etc')) {
$this->markTestSkipped(
'This test is not available on this environment.'
);
}
$adapter = new EmptyFtpAdapter($this->config);
$this->expectException(\RuntimeException::class);
$this->expectExceptionCode(1005);
$adapter->setLocalPath('/etc');
}
/**
* Tests the checkLocalFile() method
*/
public function testCheckLocalFile()
{
$adapter = new EmptyFtpAdapter($this->config);
$localFile = realpath(__DIR__ . '/../TestDocumentRoot/testfile.txt');
$expectedResult = 'testfile.txt';
$adapter->testLocalFile($localFile, false);
$this->assertSame($expectedResult, $localFile);
$expectedResult = 'testfile.(3).txt';
$adapter->testLocalFile($localFile, true);
$this->assertSame($expectedResult, $localFile);
$path = realpath(__DIR__ . '/../TestDocumentRoot/data/temp');
$adapter->setLocalPath($path);
$localFile = 'a.log';
$expectedResult = 'a.(19).log';
$adapter->testLocalFile($localFile, true);
$this->assertSame($expectedResult, $localFile);
file_put_contents($path.'/'.$localFile, 'test');
$localFile = 'a.log';
$this->expectException(\RuntimeException::class);
$this->expectExceptionCode(1009);
$adapter->testLocalFile($localFile, true);
}
/**
* Tests the getOctalChmod() method.
*/
public function testGetOctalChmod()
{
$adapter = new EmptyFtpAdapter($this->config);
$input = '-rwxr-xr-x';
$expectedResult = '0755';
$actualResult = $adapter->convertOctalChmod($input);
$this->assertSame($expectedResult, $actualResult);
$input = '-rw-r--r--';
$expectedResult = '0644';
$actualResult = $adapter->convertOctalChmod($input);
$this->assertSame($expectedResult, $actualResult);
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getUserGroupById.sql
SELECT
ug.`id_user_group`,
ug.`name`,
ug.`title`,
ug.`description`,
ug.`is_read_only`,
ug.`date_created`,
ug.`date_modified`
FROM
`webhemi_user_group` AS ug
WHERE
ug.`id_user_group` = :idUserGroup
<file_sep>/src/WebHemi/Router/ProxyInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Router;
use WebHemi\Router\Result\Result;
/**
* Interface ProxyInterface.
*/
interface ProxyInterface
{
// View a specific post
const VIEW_POST = 'view-post';
// List posts under a specific direcory url (e.g.: foo/org/ or foo/org/index.html)
const LIST_POST = 'list-post';
// List posts of a category (e.g.: category/name)
const LIST_CATEGORY = 'list-category';
// List posts of a tag (e.g.: tag/name)
const LIST_TAG = 'list-tag';
// List posts from a date date (e.g.: archive/2018-02)
const LIST_ARCHIVE = 'list-archive';
// List images under a specific gallery url (e.g.: foo/name/index.html)
const LIST_GALLERY = 'list-gallery';
// List files under a specific gallery url (e.g.: foo/name/index.html)
const LIST_BINARY = 'list-binary';
// List posts writtem by a user (e.g.: user/name/index.html)
const LIST_USER = 'list-user';
/**
* Resolves the middleware class name for the application and URL.
*
* @param string $application
* @param Result $routeResult
* @return void
*/
public function resolveMiddleware(string $application, Result&$routeResult) : void;
}
<file_sep>/resources/default_theme/static/js/functions.js
/**
* WebHemi
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
* @link http://www.gixx-web.com
*/
/**
* Returns the event element path.
*
* @param {Event} event
* @return {Array}
*/
function getEventPath(event) {
var path = (event.composedPath && event.composedPath()) || event.path,
target = event.target;
if (typeof path !== 'undefined') {
// Safari doesn't include Window, and it should.
path = (path.indexOf(window) < 0) ? path.concat([window]) : path;
return path;
}
if (target === window) {
return [window];
}
function getParents(node, memo) {
memo = memo || [];
var parentNode = node.parentNode;
if (!parentNode) {
return memo;
}
else {
return getParents(parentNode, memo.concat([parentNode]));
}
}
return [target]
.concat(getParents(target))
.concat([window]);
}
<file_sep>/src/WebHemi/Data/Entity/UserMetaEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class UserMetaEntity
*/
class UserMetaEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_user_meta' => null,
'fk_user' => null,
'meta_key' => null,
'meta_data' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return UserMetaEntity
*/
public function setUserMetaId(int $identifier) : UserMetaEntity
{
$this->container['id_user_meta'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getUserMetaId() : ? int
{
return !is_null($this->container['id_user_meta'])
? (int) $this->container['id_user_meta']
: null;
}
/**
* @param int $userIdentifier
* @return UserMetaEntity
*/
public function setUserId(int $userIdentifier) : UserMetaEntity
{
$this->container['fk_user'] = $userIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getUserId() : ? int
{
return !is_null($this->container['fk_user'])
? (int) $this->container['fk_user']
: null;
}
/**
* @param string $metaKey
* @return UserMetaEntity
*/
public function setMetaKey(string $metaKey) : UserMetaEntity
{
$this->container['meta_key'] = $metaKey;
return $this;
}
/**
* @return null|string
*/
public function getMetaKey() : ? string
{
return $this->container['meta_key'];
}
/**
* @param string $metaData
* @return UserMetaEntity
*/
public function setMetaData(string $metaData) : UserMetaEntity
{
$this->container['meta_data'] = $metaData;
return $this;
}
/**
* @return null|string
*/
public function getMetaData() : ? string
{
return $this->container['meta_data'];
}
/**
* @param DateTime $dateTime
* @return UserMetaEntity
*/
public function setDateCreated(DateTime $dateTime) : UserMetaEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return UserMetaEntity
*/
public function setDateModified(DateTime $dateTime) : UserMetaEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyEnvironmentManager.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use InvalidArgumentException;
use WebHemi\Environment\ServiceAdapter\Base\ServiceAdapter as EnvironmentManager;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
/**
* Class EnvironmentManager.
*/
class EmptyEnvironmentManager extends EnvironmentManager
{
const APPLICATION_TYPE_DIRECTORY = 'directory';
const APPLICATION_TYPE_DOMAIN = 'domain';
const COOKIE_AUTO_LOGIN_PREFIX = 'atln';
const COOKIE_SESSION_PREFIX = 'atsn';
const DEFAULT_APPLICATION = 'website';
const DEFAULT_APPLICATION_URI = '/';
const DEFAULT_MODULE = 'Website';
const DEFAULT_THEME = 'default';
const DEFAULT_THEME_RESOURCE_PATH = '/resources/default_theme';
const SESSION_SALT = 'WebHemiTestX';
/** @var string */
protected $requestUri;
/**
* ModuleManager constructor.
*
* @param ConfigInterface $configuration
* @param array $getData
* @param array $postData
* @param array $serverData
* @param array $cookieData
* @param array $filesData
* @param array $optionsData
*/
public function __construct(
ConfigInterface $configuration,
array $getData,
array $postData,
array $serverData,
array $cookieData,
array $filesData,
array $optionsData = []
) {
$this->configuration = $configuration->getConfig('applications');
$this->environmentData = [
'GET' => $getData,
'POST' => $postData,
'SERVER' => $serverData,
'COOKIE' => $cookieData,
'FILES' => $filesData,
];
$this->applicationRoot = __DIR__.'/../TestDocumentRoot';
$this->documentRoot = realpath($this->applicationRoot.'/');
$this->applicationDomain = 'www.unittest.dev';
$this->topDomain = 'unittest.dev';
$this->selectedModule = 'Website';
$this->selectedApplication = 'website';
$this->selectedApplicationUri = '/';
$this->requestUri = $serverData['REQUEST_URI'] ?? '/';
$this->selectedTheme = 'default';
$this->selectedThemeResourcePath = '/resources/vendor_themes/test_theme';
$this->isHttps = isset($serverData['HTTPS']) && $serverData['HTTPS'] == 'on';
$this->options = $optionsData;
$this->url = 'http'.($this->isHttps ? 's' : '').'://'
.$this->environmentData['SERVER']['HTTP_HOST']
.$this->environmentData['SERVER']['REQUEST_URI'];
}
/**
* @param string $documentRoot
* @return EmptyEnvironmentManager
*/
public function setDocumentRoot(string $documentRoot) : EmptyEnvironmentManager
{
$this->documentRoot = $documentRoot;
return $this;
}
/**
* @param string $application
* @return EmptyEnvironmentManager
*/
public function setSelectedApplication(string $application) : EmptyEnvironmentManager
{
$this->selectedApplication = $application;
return $this;
}
/**
* @param $uri
* @return EmptyEnvironmentManager
*/
public function setSelectedApplicationUri($uri) : EmptyEnvironmentManager
{
$this->selectedApplicationUri = $uri;
return $this;
}
/**
* @param $requestUri
* @return EmptyEnvironmentManager
*/
public function setRequestUri($requestUri) : EmptyEnvironmentManager
{
$this->requestUri = $requestUri;
return $this;
}
/**
* Gets the request URI
*
* @return string
*/
public function getRequestUri() : string
{
return $this->requestUri;
}
/**
* @param $module
* @return EmptyEnvironmentManager
*/
public function setSelectedModule($module) : EmptyEnvironmentManager
{
$this->selectedModule = $module;
return $this;
}
/**
* @param $theme
* @return EmptyEnvironmentManager
*/
public function setSelectedTheme($theme) : EmptyEnvironmentManager
{
$this->selectedTheme = $theme;
return $this;
}
/**
* @return string
*/
public function getResourcePath() : string
{
if ($this->selectedTheme !== self::DEFAULT_THEME) {
$this->selectedThemeResourcePath = '/resources/vendor_themes/'.$this->selectedTheme;
} else {
$this->selectedThemeResourcePath = '/resources/default_theme';
}
return $this->selectedThemeResourcePath;
}
}
<file_sep>/src/WebHemi/Logger/ServiceAdapter/Klogger/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Logger\ServiceAdapter\Klogger;
use Katzgrau\KLogger\Logger;
use Psr\Log\LogLevel;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Logger\ServiceInterface;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter extends LogLevel implements ServiceInterface
{
/**
* @var string
*/
protected $section;
/**
* @var Logger
*/
private $adapter;
/**
* @var array
*/
private $configuration;
/**
* @var array
*/
private $logLevel = [
0 => self::DEBUG,
1 => self::INFO,
2 => self::NOTICE,
3 => self::WARNING,
4 => self::ERROR,
5 => self::CRITICAL,
6 => self::ALERT,
7 => self::EMERGENCY,
];
private $defaultLevel = self::WARNING;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
* @param string $section
*/
public function __construct(ConfigurationInterface $configuration, string $section)
{
$this->configuration = $configuration->getData('logger/'.$section);
$logPath = $this->configuration['path'];
$logLevel = $this->logLevel[$this->configuration['log_level']];
$options = [
'prefix' => $this->configuration['file_name'],
'extension' => $this->configuration['file_extension'],
'dateFormat' => $this->configuration['date_format']
];
$this->adapter = new Logger($logPath, $logLevel, $options);
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
* @return void
*/
public function log($level, string $message, array $context = []) : void
{
if (is_numeric($level)) {
$level = isset($this->logLevel[$level]) ? $this->logLevel[$level] : $this->defaultLevel;
} elseif (!in_array($level, $this->logLevel)) {
$level = $this->defaultLevel;
}
$this->adapter->log($level, $message, $context);
}
}
<file_sep>/tests/WebHemiTest/Validator/NotEmptyValidatorTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Validator;
use PHPUnit\Framework\TestCase;
use WebHemi\Validator\NotEmptyValidator;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait;
/**
* Class NotEmptyValidatorTest
*/
class NotEmptyValidatorTest extends TestCase
{
use AssertArraysAreSimilarTrait;
/**
* Tests the validate method
*/
public function testValidator()
{
$validator = new NotEmptyValidator();
$expectedError = ['This field is mandatory and cannot be empty'];
$result = $validator->validate([]);
$this->assertFalse($result);
$this->assertArraysAreSimilar($expectedError, $validator->getErrors());
$result = $validator->validate([false]);
$this->assertFalse($result);
$result = $validator->validate([0 => 0]);
$this->assertFalse($result);
$result = $validator->validate(['key' => []]);
$this->assertFalse($result);
$result = $validator->validate(['true' => false]);
$this->assertFalse($result);
$result = $validator->validate([null]);
$this->assertFalse($result);
$result = $validator->validate([' ']);
$this->assertFalse($result);
$data = [1, 'key' => ' value', 'notempty' => [1,2,3], true];
$expectedData = [1, 'key' => 'value', 'notempty' => [1,2,3], true];
$result = $validator->validate($data);
$this->assertTrue($result);
$this->assertArraysAreSimilar($expectedData, $validator->getValidData());
}
}
<file_sep>/tests/WebHemiTest/I18n/ServiceAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\I18n;
use PHPUnit\Framework\TestCase;
use WebHemi\I18n\ServiceAdapter\Base\ServiceAdapter as I18nAdapter;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
use WebHemiTest\TestService\EmptyEnvironmentManager;
/**
* Class ServiceAdapterTest.
*/
class ServiceAdapterTest extends TestCase
{
/** @var ConfigInterface */
private $config;
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
/** @var string */
protected $documentRoot;
/** @var string */
protected $defaultTimezone;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->defaultTimezone = date_default_timezone_get();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
$this->documentRoot = realpath(__DIR__.'/../TestDocumentRoot/');
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*/
public function tearDown()
{
parent::tearDown();
date_default_timezone_set($this->defaultTimezone);
}
/**
* Creates a prepared Environment manager for the tests.
*
* @param string $feature website|admin|admin_login
* @return EmptyEnvironmentManager
*/
private function getEnvironment($feature)
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$environmentManager = new EmptyEnvironmentManager(
$this->config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$requestUri = $feature == 'admin_login' ? '/auth/login' : '/';
$environmentManager->setDocumentRoot($this->documentRoot);
$environmentManager->setRequestUri($requestUri);
$environmentManager->setSelectedTheme('default');
if ($feature == 'website') {
$environmentManager->setSelectedApplication('website');
$environmentManager->setSelectedModule('Website');
} elseif ($feature == 'admin') {
$environmentManager->setSelectedApplication('admin');
$environmentManager->setSelectedModule('Admin');
} else {
$environmentManager->setSelectedApplication('some_app');
$environmentManager->setSelectedModule('Website');
}
return $environmentManager;
}
/**
* Data provider for testLocale()
*
* @return array
*/
public function dataProvider()
{
return [
['website', 'en_GB.utf8', 'GB', 'UTF-8', 'Europe/London'],
['admin', 'en_US.utf8', 'US', 'UTF-8', 'America/Detroit'],
['some_app', 'pt_BR.utf8', 'BR', 'UTF-8', 'America/Sao_Paulo'],
];
}
/**
* Tests getters.
*
* @param $application
* @param $expectedLocale
* @param $expectedTerritory
* @param $expectedCodeSet
* @param $expectedTimeZone
*
* @dataProvider dataProvider
*/
public function testLocale($application, $expectedLocale, $expectedTerritory, $expectedCodeSet, $expectedTimeZone)
{
$configuration = $this->config;
$environmentManager = $this->getEnvironment($application);
$adapter = new I18nAdapter($configuration, $environmentManager);
$this->assertSame($expectedLocale, $adapter->getLocale());
$this->assertSame($expectedTerritory, $adapter->getTerritory());
$this->assertSame($expectedCodeSet, $adapter->getCodeSet());
$this->assertSame($expectedTimeZone, $adapter->getTimeZone());
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionCode(1000);
$adapter->setLocale('not_a_locale.UTF-8');
}
}
<file_sep>/src/WebHemi/Data/Storage/ResourceStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Query\QueryInterface;
/**
* Class ResourceStorage.
*/
class ResourceStorage extends AbstractStorage
{
/**
* Returns a full set of resources data.
*
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getResourceList(
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getResourceList',
[
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(ResourceEntity::class, $data);
}
/**
* Returns resource information identified by (unique) ID.
*
* @param int $identifier
* @return null|ResourceEntity
*/
public function getResourceById(int $identifier) : ? ResourceEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getResourceById',
[
':idResource' => $identifier
]
);
/** @var null|ResourceEntity $entity */
$entity = $this->getEntity(ResourceEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns resource information by name.
*
* @param string $name
* @return null|ResourceEntity
*/
public function getResourceByName(string $name) : ? ResourceEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getResourceByName',
[
':name' => $name
]
);
/** @var null|ResourceEntity $entity */
$entity = $this->getEntity(ResourceEntity::class, $data[0] ?? []);
return $entity;
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getApplicationByName.sql
SELECT
a.`id_application`,
a.`name`,
a.`title`,
a.`introduction`,
a.`subject`,
a.`description`,
a.`keywords`,
a.`copyright`,
a.`path`,
a.`theme`,
a.`type`,
a.`locale`,
a.`timezone`,
a.`is_read_only`,
a.`is_enabled`,
a.`date_created`,
a.`date_modified`
FROM
`webhemi_application` AS a
WHERE
a.`name` = :name
<file_sep>/tests/WebHemiTest/Auth/AuthTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Auth;
use PDO;
use WebHemi\Auth\ServiceAdapter\Base\ServiceAdapter as Auth;
use WebHemi\Auth\Result\Result;
use WebHemi\Auth\Credential\NameAndPasswordCredential;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Query\SQLite\QueryAdapter as SQLiteAdapter;
use WebHemi\Data\Driver\PDO\SQLite\DriverAdapter as SQLiteDriver;
use WebHemi\Data\Storage\UserStorage;
use WebHemiTest\TestService\EmptyAuthStorage;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\IncompleteTestError;
use PHPUnit\Framework\SkippedTestError;
/**
* Class AuthTest
*/
class AuthTest extends TestCase
{
/** @var array */
private $config;
use AssertTrait;
use InvokePrivateMethodTrait;
/** @var PDO */
protected static $dataDriver;
/** @var SQLiteAdapter */
protected static $adapter;
const TEST_PASSWORD = '<PASSWORD>';
/**
* Check requirements - also checks SQLite availability.
*/
protected function checkRequirements()
{
if (!extension_loaded('pdo_sqlite')) {
throw new SkippedTestError('No SQLite Available');
}
parent::checkRequirements();
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
$databaseFile = realpath(__DIR__ . '/../../../build/webhemi_schema.sqlite3');
self::$dataDriver = new SQLiteDriver('sqlite:' . $databaseFile);
$fixture = realpath(__DIR__ . '/../TestData/sql/authentication_test.sql');
$setUpSql = file($fixture);
if ($setUpSql) {
foreach ($setUpSql as $sql) {
$result = self::$dataDriver->query($sql);
if (!$result) {
throw new IncompleteTestError(
'Cannot set up test database: '.json_encode(self::$dataDriver->errorInfo()).'; query: '.$sql
);
}
}
}
// since the password is hashed in PHP, it's needed to update the test data in the test database.
$testPassword = password_hash(self::TEST_PASSWORD, PASSWORD_DEFAULT);
$sql = 'UPDATE webhemi_user SET password = ? WHERE id_user IN (90000, 90001, 90002)';
$statement = self::$dataDriver->prepare($sql);
$statement->bindValue(1, $testPassword, PDO::PARAM_STR);
$result = $statement->execute();
if (!$result) {
throw new IncompleteTestError(
'Cannot set up test database: '.json_encode(self::$dataDriver->errorInfo()).'; query: '.$sql
);
}
self::$adapter = new SQLiteAdapter(self::$dataDriver);
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
}
/**
* Tests authentication
*
* @covers \WebHemi\Auth\ServiceAdapter\Base\ServiceAdapter
*/
public function testAuthenticate()
{
$config = new Config($this->config);
$result = new Result();
$authStorage = new EmptyAuthStorage();
$dataEntity = new UserEntity();
$entitySet = new EntitySet();
$dataStorage = new UserStorage(self::$adapter, $entitySet, $dataEntity);
$adapter = new Auth(
$config,
$result,
$authStorage,
$dataStorage
);
$credential = new NameAndPasswordCredential();
$credential->setCredential('username', 'test');
$credential->setCredential('password', '<PASSWORD>');
$result = $adapter->authenticate($credential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE_IDENTITY_NOT_FOUND, $result->getCode());
$this->assertFalse($adapter->hasIdentity());
$credential->setCredential('username', 'test_user_1');
$result = $adapter->authenticate($credential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE_IDENTITY_DISABLED, $result->getCode());
$this->assertFalse($adapter->hasIdentity());
$credential->setCredential('username', 'test_user_2');
$result = $adapter->authenticate($credential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE_IDENTITY_INACTIVE, $result->getCode());
$this->assertFalse($adapter->hasIdentity());
$credential->setCredential('username', 'test_user_3');
$result = $adapter->authenticate($credential);
$this->assertFalse($result->isValid());
$this->assertSame(Result::FAILURE_CREDENTIAL_INVALID, $result->getCode());
$this->assertFalse($adapter->hasIdentity());
$credential->setCredential('password', self::TEST_PASSWORD);
$result = $adapter->authenticate($credential);
$this->assertTrue($result->isValid());
$this->assertSame(Result::SUCCESS, $result->getCode());
$this->assertTrue($adapter->hasIdentity());
$this->assertInstanceOf(UserEntity::class, $adapter->getIdentity());
}
/**
* This method is called after the last test of this test class is run.
*/
public static function tearDownAfterClass()
{
$fixture = realpath(__DIR__ . '/../TestData/sql/authentication_test.rollback.sql');
$tearDownSql = file($fixture);
if ($tearDownSql) {
foreach ($tearDownSql as $sql) {
self::$dataDriver->query($sql);
}
}
}
}
<file_sep>/src/WebHemi/Environment/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Environment;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
public const APPLICATION_TYPE_DIRECTORY = 'directory';
public const APPLICATION_TYPE_DOMAIN = 'domain';
public const COOKIE_AUTO_LOGIN_PREFIX = 'atln';
public const COOKIE_SESSION_PREFIX = 'atsn';
public const DEFAULT_APPLICATION = 'website';
public const DEFAULT_APPLICATION_URI = '/';
public const DEFAULT_MODULE = 'Website';
public const DEFAULT_THEME = 'default';
public const DEFAULT_THEME_RESOURCE_PATH = '/resources/default_theme';
public const SESSION_SALT = 'WebHemi';
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
* @param array $getData
* @param array $postData
* @param array $serverData
* @param array $cookieData
* @param array $filesData
* @param array $optionsData
*/
public function __construct(
ConfigurationInterface $configuration,
array $getData,
array $postData,
array $serverData,
array $cookieData,
array $filesData,
array $optionsData
);
/**
* Gets the document root path.
*
* @return string
*/
public function getDocumentRoot() : string;
/**
* Gets the application path.
*
* @return string
*/
public function getApplicationRoot() : string;
/**
* Gets the application domain.
*
* @return string
*/
public function getApplicationDomain() : string;
/**
* Gets the top domain.
*
* @return string
*/
public function getTopDomain() : string;
/**
* Gets the application SSL status.
*
* @return bool
*/
public function isSecuredApplication() : bool;
/**
* Gets the selected application.
*
* @return string
*/
public function getSelectedApplication() : string;
/**
* Get the URI path for the selected application. Required for the RouterAdapter to work with directory-based
* applications correctly.
*
* @return string
*/
public function getSelectedApplicationUri() : string;
/**
* Gets the full address
*
* @return string
*/
public function getAddress() : string;
/**
* Gets the request URI
*
* @return string
*/
public function getRequestUri() : string;
/**
* Gets the selected module.
*
* @return string
*/
public function getSelectedModule() : string;
/**
* Gets the selected theme.
*
* @return string
*/
public function getSelectedTheme() : string;
/**
* Gets the resource path for the selected theme.
*
* @return string
*/
public function getResourcePath() : string;
/**
* Gets the request method.
*
* @return string
*/
public function getRequestMethod() : string;
/**
* Gets environment data.
*
* @param string $key
* @return array
*/
public function getEnvironmentData(string $key) : array;
/**
* Gets the client IP address.
*
* @return string
*/
public function getClientIp() : string;
/**
* Gets the execution parameters (CLI).
*
* @return array
*/
public function getOptions() : array;
}
<file_sep>/src/WebHemi/Data/Entity/FilesystemMetaEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemMetaEntity
*/
class FilesystemMetaEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_filesystem_meta' => null,
'fk_filesystem' => null,
'meta_key' => null,
'meta_data' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return FilesystemMetaEntity
*/
public function setFilesystemrMetaId(int $identifier) : FilesystemMetaEntity
{
$this->container['id_filesystem_meta'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemMetaId() : ? int
{
return !is_null($this->container['id_filesystem_meta'])
? (int) $this->container['id_filesystem_meta']
: null;
}
/**
* @param int $userIdentifier
* @return FilesystemMetaEntity
*/
public function setFilesystemId(int $userIdentifier) : FilesystemMetaEntity
{
$this->container['fk_filesystem'] = $userIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemId() : ? int
{
return !is_null($this->container['fk_filesystem'])
? (int) $this->container['fk_filesystem']
: null;
}
/**
* @param string $metaKey
* @return FilesystemMetaEntity
*/
public function setMetaKey(string $metaKey) : FilesystemMetaEntity
{
$this->container['meta_key'] = $metaKey;
return $this;
}
/**
* @return null|string
*/
public function getMetaKey() : ? string
{
return $this->container['meta_key'];
}
/**
* @param string $metaData
* @return FilesystemMetaEntity
*/
public function setMetaData(string $metaData) : FilesystemMetaEntity
{
$this->container['meta_data'] = $metaData;
return $this;
}
/**
* @return null|string
*/
public function getMetaData() : ? string
{
return $this->container['meta_data'];
}
/**
* @param DateTime $dateTime
* @return FilesystemMetaEntity
*/
public function setDateCreated(DateTime $dateTime) : FilesystemMetaEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return FilesystemMetaEntity
*/
public function setDateModified(DateTime $dateTime) : FilesystemMetaEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/src/WebHemi/Mailer/ServiceAdapter/TxMailer/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Mailer\ServiceAdapter\TxMailer;
use Tx\Mailer;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Mailer\ServiceInterface;
/**
* Class ServiceAdapter
*
* @SuppressWarnings(PHPMD.ShortMethodName)
* @codeCoverageIgnore - no need to test external library
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var Mailer
*/
private $mailer;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$configuration = $configuration->getData('email');
$secure = isset($configuration['secure']) ? $configuration['secure'] : null;
$auth = isset($configuration['auth']) ? $configuration['auth'] : null;
$this->mailer = new \Tx\Mailer(null);
$this->mailer->setServer($configuration['host'], $configuration['port'], $secure);
if ($auth == 'login') {
$this->mailer->setAuth($configuration['username'], $configuration['password']);
} elseif ($auth == 'oatuh') {
$this->mailer->setOAuth($configuration['oauthToken']);
}
$this->mailer->setFrom($configuration['from']['name'], $configuration['from']['email']);
}
/**
* Sets the sender.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function setFrom(string $name, string $email) : ServiceInterface
{
$this->mailer->setFrom($name, $email);
return $this;
}
/**
* Sets a recipient.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function addTo(string $name, string $email) : ServiceInterface
{
$this->mailer->addTo($name, $email);
return $this;
}
/**
* Sets a Carbon Copy recipient.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function addCc(string $name, string $email) : ServiceInterface
{
$this->mailer->addCc($name, $email);
return $this;
}
/**
* Sets a Blind Carbon Copy recipient.
*
* @param string $name
* @param string $email
* @return ServiceInterface
*/
public function addBcc(string $name, string $email) : ServiceInterface
{
$this->mailer->addBcc($name, $email);
return $this;
}
/**
* Sets the subject.
*
* @param string $subject
* @return ServiceInterface
*/
public function setSubject(string $subject) : ServiceInterface
{
$this->mailer->setSubject($subject);
return $this;
}
/**
* Sets the body.
*
* @param string $body
* @return ServiceInterface
*/
public function setBody(string $body) : ServiceInterface
{
$this->mailer->setBody($body);
return $this;
}
/**
* Adds an attachment to the mail.
*
* @param string $name
* @param string $path
* @return ServiceInterface
*/
public function addAttachment(string $name, string $path) : ServiceInterface
{
$this->mailer->addAttachment($name, $path);
return $this;
}
/**
* Sends the email.
*
* @return bool
*/
public function send() : bool
{
return $this->mailer->send();
}
}
<file_sep>/src/WebHemi/Form/ElementInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form;
use WebHemi\Validator\ValidatorInterface;
/**
* Interface ElementInterface.
*/
interface ElementInterface
{
/**
* ElementInterface constructor.
*
* @param string $type The type of the form element.
* @param string $name For HTML forms it is the name attribute.
* @param string $label Optional. The label of the element. If not set the $name should be used.
* @param array $values Optional. The values of the element.
* @param array $valueRange Optional. The range of interpretation.
*/
public function __construct(
string $type = null,
string $name = null,
string $label = null,
array $values = [],
array $valueRange = []
);
/**
* Sets element's name.
*
* @param string $name
* @return ElementInterface
*/
public function setName(string $name) : ElementInterface;
/**
* Gets the element's name.
*
* @return string
*/
public function getName() : string;
/**
* Gets the element's unique id generated from the name.
*
* @return string
*/
public function getId() : string;
/**
* Sets the element's type.
*
* @param string $type
* @return ElementInterface
*/
public function setType(string $type) : ElementInterface;
/**
* Gets the element's type.
*
* @return string
*/
public function getType() : string;
/**
* Sets the element's label.
*
* @param string $label
* @return ElementInterface
*/
public function setLabel(string $label) : ElementInterface;
/**
* Gets the element's label.
*
* @return string
*/
public function getLabel() : string;
/**
* Sets the range of interpretation. Depends on the element type how it is used: exact element list or a min/max.
*
* @param array $valueRange
* @return ElementInterface
*/
public function setValueRange(array $valueRange) : ElementInterface;
/**
* Get the range of interpretation.
*
* @return array
*/
public function getValueRange() : array;
/**
* Sets the values.
*
* @param array $values
* @return ElementInterface
*/
public function setValues(array $values) : ElementInterface;
/**
* Gets the values.
*
* @return array
*/
public function getValues() : array;
/**
* Adds a validator to the element.
*
* @param ValidatorInterface $validator
* @return ElementInterface
*/
public function addValidator(ValidatorInterface $validator) : ElementInterface;
/**
* Validates the element.
*
* @return ElementInterface
*/
public function validate() : ElementInterface;
/**
* Set custom error.
*
* @param string $validator
* @param string $error
* @return ElementInterface
*/
public function setError(string $validator, string $error) : ElementInterface;
/**
* Returns the errors collected during the validation.
*
* @return array
*/
public function getErrors() : array;
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getApplicationList.sql
SELECT
a.`id_application`,
a.`name`,
a.`title`,
a.`introduction`,
a.`subject`,
a.`description`,
a.`keywords`,
a.`copyright`,
a.`path`,
a.`theme`,
a.`type`,
a.`locale`,
a.`timezone`,
a.`is_read_only`,
a.`is_enabled`,
a.`date_created`,
a.`date_modified`
FROM
`webhemi_application` AS a
ORDER BY
a.`name`
LIMIT
:limit
OFFSET
:offset
<file_sep>/tests/WebHemiTest/TestService/EmptyDependencyInjectionContainer.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use InvalidArgumentException;
use ReflectionClass;
use RuntimeException;
use Throwable;
use WebHemi\DependencyInjection\ServiceInterface;
use WebHemi\DependencyInjection\ServiceAdapter\AbstractAdapter;
/**
* Class EmptyDependencyInjectionContainer
*/
class EmptyDependencyInjectionContainer extends AbstractAdapter
{
private $container = [];
/**
* Returns true if the given service is registered.
*
* @param string $identifier
* @return bool
*/
public function has(string $identifier) : bool
{
return isset($this->container[$identifier])
|| isset($this->serviceLibrary[$identifier])
|| class_exists($identifier);
}
/**
* Makes the resolveServiceClassName() method to be public.
*
* @param string $identifier
* @param string $moduleName
* @return string
*/
public function callResolveServiceClassName(string $identifier, string $moduleName) : string
{
return $this->resolveServiceClassName($identifier, $moduleName);
}
/**
* Makes the resolveServiceArguments() method to be public.
*
* @param string $identifier
* @param string $moduleName
* @return array
*/
public function callResolveServiceArguments(string $identifier, string $moduleName) : array
{
return $this->resolveServiceArguments($identifier, $moduleName);
}
/**
* Makes the resolveShares() method to be public.
*
* @param string $identifier
* @param string $moduleName
* @return bool
*/
public function callResolveShares(string $identifier, string $moduleName) : bool
{
return $this->resolveShares($identifier, $moduleName);
}
/**
* Makes the moreAlias serviceIsInitialized() method public.
*
* @param string $identifier
* @return bool
*/
public function callServiceIsInitialized(string $identifier) : bool
{
return $this->serviceIsInitialized($identifier);
}
/**
* Gets a service.
*
* @param string $identifier
* @return object
*/
public function get(string $identifier)
{
if (!$this->has($identifier)) {
throw new InvalidArgumentException('Wrong service name: '.$identifier);
}
if (class_exists($identifier) && !isset($this->serviceLibrary[$identifier])) {
$this->registerService($identifier);
}
$initialized = $this->serviceLibrary[$identifier][self::SERVICE_INITIALIZED] ?? false;
if (!$initialized) {
$this->registerLibraryInstance(
$identifier,
$this->serviceLibrary[$identifier][self::SERVICE_CLASS],
$this->serviceLibrary[$identifier][self::SERVICE_ARGUMENTS]
);
}
if (!isset($this->container[$identifier])) {
throw new RuntimeException(
sprintf('The service "%s" cannot be found.', $identifier),
1002
);
}
return $this->container[$identifier];
}
/**
* @param string $identifier
* @param string $className
* @param array $arguments
*/
private function registerLibraryInstance(string $identifier, string $className, array $arguments = [])
{
try {
if (count($arguments) == 0) {
$serviceInstance = new $className;
} else {
$reflectionClass = new ReflectionClass($className);
$serviceInstance = $reflectionClass->newInstanceArgs($arguments);
}
} catch (Throwable $error) {
$serviceInstance = null;
}
if ($serviceInstance) {
$this->container[$identifier] = $serviceInstance;
$this->serviceLibrary[$identifier][self::SERVICE_INITIALIZED] = true;
}
}
/**
* Register the service.
*
* @param string $identifier
* @param object $serviceInstance
* @return ServiceInterface
*/
public function registerServiceInstance(string $identifier, $serviceInstance) : ServiceInterface
{
$instanceType = gettype($serviceInstance);
// Register synthetic services
if ('object' !== $instanceType) {
throw new InvalidArgumentException(
sprintf('The second parameter must be an object instance, %s given.', $instanceType),
1001
);
}
$this->container[$identifier] = $serviceInstance;
$this->serviceLibrary[$identifier][self::SERVICE_INITIALIZED] = true;
return $this;
}
}
<file_sep>/tests/WebHemiTest/TestService/TestMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Middleware\MiddlewareInterface;
/**
* Class TestMiddleware.
*/
class TestMiddleware implements MiddlewareInterface
{
/** @var int */
public static $counter = 0;
/** @var array */
public static $trace = [];
public static $responseStatus;
public static $responseBody;
/** @var bool */
private $isFinalMiddleware = false;
/**
* TestMiddleware constructor.
*
* @param $name
*/
public function __construct($name)
{
self::$trace[] = $name;
if ($name == 'final') {
$this->isFinalMiddleware = true;
}
}
/**
* Invokes the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return void
*/
public function __invoke(ServerRequestInterface &$request, ResponseInterface&$response) : void
{
self::$counter++;
if (in_array($request->getMethod(), ['GET', 'POST']) && $this->isFinalMiddleware) {
self::$responseStatus = $response->getStatusCode();
self::$responseBody = $response->getBody()->__toString();
}
}
}
<file_sep>/src/WebHemi/Session/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Session;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationService;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationService $configuration
*/
public function __construct(ConfigurationService $configuration);
/**
* Saves data back to session.
*/
public function __destruct();
/**
* Starts a session.
*
* @param string $name
* @param int $timeOut
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httpOnly
* @return ServiceInterface
*/
public function start(
string $name,
int $timeOut = 3600,
string $path = '/',
? string $domain = null,
bool $secure = false,
bool $httpOnly = false
) : ServiceInterface;
/**
* Regenerates session identifier.
*
* @return ServiceInterface
*/
public function regenerateId() : ServiceInterface;
/**
* Returns the session id.
*
* @return string
*/
public function getSessionId() : string;
/**
* Sets session data.
*
* @param string $name
* @param mixed $value
* @param bool $readOnly
* @throws RuntimeException
* @return ServiceInterface
*/
public function set(string $name, $value, bool $readOnly = false) : ServiceInterface;
/**
* Checks whether a session data exists or not.
*
* @param string $name
* @throws RuntimeException
* @return bool
*/
public function has(string $name) : bool;
/**
* Gets session data.
*
* @param string $name
* @param bool $skipMissing
* @throws RuntimeException
* @return mixed
*/
public function get(string $name, bool $skipMissing = true);
/**
* Deletes session data.
*
* @param string $name
* @param bool $forceDelete
* @throws RuntimeException
* @return ServiceInterface
*/
public function delete(string $name, bool $forceDelete = false) : ServiceInterface;
/**
* Unlocks readOnly data.
*
* @param string $name
* @return ServiceInterface
*/
public function unlock(string $name) : ServiceInterface;
/**
* Returns the internal storage.
*
* @return array
*/
public function toArray() : array;
}
<file_sep>/src/WebHemi/Middleware/Action/Website/Directory/BinaryAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Website\Directory;
use WebHemi\Data\Entity;
use WebHemi\Middleware\Action\Website\IndexAction;
/**
* Class BinaryAction.
*/
class BinaryAction extends IndexAction
{
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'website-file-list';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->getApplicationStorage()
->getApplicationByName($this->environmentManager->getSelectedApplication());
$blogPosts = [];
return [
'page' => [
'title' => '',
'type' => 'Binary',
],
'activeMenu' => '',
'application' => $this->getApplicationData($applicationEntity),
'blogPosts' => $blogPosts,
];
}
}
<file_sep>/src/WebHemi/Form/PresetInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form;
/**
* Interface PresetInterface
*/
interface PresetInterface
{
/**
* PresetInterface constructor.
*
* @param ServiceInterface $formAdapter
* @param ElementInterface[] ...$elementPrototypes
*/
public function __construct(ServiceInterface $formAdapter, ElementInterface ...$elementPrototypes);
/**
* Returns the initialized form.
*
* @return ServiceInterface
*/
public function getPreset() : ServiceInterface;
}
<file_sep>/src/WebHemi/Application/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Application;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param DependencyInjectionInterface $container
*/
public function __construct(DependencyInjectionInterface $container);
/**
* Starts the session.
*
* @return ServiceInterface
*/
public function initSession() : ServiceInterface;
/**
* Initializes the I18n Service.
*
* @return ServiceInterface
*/
public function initInternationalization() : ServiceInterface;
/**
* Runs the application. This is where the magic happens.
* For example for a web application this initializes the Request and Response objects, builds the middleware
* pipeline, applies the Router and the Dispatcher.
*
* @return ServiceInterface
*/
public function run() : ServiceInterface;
/**
* Renders the response body and sends it to the client.
*
* @return void
*
* @codeCoverageIgnore - no output for tests
*/
public function renderOutput() : void;
/**
* Sends the response body to the client.
*
* @return void
*
* @codeCoverageIgnore - no output for tests
*/
public function sendOutput() : void;
}
<file_sep>/tests/WebHemiTest/MiddlewarePipeline/PipelineManagerTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\MiddlewarePipeline;
use WebHemi\DateTime;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Middleware\Common\DispatcherMiddleware;
use WebHemi\Middleware\Common\RoutingMiddleware;
use WebHemi\MiddlewarePipeline\ServiceAdapter\Base\ServiceAdapter as Pipeline;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
/**
* Class PipelineTest.
*/
class PipelineTest extends TestCase
{
protected $config;
use AssertTrait;
use InvokePrivateMethodTrait;
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
}
/**
* Tests the getPipelineList() method.
*/
public function testGetList()
{
$pipeline = new Pipeline($this->config);
$pipeline->addModulePipeLine('SomeApp')
->start();
$expectedPipeline = [
'pipe2',
RoutingMiddleware::class,
'pipe3',
'someModuleAlias',
'pipe1',
DispatcherMiddleware::class,
'pipe4'
];
$actualPipeline = $pipeline->getPipelineList();
$this->assertArraysAreSimilar($actualPipeline, $expectedPipeline);
}
/**
* Tests the getPipelineList() method.
*/
public function testErrorOfCallNextWhenNotStarted()
{
$pipeline = new Pipeline($this->config);
// Exception for not started pipeline
$this->expectException(RuntimeException::class);
$this->expectExceptionCode(1003);
$pipeline->next();
}
/**
* Tests the getPipelineList() method.
*/
public function testErrorOfCheckMiddlewareWhenStarted()
{
$pipeline = new Pipeline($this->config);
$pipeline->start();
// Exception for already started pipeline
$this->expectException(RuntimeException::class);
$this->expectExceptionCode(1000);
$this->invokePrivateMethod($pipeline, 'checkMiddleware', ['newService']);
}
/**
* Tests the getPipelineList() method.
*/
public function testErrorOfCheckMiddlewareWithQueuedService()
{
$pipeline = new Pipeline($this->config);
// Exception for already registered item
$this->expectException(RuntimeException::class);
$this->expectExceptionCode(1001);
$this->invokePrivateMethod($pipeline, 'checkMiddleware', ['pipe1']);
}
/**
* Tests the getPipelineList() method.
*/
public function testErrorOfCheckMiddlewareWithWrongInstance()
{
$pipeline = new Pipeline($this->config);
// Exception for not-middleware class
$this->expectException(RuntimeException::class);
$this->expectExceptionCode(1002);
$this->invokePrivateMethod($pipeline, 'checkMiddleware', [DateTime::class]);
}
}
<file_sep>/src/WebHemi/Http/ServiceAdapter/GuzzleHttp/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http\ServiceAdapter\GuzzleHttp;
use GuzzleHttp\Psr7\LazyOpenStream;
use GuzzleHttp\Psr7\Uri;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Http\ServiceInterface;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var ServerRequest
*/
private $request;
/**
* @var Response
*/
private $response;
/**
* @var array
*/
private $get;
/**
* @var array
*/
private $post;
/**
* @var array
*/
private $server;
/**
* @var array
*/
private $cookie;
/**
* @var array
*/
private $files;
/**
* ServiceAdapter constructor.
*
* @param EnvironmentInterface $environmentManager
*/
public function __construct(EnvironmentInterface $environmentManager)
{
$this->environmentManager = $environmentManager;
$this->get = $environmentManager->getEnvironmentData('GET');
$this->post = $environmentManager->getEnvironmentData('POST');
$this->server = $environmentManager->getEnvironmentData('SERVER');
$this->cookie = $environmentManager->getEnvironmentData('COOKIE');
$this->files = $environmentManager->getEnvironmentData('FILES');
$this->initialize();
}
/**
* Initialize adapter: create the ServerRequest and Response instances.
*
* @return void
*/
private function initialize() : void
{
$uri = new Uri('');
$uri = $uri->withScheme($this->getScheme())
->withHost($this->getHost())
->withPort($this->getServerData('SERVER_PORT', '80'))
->withPath($this->getRequestUri())
->withQuery($this->getServerData('QUERY_STRING', ''));
$serverRequest = new ServerRequest(
$this->getServerData('REQUEST_METHOD', 'GET'),
$uri,
[],
new LazyOpenStream('php://input', 'r+'),
$this->getProtocol(),
$this->server
);
$this->request = $serverRequest
->withCookieParams($this->cookie)
->withQueryParams($this->get)
->withParsedBody($this->post);
// Create a Response with HTTP 102 - Processing.
$this->response = new Response(Response::STATUS_PROCESSING);
}
/**
* Gets the specific server data, or a default value if not present.
*
* @param string $keyName
* @param string $defaultValue
* @return string
*/
private function getServerData(string $keyName, string $defaultValue = '') : string
{
if (isset($this->server[$keyName])) {
$defaultValue = $this->server[$keyName];
}
return (string) $defaultValue;
}
/**
* Gets server scheme.
*
* @return string
*/
private function getScheme() : string
{
return $this->environmentManager->isSecuredApplication() ? 'https' : 'http';
}
/**
* Gets the server host name.
*
* @return string
*/
private function getHost() : string
{
$host = $this->getServerData('HTTP_HOST');
$name = $this->getServerData('SERVER_NAME');
if (empty($host) && !empty($name)) {
$host = $name;
}
return (string) preg_replace('/:[0-9]+$/', '', $host);
}
/**
* Gets the server request uri.
*
* @return string
*/
private function getRequestUri() : string
{
$requestUri = $this->environmentManager->getRequestUri();
return (string) current(explode('?', $requestUri));
}
/**
* Gets the server protocol.
*
* @return string
*/
private function getProtocol() : string
{
$protocol = '1.1';
$serverProtocol = $this->getServerData('SERVER_PROTOCOL');
if (!empty($serverProtocol)) {
$protocol = str_replace('HTTP/', '', $serverProtocol);
}
return (string) $protocol;
}
/**
* Returns the HTTP request.
*
* @return ServerRequestInterface
*/
public function getRequest() : ServerRequestInterface
{
return $this->request;
}
/**
* Returns the response being sent.
*
* @return ResponseInterface
*/
public function getResponse() : ResponseInterface
{
return $this->response;
}
}
<file_sep>/src/WebHemi/Renderer/TagFilterInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer;
/**
* Interface TagFilterInterface
*/
interface TagFilterInterface
{
/**
* Apply the filter.
*
* @param string $text
* @return string
*/
public function filter(string $text) : string;
}
<file_sep>/tests/WebHemiTest/TestData/sql/acl_test.rollback.sql
DELETE FROM `webhemi_user_to_policy` WHERE `id_user_to_policy` IN (90000, 90001, 90002);
DELETE FROM `webhemi_user_to_user_group` WHERE `id_user_to_user_group` IN (90000, 90001);
DELETE FROM `webhemi_user_group_to_policy` WHERE `id_user_group_to_policy` IN (90000, 90001, 90002, 90003);
DELETE FROM `webhemi_policy` WHERE `id_policy` IN (90000, 90001, 90002, 90003);
DELETE FROM `webhemi_application` WHERE `id_application` IN (90000);
DELETE FROM `webhemi_resource` WHERE `id_resource` IN (90000);
DELETE FROM `webhemi_user_group` WHERE `id_user_group` IN (90000, 90001);
DELETE FROM `webhemi_user` WHERE `id_user` IN (90000, 90001);
<file_sep>/src/WebHemi/Middleware/Action/Website/View/PostAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Website\View;
use RuntimeException;
use WebHemi\Data\Entity;
use WebHemi\Middleware\Action\Website\IndexAction;
/**
* Class PostAction
*/
class PostAction extends IndexAction
{
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'website-post-view';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$routingParams = $this->getRoutingParameters();
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->getApplicationStorage()
->getApplicationByName($this->environmentManager->getSelectedApplication());
/**
* @var null|Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
*/
$publishedDocumentEntity = $this->getFilesystemStorage()
->getFilesystemPublishedDocumentByApplicationAndPath(
(int) $applicationEntity->getApplicationId(),
$routingParams['path'],
$routingParams['basename']
);
if (!$publishedDocumentEntity instanceof Entity\FilesystemPublishedDocumentEntity) {
throw new RuntimeException('Page not found', 404);
}
return [
'activeMenu' => '',
'page' => [
'type' => 'Categories',
],
'application' => $this->getApplicationData($applicationEntity),
'blogPost' => $this->getBlobPostData($applicationEntity, $publishedDocumentEntity),
];
}
}
<file_sep>/resources/default_theme/static/js/site.js
/**
* WebHemi
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
* @link http://www.gixx-web.com
*/
(function() {
hljs.configure({
tabReplace: ' '
});
hljs.initHighlighting();
var moods = document.querySelectorAll('span.mood');
for (var i = 0, num = moods.length; i < num; i++) {
moods[i].innerHTML = emojione.toImage(moods[i].innerText);
}
document.querySelectorAll('body > header a').forEach(function(element) {
element.addEventListener('click', function(e) {
e.preventDefault();
var drawerElementTag = e.target.classList[0];
document.querySelector('body > '+drawerElementTag).classList.toggle('open');
});
});
document.addEventListener('click', function(event) {
var path = getEventPath(event);
for (var i = 0, num = path.length; i < num; i++) {
if (typeof path[i].tagName === 'undefined') {
continue;
}
if (path[i].tagName.toLowerCase() === 'div' &&
path[i].classList.contains('container')
){
if (typeof path[i+1] !== 'undefined' &&
(path[i+1].tagName.toLowerCase() === 'nav' || path[i+1].tagName.toLowerCase() === 'aside') &&
path[i+1].classList.contains('open')
) {
break;
}
}
if ((path[i].tagName.toLowerCase() === 'nav' || path[i].tagName.toLowerCase() === 'aside') &&
path[i].classList.contains('open')
) {
var menu = path[i];
event.preventDefault();
menu.classList.remove('open');
menu.classList.add('closing');
setTimeout(function(){
menu.classList.remove('closing');
}, 1000);
break;
}
}
});
})();
<file_sep>/bin/regenerate.sqlite.sh
#!/bin/sh
dir="$(dirname "$0")"
cd $dir
rm -f ../build/webhemi_schema.sqlite3 && ./mysql2sqlite.sh --host=localhost -u root -pdevmysql webhemi | sqlite3 ../build/webhemi_schema.sqlite3
<file_sep>/config/modules/admin/dependencies.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Acl;
use WebHemi\Application;
use WebHemi\Auth;
use WebHemi\Configuration;
use WebHemi\Data;
use WebHemi\Environment;
use WebHemi\Form;
use WebHemi\Middleware;
use WebHemi\Session;
return [
'dependencies' => [
'Admin' => [
Application\Progress::class => [
'arguments' => [
Environment\ServiceInterface::class,
Session\ServiceInterface::class
],
'shared' => false
],
// Pipeline elements
Middleware\Security\AclMiddleware::class => [
'arguments' => [
Auth\ServiceInterface::class,
Acl\ServiceInterface::class,
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class,
Data\Storage\ResourceStorage::class,
Data\Storage\UserStorage::class
]
],
Middleware\Security\AccessLogMiddleware::class => [
'arguments' => [
'AccessLog',
Auth\ServiceInterface::class,
Environment\ServiceInterface::class
]
],
// Actions
Middleware\Action\Auth\LoginAction::class => [
'arguments' => [
Auth\ServiceInterface::class,
Auth\CredentialInterface::class,
Environment\ServiceInterface::class,
'AdminLoginForm',
],
],
Middleware\Action\Auth\LogoutAction::class => [
'arguments' => [
Auth\ServiceInterface::class,
Environment\ServiceInterface::class,
]
],
Middleware\Action\Admin\DashboardAction::class => [
'arguments' => [
Auth\ServiceInterface::class,
Environment\ServiceInterface::class
],
],
Middleware\Action\Admin\Applications\IndexAction::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Auth\ServiceInterface::class,
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class
],
],
Middleware\Action\Admin\Applications\AddAction::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Auth\ServiceInterface::class,
Environment\ServiceInterface::class,
'ApplicationEditForm'
],
],
Middleware\Action\Admin\Applications\ViewAction::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Auth\ServiceInterface::class,
Environment\ServiceInterface::class,
Data\Storage\ApplicationStorage::class
],
],
Middleware\Action\Admin\Applications\PreferencesAction::class => [
'inherits' => Middleware\Action\Admin\Applications\ViewAction::class,
],
Middleware\Action\Admin\Applications\DeleteAction::class => [
'inherits' => Middleware\Action\Admin\Applications\ViewAction::class,
],
Middleware\Action\Admin\ControlPanel\Groups\ListAction::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class,
Data\Storage\UserStorage::class
]
],
Middleware\Action\Admin\ControlPanel\Groups\ViewAction::class => [
'inherits' => Middleware\Action\Admin\ControlPanel\Groups\ListAction::class
],
Middleware\Action\Admin\ControlPanel\Themes\IndexAction::class => [
'arguments' => [
Configuration\ServiceInterface::class,
Environment\ServiceInterface::class,
],
],
// Form Presets - looks kinda hack, but it is by purpose.
Form\PresetInterface::class => [
'class' => Form\Preset\SimplePreset::class,
'arguments' => [
Form\ServiceAdapter\Base\ServiceAdapter::class,
Form\Element\Html\HtmlElement::class
]
],
'AdminLoginForm' => [
'class' => Form\Preset\AdminLoginForm::class,
'inherits' => Form\PresetInterface::class
],
'ApplicationEditForm' => [
'class' => Form\Preset\ApplicationEditForm::class,
'inherits' => Form\PresetInterface::class
]
]
],
];
<file_sep>/src/WebHemi/Form/Element/Html/Html5Element.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form\Element\Html;
/**
* Class Html5Element.
*/
class Html5Element extends AbstractElement
{
public const HTML5_ELEMENT_DATALIST = 'datalist';
public const HTML5_ELEMENT_INPUT_COLOR = 'inputColor';
public const HTML5_ELEMENT_INPUT_DATE = 'inputDate';
public const HTML5_ELEMENT_INPUT_DATETIME = 'inputDateTime';
public const HTML5_ELEMENT_INPUT_DATETIMELOCAL = 'inputDateTimeLocal';
public const HTML5_ELEMENT_INPUT_EMAIL = 'inputEmail';
public const HTML5_ELEMENT_INPUT_MONTH = 'inputMonth';
public const HTML5_ELEMENT_INPUT_NUMBER = 'inputNumber';
public const HTML5_ELEMENT_INPUT_RANGE = 'inputRange';
public const HTML5_ELEMENT_INPUT_SEARCH = 'inputSearch';
public const HTML5_ELEMENT_INPUT_TEL = 'inputTel';
public const HTML5_ELEMENT_INPUT_TIME = 'inputTime';
public const HTML5_ELEMENT_INPUT_URL = 'inputUrl';
public const HTML5_ELEMENT_INPUT_WEEK = 'inputWeek';
public const HTML5_ELEMENT_KEYGEN = 'keygen';
public const HTML5_ELEMENT_OUTPUT = 'output';
/**
* @var array
*/
protected $validTypes = [
self::HTML5_ELEMENT_DATALIST,
self::HTML5_ELEMENT_INPUT_COLOR,
self::HTML5_ELEMENT_INPUT_DATE,
self::HTML5_ELEMENT_INPUT_DATETIME,
self::HTML5_ELEMENT_INPUT_DATETIMELOCAL,
self::HTML5_ELEMENT_INPUT_EMAIL,
self::HTML5_ELEMENT_INPUT_MONTH,
self::HTML5_ELEMENT_INPUT_NUMBER,
self::HTML5_ELEMENT_INPUT_RANGE,
self::HTML5_ELEMENT_INPUT_SEARCH,
self::HTML5_ELEMENT_INPUT_TEL,
self::HTML5_ELEMENT_INPUT_TIME,
self::HTML5_ELEMENT_INPUT_URL,
self::HTML5_ELEMENT_INPUT_WEEK,
self::HTML5_ELEMENT_KEYGEN,
self::HTML5_ELEMENT_OUTPUT,
];
}
<file_sep>/config/settings/_global/application.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
/**
* Default Website and Admin application configuration.
*/
return [
'applications' => [
'website' => [
'domain' => $_SERVER['SERVER_NAME'],
'path' => '/',
'type' => 'domain',
'theme' => 'default',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
],
'admin' => [
'domain' => $_SERVER['SERVER_NAME'],
'path' => '/admin',
'type' => 'directory',
'theme' => 'default',
'locale' => 'en_GB.UTF-8',
'timezone' => 'Europe/London',
],
],
];
<file_sep>/src/WebHemi/Application/ServiceAdapter/AbstractAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Application\ServiceAdapter;
use Throwable;
use WebHemi\Application\ServiceInterface;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Http\ServiceInterface as HttpInterface;
use WebHemi\I18n\ServiceInterface as I18nInterface;
/**
* Class AbstractAdapter
*/
abstract class AbstractAdapter implements ServiceInterface
{
/**
* @var Throwable
*/
public $error;
/**
* @var DependencyInjectionInterface
*/
protected $container;
/**
* @var ServerRequestInterface
*/
protected $request;
/**
* @var ResponseInterface
*/
protected $response;
/**
* @var I18nInterface
*/
protected $i18n;
/**
* ServiceAdapter constructor.
*
* @param DependencyInjectionInterface $container
*/
public function __construct(DependencyInjectionInterface $container)
{
$this->container = $container;
/**
* @var HttpInterface $httpAdapter
*/
$httpAdapter = $this->container->get(HttpInterface::class);
/**
* @var ServerRequestInterface $request
*/
$this->request = $httpAdapter->getRequest();
/**
* @var ResponseInterface $response
*/
$this->response = $httpAdapter->getResponse();
}
/**
* Starts the session.
*
* @return ServiceInterface
*/
abstract public function initSession() : ServiceInterface;
/**
* Initializes the I18n Service.
*
* @return ServiceInterface
*/
public function initInternationalization() : ServiceInterface
{
/** @var I18nInterface $instance */
$instance = $this->container->get(I18nInterface::class);
$this->i18n = $instance;
return $this;
}
/**
* Runs the application. This is where the magic happens.
* According tho the environment settings this must build up the middleware pipeline and execute it.
*
* a Pre-Routing Middleware can be; priority < 0:
* - LockCheck - check if the client IP is banned > S102|S403
* - Auth - if the user is not logged in, but there's a "Remember me" cookie, then logs in > S102
*
* Routing Middleware is fixed (RoutingMiddleware::class); priority = 0:
* - A middleware that routes the incoming Request and delegates to the matched middleware. > S102|S404|S405
* The RouteResult should be attached to the Request.
* If the Routing is not defined explicitly in the pipeline, then it will be injected with priority 0.
*
* a Post-Routing Middleware can be; priority between 0 and 100:
* - Acl - checks if the given route is available for the client. Also checks the auth > S102|S401|S403
* - CacheReader - checks if a suitable response body is cached. > S102|S200
*
* Dispatcher Middleware is fixed (DispatcherMiddleware::class); priority = 100:
* - A middleware which gets the corresponding Action middleware and applies it > S102
* If the Dispatcher is not defined explicitly in the pipeline, then it will be injected with priority 100.
* The Dispatcher should not set the response Status Code to 200 to let Post-Dispatchers to be called.
*
* a Post-Dispatch Middleware can be; priority > 100:
* - CacheWriter - writes response body into DataStorage (DB, File etc.) > S102
*
* Final Middleware is fixed (FinalMiddleware:class):
* - This middleware behaves a bit differently. It cannot be ordered, it's always the last called middleware:
* - when the middleware pipeline reached its end (typically when the Status Code is still 102)
* - when one item of the middleware pipeline returns with return response (status code is set to 200|40*|500)
* - when during the pipeline process an Exception is thrown.
*
* When the middleware pipeline is finished the application prints the header and the output.
*
* If a middleware other than the Routing, Dispatcher and Final Middleware has no priority set, it will be
* considered to have priority = 50.
*
* @return ServiceInterface
*/
abstract public function run() : ServiceInterface;
/**
* Renders the response body and sends it to the client.
*
* @return void
*
* @codeCoverageIgnore - no output for tests
*/
abstract public function renderOutput() : void;
/**
* Sends the response body to the client.
*
* @return void
*
* @codeCoverageIgnore - no output for tests
*/
abstract public function sendOutput() : void;
}
<file_sep>/tests/WebHemiTest/Middleware/FinalMiddlewareTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Middleware;
use PHPUnit\Framework\TestCase;
use WebHemi\Auth\ServiceInterface as AuthAdapterInterface;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Environment\ServiceAdapter\Base\ServiceAdapter as EnvironmentManager;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\ServerRequest;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\Response;
use WebHemi\Logger\ServiceInterface as LogAdapterInterface;
use WebHemi\Middleware\Common\FinalMiddleware;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use WebHemiTest\TestService\EmptyLogger;
/**
* Class FinalMiddlewareTest.
*/
class FinalMiddlewareTest extends TestCase
{
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Tests middleware with no error.
*/
public function testMiddlewareNoError()
{
$output = 'Hello World!';
$request = new ServerRequest('GET', '/');
$body = \GuzzleHttp\Psr7\stream_for($output);
$response = new Response(Response::STATUS_OK);
$response = $response->withBody($body);
$authAdapterProphecy = $this->prophesize(AuthAdapterInterface::class);
$environmentProphecy = $this->prophesize(EnvironmentManager::class);
/** @var AuthAdapterInterface $authAdapter */
$authAdapter = $authAdapterProphecy->reveal();
/** @var EnvironmentManager $environmentManager */
$environmentManager = $environmentProphecy->reveal();
/** @var LogAdapterInterface $logAdapter */
$logAdapter = new EmptyLogger(new Config([]), '');
$middleware = new FinalMiddleware($authAdapter, $environmentManager, $logAdapter);
/** @var ResponseInterface $result */
$middleware($request, $response);
$this->assertSame(Response::STATUS_OK, $response->getStatusCode());
$this->assertFalse($request->isXmlHttpRequest());
}
/**
* Tests middleware with error.
*/
public function testMiddlewareErrorHandling()
{
$request = new ServerRequest('GET', '/');
$response = new Response(404);
$authAdapterProphecy = $this->prophesize(AuthAdapterInterface::class);
$authAdapterProphecy->hasIdentity()->willReturn(true);
$authAdapterProphecy->getIdentity()->will(
function () {
$userEntity = new UserEntity();
$userEntity->setEmail('<EMAIL>');
return $userEntity;
}
);
$environmentProphecy = $this->prophesize(EnvironmentManager::class);
$environmentProphecy->getSelectedModule()->willReturn("admin");
$environmentProphecy->getClientIp()->willReturn("127.0.0.1");
/** @var AuthAdapterInterface $authAdapter */
$authAdapter = $authAdapterProphecy->reveal();
/** @var EnvironmentManager $environmentManager */
$environmentManager = $environmentProphecy->reveal();
/** @var LogAdapterInterface $logAdapter */
$logAdapter = new EmptyLogger(new Config([]), '');
$middleware = new FinalMiddleware($authAdapter, $environmentManager, $logAdapter);
/** @var ResponseInterface $result */
$middleware($request, $response);
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertSame(404, $response->getStatusCode());
}
/**
* Tests Ajax request.
*/
public function testAjax()
{
$request = new ServerRequest(
'GET',
'/',
[],
null,
'1.1',
['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']
);
$templateData = ['test' => 'data'];
$request = $request->withAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA, $templateData);
$response = new Response(404);
$authAdapterProphecy = $this->prophesize(AuthAdapterInterface::class);
$authAdapterProphecy->hasIdentity()->willReturn(true);
$authAdapterProphecy->getIdentity()->will(
function () {
$userEntity = new UserEntity();
$userEntity->setEmail('<EMAIL>');
return $userEntity;
}
);
$environmentProphecy = $this->prophesize(EnvironmentManager::class);
$environmentProphecy->getSelectedModule()->willReturn("admin");
$environmentProphecy->getClientIp()->willReturn("127.0.0.1");
/** @var AuthAdapterInterface $authAdapter */
$authAdapter = $authAdapterProphecy->reveal();
/** @var EnvironmentManager $environmentManager */
$environmentManager = $environmentProphecy->reveal();
/** @var LogAdapterInterface $logAdapter */
$logAdapter = new EmptyLogger(new Config([]), '');
$middleware = new FinalMiddleware($authAdapter, $environmentManager, $logAdapter);
/** @var ResponseInterface $result */
$middleware($request, $response);
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertSame(404, $response->getStatusCode());
$this->assertTrue($request->isXmlHttpRequest());
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getPolicyListByUserGroup.sql
SELECT
p.`id_policy`,
p.`fk_resource`,
p.`fk_application`,
p.`name`,
p.`title`,
p.`description`,
p.`method`,
p.`is_read_only`,
p.`date_created`,
p.`date_modified`
FROM
`webhemi_policy` AS p
INNER JOIN `webhemi_user_group_to_policy` AS ugtp ON p.id_policy = ugtp.fk_policy
WHERE
ugtp.`fk_user_group` = :idUserGroup
ORDER BY
p.`name`
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Auth/ServiceAdapter/AbstractServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth\ServiceAdapter;
use WebHemi\Auth;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\UserStorage;
/**
* Class AbstractServiceAdapter
*/
abstract class AbstractServiceAdapter implements Auth\ServiceInterface
{
/**
* @var Auth\ResultInterface
*/
private $authResult;
/**
* @var Auth\StorageInterface
*/
private $authStorage;
/**
* @var UserStorage
*/
private $dataStorage;
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* AbstractServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
* @param Auth\ResultInterface $authResultPrototype
* @param Auth\StorageInterface $authStorage
* @param UserStorage $dataStorage
*/
public function __construct(
ConfigurationInterface $configuration,
Auth\ResultInterface $authResultPrototype,
Auth\StorageInterface $authStorage,
UserStorage $dataStorage
) {
$this->configuration = $configuration->getConfig('auth');
$this->authResult = $authResultPrototype;
$this->authStorage = $authStorage;
$this->dataStorage = $dataStorage;
}
/**
* Gets the auth storage instance. (e.g.: AuthSessionStorage)
*
* @return Auth\StorageInterface
*/
protected function getAuthStorage() : Auth\StorageInterface
{
return $this->authStorage;
}
/**
* Gets the data storage instance. (e.g.: UserStorage)
*
* @return UserStorage
*/
protected function getDataStorage() : UserStorage
{
return $this->dataStorage;
}
/**
* Gets a new instance of the auth result container.
*
* @return Auth\ResultInterface
*/
protected function getNewAuthResultInstance() : Auth\ResultInterface
{
return clone $this->authResult;
}
/**
* Authenticates the user.
*
* @param Auth\CredentialInterface $credential
* @return Auth\ResultInterface
*/
abstract public function authenticate(Auth\CredentialInterface $credential) : Auth\ResultInterface;
/**
* Sets the authenticated user.
*
* @param UserEntity $dataEntity
* @return Auth\ServiceInterface
*/
public function setIdentity(UserEntity $dataEntity) : Auth\ServiceInterface
{
$this->authStorage->setIdentity($dataEntity);
return $this;
}
/**
* Checks whether the user is authenticated or not.
*
* @return bool
*/
public function hasIdentity() : bool
{
return $this->authStorage->hasIdentity();
}
/**
* Gets the authenticated user's entity.
*
* @return UserEntity|null
*/
public function getIdentity() : ? UserEntity
{
return $this->authStorage->getIdentity();
}
/**
* Clears the session.
*
* @return Auth\ServiceInterface
*/
public function clearIdentity() : Auth\ServiceInterface
{
$this->authStorage->clearIdentity();
return $this;
}
}
<file_sep>/config/modules/admin/pipeline.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Middleware\Security\AclMiddleware;
use WebHemi\Middleware\Security\AccessLogMiddleware;
return [
'middleware_pipeline' => [
'Admin' => [
['service' => AclMiddleware::class, 'priority' => 10],
['service' => AccessLogMiddleware::class, 'priority' => 11],
],
],
];
<file_sep>/tests/WebHemiTest/TestService/EmptyFtpAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Ftp\ServiceAdapter\AbstractServiceAdapter;
use WebHemi\Ftp\ServiceInterface;
/**
* Class EmptyFtpAdapter
*/
class EmptyFtpAdapter extends AbstractServiceAdapter
{
/** @var bool */
public $connected = false;
/** @var bool */
public $secure = false;
/** @var bool */
public $passive = false;
/** @var string */
public $remotePath = '/';
/** @var string */
public $remoteFilename = 'test.txt';
/** @var array */
protected $remoteFileSystem = [];
/**
* Connect and login to remote host.
*
* @return ServiceInterface
*/
public function connect() : ServiceInterface
{
$this->connected = true;
return $this;
}
/**
* Disconnect from remote host.
*
* @return ServiceInterface
*/
public function disconnect() : ServiceInterface
{
$this->connected = false;
return $this;
}
/**
* Toggles connection security level.
*
* @param bool $state
* @return ServiceInterface
*/
public function setSecureConnection(bool $state) : ServiceInterface
{
$this->secure = $state;
return $this;
}
/**
* Toggles connection passive mode.
*
* @param bool $state
* @return ServiceInterface
*/
public function setPassiveMode(bool $state) : ServiceInterface
{
$this->passive = $state;
return $this;
}
/**
* Sets remote path.
*
* @param string $path
* @return ServiceInterface
*/
public function setRemotePath(string $path) : ServiceInterface
{
$this->remotePath = $path;
return $this;
}
/**
* Gets remote path.
*
* @return string
*/
public function getRemotePath() : string
{
return $this->remotePath;
}
/**
* Check remote file name.
*
* @param string $remoteFileName
*/
protected function checkRemoteFile(string&$remoteFileName) : void
{
if (!$remoteFileName) {
$remoteFileName = $this->remoteFilename;
}
}
/**
* Lists remote path.
*
* @param null|string $path
* @param bool|null $changeToDirectory
* @return array
*/
public function getRemoteFileList(? string $path, ? bool $changeToDirectory) : array
{
$remoteFileList = [];
if ($changeToDirectory) {
$this->setRemotePath($path);
}
foreach ($this->remoteFileSystem as $file) {
if (isset($file['remotePath']) && isset($file['remoteFile']) && $file['remotePath'] == $this->remotePath) {
$remoteFileList[] = $file['remoteFile'];
}
}
return $remoteFileList;
}
/**
* Uploads file to remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $sourceFileName
* @param string $destinationFileName
* @param int $fileMode
* @return mixed
*/
public function upload(
string $sourceFileName,
string $destinationFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface {
$this->remoteFileSystem[] = [
'localPath' => $this->localPath,
'localFile' => $sourceFileName,
'remotePath' => $this->remotePath,
'remoteFile' => $destinationFileName,
'mode' => $fileMode
];
return $this;
}
/**
* Downloads file from remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $remoteFileName
* @param string $localFileName
* @param int $fileMode
* @return mixed
*/
public function download(
string $remoteFileName,
string&$localFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface {
$localFileName .= '';
unset($remoteFileName, $fileMode);
return $this;
}
/**
* Moves file on remote host.
*
* @param string $currentPath
* @param string $newPath
* @return ServiceInterface
*/
public function moveRemoteFile(string $currentPath, string $newPath) : ServiceInterface
{
$oldFilePath = dirname($currentPath);
$oldFileName = basename($currentPath);
$newFilePath = dirname($newPath);
$newFileName = basename($newPath);
foreach ($this->remoteFileSystem as $index => $file) {
if (!($file['remoteFile'] == $oldFileName && $file['remotePath'] == $oldFilePath)) {
$this->remoteFileSystem[$index]['remoteFile'] = $newFileName;
$this->remoteFileSystem[$index]['remotePath'] = $newFilePath;
}
}
return $this;
}
/**
* Deletes file on remote host.
*
* @param string $path
* @return ServiceInterface
*/
public function deleteRemoteFile(string $path) : ServiceInterface
{
$tmp = [];
$filePath = dirname($path);
$fileName = basename($path);
foreach ($this->remoteFileSystem as $file) {
if (!($file['remoteFile'] == $fileName && $file['remotePath'] == $filePath)) {
$tmp[] = $file;
}
}
$this->remoteFileSystem = $tmp;
return $this;
}
/**
* @param string $localFileName
* @param bool $forceUnique
*/
public function testLocalFile(string&$localFileName, bool $forceUnique = false) : void
{
$this->checkLocalFile($localFileName, $forceUnique);
}
/**
* @param string $permissions
* @return string
*/
public function convertOctalChmod(string $permissions) : string
{
return $this->getOctalChmod($permissions);
}
}
<file_sep>/src/WebHemi/Auth/Storage/Session.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth\Storage;
use WebHemi\Auth\StorageInterface;
use WebHemi\Session\ServiceInterface as SessionInterface;
use WebHemi\Data\Entity\UserEntity;
/**
* Class Session
*/
class Session implements StorageInterface
{
/**
* @var string
*/
private $sessionKey = '_auth_identity';
/**
* @var SessionInterface
*/
private $sessionManager;
/**
* Session constructor.
*
* @param SessionInterface $sessionManager
*/
public function __construct(SessionInterface $sessionManager)
{
$this->sessionManager = $sessionManager;
}
/**
* Sets the authenticated user.
*
* @param UserEntity $dataEntity
* @return StorageInterface
*/
public function setIdentity(UserEntity $dataEntity) : StorageInterface
{
// for safety purposes
$this->sessionManager->regenerateId();
// set user entity into the session as read-only
$this->sessionManager->set($this->sessionKey, $dataEntity);
return $this;
}
/**
* Checks if there is any authenticated user.
*
* @return bool
*/
public function hasIdentity() : bool
{
return $this->sessionManager->has($this->sessionKey);
}
/**
* Gets the authenticated user.
*
* @return null|UserEntity
*/
public function getIdentity() : ? UserEntity
{
return $this->sessionManager->get($this->sessionKey);
}
/**
* Clears the session.
*
* @return StorageInterface
*/
public function clearIdentity() : StorageInterface
{
// force delete read-only data.
$this->sessionManager->delete($this->sessionKey, true);
// for safety purposes
$this->sessionManager->regenerateId();
return $this;
}
}
<file_sep>/src/WebHemi/Middleware/Common/RoutingMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Common;
use Exception;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Router\ServiceInterface as RouterInterface;
use WebHemi\Middleware\MiddlewareInterface;
use WebHemi\Router\Result;
/**
* Class RoutingMiddleware.
*/
class RoutingMiddleware implements MiddlewareInterface
{
/**
* @var RouterInterface
*/
private $routerAdapter;
/**
* RoutingMiddleware constructor.
*
* @param RouterInterface $routerAdapter
*/
public function __construct(RouterInterface $routerAdapter)
{
$this->routerAdapter = $routerAdapter;
}
/**
* From the request the middleware determines whether the requested URI is valid or not.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @throws Exception
* @return void
*/
public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void
{
$routeResult = $this->routerAdapter->match($request);
if ($routeResult->getStatus() !== Result\Result::CODE_FOUND) {
throw new Exception($routeResult->getStatusReason(), $routeResult->getStatus());
} else {
$request = $request
->withAttribute(
ServerRequestInterface::REQUEST_ATTR_RESOLVED_ACTION_CLASS,
$routeResult->getMatchedMiddleware()
);
$request = $request
->withAttribute(
ServerRequestInterface::REQUEST_ATTR_ROUTING_RESOURCE,
$routeResult->getResource()
);
$request = $request
->withAttribute(
ServerRequestInterface::REQUEST_ATTR_ROUTING_PARAMETERS,
$routeResult->getParameters()
);
}
$response = $response->withStatus(ResponseInterface::STATUS_PROCESSING);
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyUserStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Data\Entity\EntityInterface as DataEntityInterface;
use WebHemi\Data\Storage\UserStorage;
/**
* Class EmptyUserStorage.
*
*/
class EmptyUserStorage extends UserStorage
{
}
<file_sep>/src/WebHemi/DependencyInjection/ServiceAdapter/AbstractAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\DependencyInjection\ServiceAdapter;
use RuntimeException;
use InvalidArgumentException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\DependencyInjection\ServiceInterface;
use WebHemi\GeneralLib;
/**
* Class AbstractAdapter
*/
abstract class AbstractAdapter implements ServiceInterface
{
public const SERVICE_SOURCE_MODULE = 'source_module';
public const SERVICE_CLASS = 'class';
public const SERVICE_ARGUMENTS = 'arguments';
public const SERVICE_METHOD_CALL = 'calls';
public const SERVICE_SHARE = 'shared';
public const SERVICE_SYNTHETIC = 'synthetic';
public const SERVICE_INHERIT = 'inherits';
public const SERVICE_INITIALIZED = 'initialized';
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* @var array
*/
protected $registeredModules = [];
/**
* @var array
*/
protected $serviceLibrary = [];
/**
* @var array
*/
protected $serviceConfiguration = [];
/**
* AbstractAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$this->configuration = $configuration->getConfig('dependencies');
}
/**
* Returns true if the given service is registered.
*
* @param string $identifier
* @return bool
*/
abstract public function has(string $identifier) : bool;
/**
* Gets a service.
*
* @param string $identifier
* @return object
*/
abstract public function get(string $identifier);
/**
* Register the service.
*
* @param string $identifier
* @param string $moduleName
* @return ServiceInterface
*/
public function registerService(string $identifier, string $moduleName = 'Global') : ServiceInterface
{
// Check if the service is not initialized yet.
if (!$this->serviceIsInitialized($identifier)) {
// overwrite if it was registered earlier.
$this->serviceLibrary[$identifier] = [
self::SERVICE_SOURCE_MODULE => $moduleName,
self::SERVICE_INITIALIZED => false,
self::SERVICE_ARGUMENTS => $this->resolveServiceArguments($identifier, $moduleName),
self::SERVICE_METHOD_CALL => $this->resolveMethodCalls($identifier, $moduleName),
self::SERVICE_SHARE => $this->resolveShares($identifier, $moduleName),
self::SERVICE_CLASS => $this->resolveServiceClassName($identifier, $moduleName),
];
}
return $this;
}
/**
* Checks if the service has been already initialized.
*
* @param string $identifier
* @return bool
*/
protected function serviceIsInitialized(string $identifier) : bool
{
return isset($this->serviceLibrary[$identifier])
&& $this->serviceLibrary[$identifier][self::SERVICE_INITIALIZED];
}
/**
* Retrieves configuration for a service.
*
* @param string $identifier
* @param string $moduleName
* @return array
*/
public function getServiceConfiguration(string $identifier, string $moduleName = null) : array
{
$configuration = $this->serviceLibrary[$identifier] ?? [];
if (isset($configuration[self::SERVICE_SOURCE_MODULE])
&& ($configuration[self::SERVICE_SOURCE_MODULE] == $moduleName || is_null($moduleName))
) {
return $configuration;
}
// Get all registered module configurations and merge them together.
$this->getAllRegisteredModuleConfigurations($configuration, $moduleName.'/'.$identifier);
// Resolve inheritance.
$this->resolveInheritance($configuration, $identifier);
$this->serviceConfiguration[$identifier] = $configuration;
return $configuration;
}
/**
* Get all registered module configurations and merge them together.
*
* @param array $configuration
* @param string $path
*/
protected function getAllRegisteredModuleConfigurations(array &$configuration, string $path) : void
{
if ($this->configuration->has($path)) {
$moduleConfig = $this->configuration->getData($path);
$configuration = GeneralLib::mergeArrayOverwrite($configuration, $moduleConfig);
}
}
/**
* Resolves the config inheritance.
*
* @param array $configuration
* @param string $identifier
*/
protected function resolveInheritance(array &$configuration, string $identifier) : void
{
if (isset($configuration[self::SERVICE_INHERIT])) {
$parentConfiguration = $this->getServiceConfiguration($configuration[self::SERVICE_INHERIT]);
foreach ($configuration as $key => $value) {
$parentConfiguration[$key] = $value;
}
// If the class name is not explicitly defined but the identifier is a class, the inherited class name
// should be overwritten.
if (!isset($configuration[self::SERVICE_CLASS]) && class_exists($identifier)) {
$parentConfiguration[self::SERVICE_CLASS] = $identifier;
}
$configuration = $parentConfiguration;
unset($parentConfiguration, $configuration[self::SERVICE_INHERIT]);
}
}
/**
* Retrieves real service class name.
*
* @param string $identifier
* @param string $moduleName
* @return string
*/
protected function resolveServiceClassName(string $identifier, string $moduleName) : string
{
$serviceConfiguration = $this->getServiceConfiguration($identifier, $moduleName);
$className = $serviceConfiguration[self::SERVICE_CLASS] ?? $identifier;
if (!class_exists($className)) {
throw new RuntimeException(
sprintf('The resolved class "%s" cannot be found.', $className),
1002
);
}
return $className;
}
/**
* Gets argument list and resolves alias references.
*
* @param string $identifier
* @param string $moduleName
* @return array
*/
protected function resolveServiceArguments(string $identifier, string $moduleName) : array
{
$serviceConfiguration = $this->getServiceConfiguration($identifier, $moduleName);
return $serviceConfiguration[self::SERVICE_ARGUMENTS] ?? [];
}
/**
* Returns the service post-init method calls.
*
* @param string $identifier
* @param string $moduleName
* @return array
*/
protected function resolveMethodCalls(string $identifier, string $moduleName) : array
{
$serviceConfiguration = $this->getServiceConfiguration($identifier, $moduleName);
return $serviceConfiguration[self::SERVICE_METHOD_CALL] ?? [];
}
/**
* Returns the service share status.
*
* @param string $identifier
* @param string $moduleName
* @return bool
*/
protected function resolveShares(string $identifier, string $moduleName) : bool
{
$serviceConfiguration = $this->getServiceConfiguration($identifier, $moduleName);
return $serviceConfiguration[self::SERVICE_SHARE] ?? false;
}
/**
* Register the service.
*
* @param string $identifier
* @param object $serviceInstance
* @return ServiceInterface
*/
abstract public function registerServiceInstance(string $identifier, $serviceInstance) : ServiceInterface;
/**
* Register module specific services.
* If a service is already registered in the Global namespace, it will be skipped.
*
* @param string $moduleName
* @return ServiceInterface
*/
public function registerModuleServices(string $moduleName) : ServiceInterface
{
if (!$this->configuration->has($moduleName)) {
throw new InvalidArgumentException(
sprintf('\'%s\' is not a valid module name', $moduleName),
1002
);
}
$this->registeredModules[] = $moduleName;
$services = array_keys($this->configuration->getData($moduleName));
while (key($services) !== null) {
$this->registerService(current($services), $moduleName);
next($services);
}
return $this;
}
}
<file_sep>/src/WebHemi/Middleware/Security/AclMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Security;
use RuntimeException;
use WebHemi\Acl\ServiceInterface as AclInterface;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Data\Entity;
use WebHemi\Data\Storage;
use WebHemi\Middleware\Action;
use WebHemi\Middleware\MiddlewareInterface;
/**
* Class AclMiddleware.
*/
class AclMiddleware implements MiddlewareInterface
{
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var AclInterface
*/
private $aclAdapter;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var Storage\ApplicationStorage
*/
private $applicationStorage;
/**
* @var Storage\ResourceStorage
*/
private $resourceStorage;
/**
* @var Storage\UserStorage
*/
private $userStorage;
/**
* @var array
*/
private $middlewareWhiteList = [
Action\Auth\LoginAction::class,
Action\Auth\LogoutAction::class,
];
/**
* AclMiddleware constructor.
*
* @param AuthInterface $authAdapter
* @param AclInterface $aclAdapter
* @param EnvironmentInterface $environmentManager
* @param Storage\ApplicationStorage $applicationStorage
* @param Storage\ResourceStorage $resourceStorage
* @param Storage\UserStorage $userStorage
*/
public function __construct(
AuthInterface $authAdapter,
AclInterface $aclAdapter,
EnvironmentInterface $environmentManager,
Storage\ApplicationStorage $applicationStorage,
Storage\ResourceStorage $resourceStorage,
Storage\UserStorage $userStorage
) {
$this->authAdapter = $authAdapter;
$this->aclAdapter = $aclAdapter;
$this->environmentManager = $environmentManager;
$this->applicationStorage = $applicationStorage;
$this->resourceStorage = $resourceStorage;
$this->userStorage = $userStorage;
}
/**
* A middleware is a callable. It can do whatever is appropriate with the Request and Response objects.
* The only hard requirement is that a middleware MUST return an instance of \Psr\Http\Message\ResponseInterface.
* Each middleware SHOULD invoke the next middleware and pass it Request and Response objects as arguments.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @throws RuntimeException
* @return void
*/
public function __invoke(ServerRequestInterface&$request, ResponseInterface&$response) : void
{
$actionMiddleware = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_RESOLVED_ACTION_CLASS);
$resourceName = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_ROUTING_RESOURCE);
if (in_array($actionMiddleware, $this->middlewareWhiteList)) {
return;
}
/**
* @var Entity\UserEntity|null $identity
*/
$identity = $this->authAdapter->getIdentity();
if ($identity instanceof Entity\UserEntity) {
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->applicationStorage
->getApplicationByName($this->environmentManager->getSelectedApplication());
/**
* @var Entity\ResourceEntity $resourceEntity
*/
$resourceEntity = $this->resourceStorage->getResourceByName($resourceName);
// Check the user against the application and resource
$hasAccess = $this->aclAdapter->isAllowed($identity, $resourceEntity, $applicationEntity);
$request = $this->setIdentityForTemplate($request, $identity);
if (!$hasAccess) {
throw new RuntimeException('Forbidden', 403);
}
} else {
// Instead of throw a useless 401 error here, redirect the user to the login page
$appUri = rtrim($this->environmentManager->getSelectedApplicationUri(), '/');
$response = $response->withStatus(ResponseInterface::STATUS_REDIRECT, 'Found')
->withHeader('Location', $appUri.'/auth/login');
}
}
/**
* Set identified user data for the templates
*
* @param ServerRequestInterface $request
* @param Entity\UserEntity $identity
* @return ServerRequestInterface
*/
private function setIdentityForTemplate(
ServerRequestInterface $request,
Entity\UserEntity $identity
) : ServerRequestInterface {
// Set authenticated user for the templates
$templateData = $request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA, []);
$templateData[ServerRequestInterface::REQUEST_ATTR_AUTHENTICATED_USER] = $identity;
$templateData[ServerRequestInterface::REQUEST_ATTR_AUTHENTICATED_USER_META] = $this->userStorage
->getUserMetaListByUser((int) $identity->getUserId());
return $request->withAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA, $templateData);
}
}
<file_sep>/src/WebHemi/Data/Entity/FilesystemPublishedDocumentEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemPublishedDocumentEntity
*/
class FilesystemPublishedDocumentEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_filesystem' => null,
'id_filesystem_document' => null,
'fk_application' => null,
'fk_category' => null,
'fk_author' => null,
'path' => null,
'basename' => null,
'uri' => null,
'title' => null,
'description' => null,
'content_lead' => null,
'content_body' => null,
'date_published' => null,
];
/**
* @param int $identifier
* @return FilesystemPublishedDocumentEntity
*/
public function setFilesystemId(int $identifier) : FilesystemPublishedDocumentEntity
{
$this->container['id_filesystem'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemId() : ? int
{
return !is_null($this->container['id_filesystem'])
? (int) $this->container['id_filesystem']
: null;
}
/**
* @param int $identifier
* @return FilesystemPublishedDocumentEntity
*/
public function setFilesystemDocumentId(int $identifier) : FilesystemPublishedDocumentEntity
{
$this->container['id_filesystem_document'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemDocumentId() : ? int
{
return !is_null($this->container['id_filesystem_document'])
? (int) $this->container['id_filesystem_document']
: null;
}
/**
* @param int $applicationIdentifier
* @return FilesystemPublishedDocumentEntity
*/
public function setApplicationId(int $applicationIdentifier) : FilesystemPublishedDocumentEntity
{
$this->container['fk_application'] = $applicationIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getApplicationId() : ? int
{
return !is_null($this->container['fk_application'])
? (int) $this->container['fk_application']
: null;
}
/**
* @param int $categoryIdentifier
* @return FilesystemPublishedDocumentEntity
*/
public function setCategoryId(int $categoryIdentifier) : FilesystemPublishedDocumentEntity
{
$this->container['fk_category'] = $categoryIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getCategoryId() : ? int
{
return !is_null($this->container['fk_category'])
? (int) $this->container['fk_category']
: null;
}
/**
* @param int $authorIdentifier
* @return FilesystemPublishedDocumentEntity
*/
public function setAuthorId(int $authorIdentifier) : FilesystemPublishedDocumentEntity
{
$this->container['fk_author'] = $authorIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getAuthorId() : ? int
{
return !is_null($this->container['fk_author'])
? (int) $this->container['fk_author']
: null;
}
/**
* @param string $path
* @return FilesystemPublishedDocumentEntity
*/
public function setPath(string $path) : FilesystemPublishedDocumentEntity
{
$this->container['path'] = $path;
return $this;
}
/**
* @return null|string
*/
public function getPath() : ? string
{
return $this->container['path'];
}
/**
* @param string $baseName
* @return FilesystemPublishedDocumentEntity
*/
public function setBaseName(string $baseName) : FilesystemPublishedDocumentEntity
{
$this->container['basename'] = $baseName;
return $this;
}
/**
* @return null|string
*/
public function getBaseName() : ? string
{
return $this->container['basename'];
}
/**
* @param string $uri
* @return FilesystemPublishedDocumentEntity
*/
public function setUri(string $uri) : FilesystemPublishedDocumentEntity
{
$this->container['uri'] = $uri;
return $this;
}
/**
* @return null|string
*/
public function getUri() : ? string
{
return $this->container['uri'];
}
/**
* @param string $title
* @return FilesystemPublishedDocumentEntity
*/
public function setTitle(string $title) : FilesystemPublishedDocumentEntity
{
$this->container['title'] = $title;
return $this;
}
/**
* @return null|string
*/
public function getTitle() : ? string
{
return $this->container['title'];
}
/**
* @param string $description
* @return FilesystemPublishedDocumentEntity
*/
public function setDescription(string $description) : FilesystemPublishedDocumentEntity
{
$this->container['description'] = $description;
return $this;
}
/**
* @return null|string
*/
public function getDescription() : ? string
{
return $this->container['description'];
}
/**
* @param string $contentLead
* @return FilesystemPublishedDocumentEntity
*/
public function setContentLead(string $contentLead) : FilesystemPublishedDocumentEntity
{
$this->container['content_lead'] = $contentLead;
return $this;
}
/**
* @return null|string
*/
public function getContentLead() : ? string
{
return $this->container['content_lead'];
}
/**
* @param string $contentBody
* @return FilesystemPublishedDocumentEntity
*/
public function setContentBody(string $contentBody) : FilesystemPublishedDocumentEntity
{
$this->container['content_body'] = $contentBody;
return $this;
}
/**
* @return null|string
*/
public function getContentBody() : ? string
{
return $this->container['content_body'];
}
/**
* @param DateTime $dateTime
* @return FilesystemPublishedDocumentEntity
*/
public function setDatePublished(DateTime $dateTime) : FilesystemPublishedDocumentEntity
{
$this->container['date_published'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDatePublished() : ? DateTime
{
return !empty($this->container['date_published'])
? new DateTime($this->container['date_published'])
: null;
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemByApplicationAndPath.sql
SELECT
fs.`id_filesystem`,
fs.`fk_application`,
fs.`fk_category`,
fs.`fk_parent_node`,
fs.`fk_filesystem_document`,
fs.`fk_filesystem_file`,
fs.`fk_filesystem_directory`,
fs.`fk_filesystem_link`,
fs.`path`,
fs.`basename`,
REPLACE(CONCAT(fs.`path`,'/',fs.`basename`), '//', '/') AS uri,
fs.`title`,
fs.`description`,
fs.`is_hidden`,
fs.`is_read_only`,
fs.`is_deleted`,
fs.`date_created`,
fs.`date_modified`,
fs.`date_published`
FROM
`webhemi_filesystem` AS fs
WHERE
fs.`fk_application` = :idApplication AND
fs.`path` = :path AND
fs.`basename` = :baseName
<file_sep>/src/WebHemi/MiddlewarePipeline/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\MiddlewarePipeline;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigInterface $configuration
*/
public function __construct(ConfigInterface $configuration);
/**
* Adds module specific pipeline.
*
* @param string $moduleName
* @return ServiceInterface
*/
public function addModulePipeLine(string $moduleName) : ServiceInterface;
/**
* Adds a new middleware to the pipeline queue.
*
* @param string $middleWareClass
* @param int $priority
* @throws RuntimeException
* @return ServiceInterface
*/
public function queueMiddleware(string $middleWareClass, int $priority = 50) : ServiceInterface;
/**
* Starts the pipeline.
*
* @return null|string
*/
public function start() : ? string;
/**
* Gets next element from the pipeline.
*
* @return null|string
*/
public function next() : ? string;
/**
* Gets the full pipeline list.
*
* @return array
*/
public function getPipelineList() : array;
}
<file_sep>/src/WebHemi/Form/Element/Html/HtmlElement.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form\Element\Html;
/**
* Class HtmlElement.
*/
class HtmlElement extends AbstractElement
{
public const HTML_ELEMENT_BUTTON = 'button';
public const HTML_ELEMENT_FORM = 'form';
public const HTML_ELEMENT_HIDDEN = 'hidden';
public const HTML_ELEMENT_INPUT_CHECKBOX = 'inputCheckbox';
public const HTML_ELEMENT_INPUT_FILE = 'inputFile';
public const HTML_ELEMENT_INPUT_IMAGE = 'inputImage';
public const HTML_ELEMENT_INPUT_PASSWORD = 'inputPassword';
public const HTML_ELEMENT_INPUT_RADIO = 'inputRadio';
public const HTML_ELEMENT_INPUT_TEXT = 'inputText';
public const HTML_ELEMENT_RESET = 'reset';
public const HTML_ELEMENT_SELECT = 'select';
public const HTML_ELEMENT_SUBMIT = 'submit';
public const HTML_ELEMENT_TEXTAREA = 'textarea';
/**
* @var array
*/
protected $validTypes = [
self::HTML_ELEMENT_BUTTON,
self::HTML_ELEMENT_FORM,
self::HTML_ELEMENT_HIDDEN,
self::HTML_ELEMENT_INPUT_CHECKBOX,
self::HTML_ELEMENT_INPUT_FILE,
self::HTML_ELEMENT_INPUT_IMAGE,
self::HTML_ELEMENT_INPUT_PASSWORD,
self::HTML_ELEMENT_INPUT_RADIO,
self::HTML_ELEMENT_INPUT_TEXT,
self::HTML_ELEMENT_RESET,
self::HTML_ELEMENT_SELECT,
self::HTML_ELEMENT_SUBMIT,
self::HTML_ELEMENT_TEXTAREA,
];
}
<file_sep>/tests/WebHemiTest/TestData/sql/authentication_test.rollback.sql
DELETE FROM `webhemi_user` WHERE `id_user` IN (90000, 90001, 90002);
<file_sep>/src/WebHemi/I18n/DriverInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\I18n;
/**
* Interface DriverInterface.
*/
interface DriverInterface
{
/**
* DriverInterface constructor.
*
* @param ServiceInterface $i18nService
*/
public function __construct(ServiceInterface $i18nService);
/**
* Translates the given text.
*
* @param string $text
* @return string
*/
public function translate(string $text) : string;
}
<file_sep>/src/WebHemi/Renderer/Helper/GetTagsHelper.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Helper;
use WebHemi\Data\Entity;
use WebHemi\Data\Storage\ApplicationStorage;
use WebHemi\Data\Storage\FilesystemStorage;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Renderer\HelperInterface;
use WebHemi\Router\ProxyInterface;
/**
* Class GetTagsHelper
*/
class GetTagsHelper implements HelperInterface
{
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var ApplicationStorage
*/
private $applicationStorage;
/**
* @var FilesystemStorage
*/
private $filesystemStorage;
/**
* GetTagsHelper constructor.
*
* @param EnvironmentInterface $environmentManager
* @param ApplicationStorage $applicationStorage
* @param FilesystemStorage $filesystemStorage
*/
public function __construct(
EnvironmentInterface $environmentManager,
ApplicationStorage $applicationStorage,
FilesystemStorage $filesystemStorage
) {
$this->environmentManager = $environmentManager;
$this->applicationStorage = $applicationStorage;
$this->filesystemStorage = $filesystemStorage;
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'getTags';
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{{ getTags(order_by, limit) }}';
}
/**
* Gets helper options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Returns the tags for the current application.';
}
/**
* A renderer helper should be called with its name.
*
* @return array
*/
public function __invoke() : array
{
$tags = [];
/**
* @var Entity\ApplicationEntity $application
*/
$application = $this->applicationStorage
->getApplicationByName($this->environmentManager->getSelectedApplication());
$applicationId = $application->getApplicationId();
/**
* @var Entity\FilesystemDirectoryDataEntity $categoryDirectoryData
*/
$categoryDirectoryData = $this->filesystemStorage
->getFilesystemDirectoryDataByApplicationAndProxy((int) $applicationId, ProxyInterface::LIST_TAG);
/**
* @var Entity\EntitySet $tagList
*/
$tagList = $this->filesystemStorage
->getFilesystemTagListByApplication((int) $applicationId);
foreach ($tagList as $tagEntity) {
$tags[] = [
'path' => $categoryDirectoryData->getUri(),
'name' => $tagEntity->getName(),
'title' => $tagEntity->getTitle()
];
}
return $tags;
}
}
<file_sep>/tests/WebHemiTest/Acl/AclTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Acl;
use PDO;
use WebHemi\Acl\ServiceAdapter\Base\ServiceAdapter as Acl;
use WebHemi\Acl\ServiceInterface as AclAdapterInterface;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Data\Driver\PDO\SQLite\DriverAdapter as SQLiteDriver;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\PolicyEntity;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Entity\UserGroupEntity;
use WebHemi\Data\Query\SQLite\QueryAdapter as SQLiteAdapter;
use WebHemi\Data\Storage\UserStorage;
use WebHemi\Data\Storage\PolicyStorage;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\IncompleteTestError;
use PHPUnit\Framework\SkippedTestError;
use WebHemiTest\TestService\EmptyEnvironmentManager;
/**
* Class AclTest
*/
class AclTest extends TestCase
{
/** @var array */
protected $config;
/** @var array */
protected $get = [];
/** @var array */
protected $post = [];
/** @var array */
protected $server;
/** @var array */
protected $cookie = [];
/** @var array */
protected $files = [];
use AssertTrait;
use InvokePrivateMethodTrait;
/** @var PDO */
protected static $dataDriver;
/** @var SQLiteAdapter */
protected static $adapter;
/**
* Check requirements - also checks SQLite availability.
*/
protected function checkRequirements()
{
if (!extension_loaded('pdo_sqlite')) {
throw new SkippedTestError('No SQLite Available');
}
parent::checkRequirements();
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
$databaseFile = realpath(__DIR__ . '/../../../build/webhemi_schema.sqlite3');
/** @var PDO dataDriver */
self::$dataDriver = new SQLiteDriver('sqlite:' . $databaseFile);
$fixture = realpath(__DIR__ . '/../TestData/sql/acl_test.sql');
$setUpSql = file($fixture);
if ($setUpSql) {
foreach ($setUpSql as $sql) {
$result = self::$dataDriver->query($sql);
if (!$result) {
throw new IncompleteTestError(
'Cannot set up test database: '.json_encode(self::$dataDriver->errorInfo()).'; query: '.$sql
);
}
}
}
self::$adapter = new SQLiteAdapter(self::$dataDriver);
}
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->config = require __DIR__ . '/../test_config.php';
}
/**
* Tests constructor.
*/
public function testConstructor()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$userStorage = new UserStorage(
self::$adapter,
new EntitySet(),
new UserEntity(),
new UserGroupEntity()
);
$policyStorage = new PolicyStorage(
self::$adapter,
new EntitySet(),
new PolicyEntity()
);
$aclAdapter = new Acl(
$environmentManager,
$userStorage,
$policyStorage
);
$this->assertInstanceOf(AclAdapterInterface::class, $aclAdapter);
}
/**
* Tests access control validation with actual data.
*
* So the privileges are set as follows:
*
* Application ids: 90000
* Resource ids: 90000
* Policy ids: 90000 (admin), 90001 (GET only), 90002 (POST only), 90003
* User Group ids: 90000, 90001
* User ids: 90000, 90001
*
* User A id 90000 is assigned to User Group id 90000 and to Policy id 90000, 90001
* User B id 90001 is assigned to User Group id 90001 and to Policy id 90003
*
* User Group id 90000 is assigned to Policy id 90000, 90003
* User Group id 90001 is assigned to Policy id 90001, 90003
*
* | Resource | Application | Method | | Policy || Allow User A? | Allow User B? |
* +----------+-------------+--------+----+--------++---------------+---------------+
* | null | null | null | => | 90000 || Yes | No |
* | 90000 | null | GET | => | 90001 || Yes | Yes |
* | null | 90000 | POST | => | 90002 || Yes | No |
* | 90000 | 90000 | null | => | 90003 || Yes | Yes |
*
* User A has the Jolly Joker policy (all resource in all application with all method), so he has access to
* everything.
*/
public function testIsAllowed()
{
$this->server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
'REQUEST_METHOD' => 'POST'
];
$config = new Config($this->config);
$environmentManager = new EmptyEnvironmentManager(
$config,
$this->get,
$this->post,
$this->server,
$this->cookie,
$this->files
);
$userStorage = new UserStorage(
self::$adapter,
new EntitySet(),
new UserEntity(),
new UserGroupEntity()
);
$policyStorage = new PolicyStorage(
self::$adapter,
new EntitySet(),
new PolicyEntity()
);
$aclAdapter = new Acl(
$environmentManager,
$userStorage,
$policyStorage
);
$userEntity = new UserEntity();
$resourceEntity = new ResourceEntity();
$resourceEntity->setResourceId(90000);
$applicationEntity = new ApplicationEntity();
$applicationEntity->setApplicationId(90000);
$userA = clone $userEntity;
$userA->setUserId(90000);
$userB = clone $userEntity;
$userB->setUserId(90001);
// POLICY 90000
// always TRUE because User A is assigned to Policy 90000 which is admin
$this->assertTrue($aclAdapter->isAllowed($userA, null, null, null));
// FALSE because User B isn't assigned to Policy 90000 and not member of User Group 90000
$this->assertFalse($aclAdapter->isAllowed($userB, null, null, null));
// POLICY 90001
// always TRUE because User A is assigned to Policy 90000 which is admin
$this->assertTrue($aclAdapter->isAllowed($userA, $resourceEntity, null, 'GET'));
$this->assertTrue($aclAdapter->isAllowed($userA, $resourceEntity, null, 'POST'));
$this->assertTrue($aclAdapter->isAllowed($userA, $resourceEntity, null, null));
// TRUE for GET, FALSE otherwise
$this->assertTrue($aclAdapter->isAllowed($userB, $resourceEntity, null, 'GET'));
$this->assertFalse($aclAdapter->isAllowed($userB, $resourceEntity, null, 'POST'));
$this->assertFalse($aclAdapter->isAllowed($userB, $resourceEntity, null, null));
// POLICY 90002
// always TRUE because User A is assigned to Policy 90000 which is admin
$this->assertTrue($aclAdapter->isAllowed($userA, null, $applicationEntity, 'GET'));
$this->assertTrue($aclAdapter->isAllowed($userA, null, $applicationEntity, 'POST'));
$this->assertTrue($aclAdapter->isAllowed($userA, null, $applicationEntity, null));
// always FALSE because User B isn't assigned to Policy 90002 and no User Group is assigned to Policy 90002
$this->assertFalse($aclAdapter->isAllowed($userB, null, $applicationEntity, 'GET'));
$this->assertFalse($aclAdapter->isAllowed($userB, null, $applicationEntity, 'POST'));
$this->assertFalse($aclAdapter->isAllowed($userB, null, $applicationEntity, null));
// POLICY 90003
// always TRUE because User A is assigned to Policy 90000 which is admin
$this->assertTrue($aclAdapter->isAllowed($userA, $resourceEntity, $applicationEntity, null));
// TRUE because User B is assigned to Policy 90003 and/or assigned to User Group 90001
$this->assertTrue($aclAdapter->isAllowed($userB, $resourceEntity, $applicationEntity, null));
}
/**
* This method is called after the last test of this test class is run.
*/
public static function tearDownAfterClass()
{
$fixture = realpath(__DIR__.'/../TestData/sql/acl_test.rollback.sql');
$tearDownSql = file($fixture);
if ($tearDownSql) {
foreach ($tearDownSql as $sql) {
self::$dataDriver->query($sql);
}
}
}
}
<file_sep>/src/WebHemi/GeneralLib.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi;
use InvalidArgumentException;
/**
* Class GeneralLib
*/
class GeneralLib
{
/**
* Collects and returns some information about the render time. First call will start start, the others will return.
*
* @return array
*
* @codeCoverageIgnore - don't test core functions.
*/
public static function renderStat() : array
{
static $stat;
// Set timer
if (!isset($stat)) {
$stat = [
'start_time' => microtime(true),
'end_time' => null,
'duration' => 0,
'memory' => 0,
'memory_bytes' => 0,
];
return $stat;
}
// Get time
$stat['end_time'] = microtime(true);
$stat['duration'] = bcsub((string) $stat['end_time'], (string) $stat['start_time'], 4);
// Memory peak
$units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
$bytes = max(memory_get_peak_usage(true), 0);
$stat['memory_bytes'] = number_format($bytes).' bytes';
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
$stat['memory'] = round($bytes, 2).' '.$units[$pow];
return $stat;
}
/**
* Merge config arrays in the correct way.
* This rewrites the given key->value pairs and does not make key->array(value1, value2) like the
* `array_merge_recursive` does.
*
* @throws InvalidArgumentException
* @return array
*/
public static function mergeArrayOverwrite()
{
if (func_num_args() < 2) {
throw new InvalidArgumentException(
__CLASS__ . '::' . __METHOD__ . ' needs two or more array arguments',
1000
);
}
$arrays = func_get_args();
$merged = [];
while ($arrays) {
$array = array_shift($arrays);
if (!is_array($array)) {
throw new InvalidArgumentException(
__CLASS__ . '::' . __METHOD__ . ' encountered a non array argument',
1001
);
}
if (!$array) {
continue;
}
foreach ($array as $key => $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = self::mergeArrayOverwrite($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
}
return $merged;
}
}
<file_sep>/src/WebHemi/Data/Driver/DriverInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Driver;
/**
* Interface DriverInterface.
*/
interface DriverInterface
{
}
<file_sep>/tests/WebHemiTest/Validator/RangeValidatorTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Validator;
use PHPUnit\Framework\TestCase;
use WebHemi\Validator\RangeValidator;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait;
/**
* Class RangeValidatorTest
*/
class RangeValidatorTest extends TestCase
{
use AssertArraysAreSimilarTrait;
/**
* Tests the constructor
*/
public function testConstructor()
{
$validator = new RangeValidator([1,2,3]);
$this->assertAttributeInternalType('array', 'availableValues', $validator);
$this->assertAttributeSame(false, 'validateKeys', $validator);
$validator = new RangeValidator([1,2,3], true);
$this->assertAttributeSame(true, 'validateKeys', $validator);
}
/**
* Tests the validate method
*/
public function testValidator()
{
$validator = new RangeValidator([1,2,3]);
$data = [];
$result = $validator->validate($data);
$this->assertTrue($result);
$this->assertArraysAreSimilar($data, $validator->getValidData());
$data = [1,3];
$result = $validator->validate($data);
$this->assertTrue($result);
$this->assertArraysAreSimilar($data, $validator->getValidData());
$expectedError = ['Some data is out of range: 5, 6'];
$result = $validator->validate([1,3,5,6]);
$this->assertFalse($result);
$this->assertArraysAreSimilar($expectedError, $validator->getErrors());
}
/**
* Tests the validate method
*/
public function testValidatorForKeys()
{
$validator = new RangeValidator(['apple', 'pear', 'orange'], true);
$data = ['apple' => 0, 'pear' => 1];
$result = $validator->validate($data);
$this->assertTrue($result);
$this->assertArraysAreSimilar($data, $validator->getValidData());
$expectedError = ['Some data is out of range: banana'];
$data = ['apple' => 0, 'pear' => 1, 'banana' => 3];
$result = $validator->validate($data);
$this->assertFalse($result);
$this->assertArraysAreSimilar($expectedError, $validator->getErrors());
}
}
<file_sep>/src/WebHemi/Renderer/Helper/GetStatHelper.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Helper;
use WebHemi\GeneralLib;
use WebHemi\Renderer\HelperInterface;
/**
* Class GetStatHelper
*
* @codeCoverageIgnore - config and PHP core functions. No business logic.
*/
class GetStatHelper implements HelperInterface
{
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'getStat';
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{{ getStat() }}';
}
/**
* Gets helper options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Triggers the WebHemi\'s built-in timer and returns the data in array:'.PHP_EOL
. '\'start_time\': the time when the timer had been called (called automatically).'.PHP_EOL
. '\'end_time\': the time when the timer had been stopped (called in a template)'.PHP_EOL
. '\'duration\': the difference in seconds '.PHP_EOL
. '\'memory\': the maximum memory usage during the render in a human readable format '.PHP_EOL;
}
/**
* A renderer helper should be called with its name.
*
* @return array
*/
public function __invoke() : array
{
return GeneralLib::renderStat();
}
}
<file_sep>/src/WebHemi/I18n/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\I18n;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager
);
/**
* Gets the language.
*
* @return string
*/
public function getLanguage() : string;
/**
* Gets the territory.
*
* @return string
*/
public function getTerritory() : string;
/**
* Gets the Locale.
*
* @return string
*/
public function getLocale() : string;
/**
* Gets the code set.
*
* @return string
*/
public function getCodeSet() : string;
/**
* Sets the locale.
*
* @param string $locale
* @return ServiceInterface
*/
public function setLocale(string $locale);
/**
* Gets the time zone.
*
* @return string
*/
public function getTimeZone() : string;
/**
* Sets the time zone.
*
* @param string $timeZone
* @return ServiceInterface
*/
public function setTimeZone(string $timeZone);
}
<file_sep>/tests/WebHemiTest/TestService/TestAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use GuzzleHttp\Psr7\LazyOpenStream;
use GuzzleHttp\Psr7\Uri;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\ServerRequest;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\Response;
/**
* Class TestAdapter.
*/
class TestAdapter
{
/**
* Returns the HTTP request.
*
* @return ServerRequest
*/
public function getRequest()
{
$uri = new Uri('');
$uri = $uri->withScheme('http')
->withHost('unittest.dev')
->withPort(80)
->withPath('/')
->withQuery('');
return new ServerRequest(
'GET',
$uri,
[],
new LazyOpenStream('php://input', 'r+'),
'1.1',
[
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
]
);
}
/**
* Returns the response being sent.
*
* @return Response
*/
public function getResponse()
{
return new Response(Response::STATUS_PROCESSING);
}
}
<file_sep>/src/WebHemi/Validator/RangeValidator.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Validator;
/**
* class RangeValidator.
*/
class RangeValidator implements ValidatorInterface
{
/**
* @var array
*/
private $availableValues;
/**
* @var bool
*/
private $validateKeys;
/**
* @var array
*/
private $errors;
/**
* @var array
*/
private $validData;
/**
* RangeValidator constructor.
*
* @param array $availableValues
* @param bool $validateKeys
*/
public function __construct(array $availableValues, bool $validateKeys = false)
{
$this->availableValues = array_values($availableValues);
$this->validateKeys = $validateKeys;
}
/**
* Validates data.
*
* @param array $values
* @return bool
*/
public function validate(array $values) : bool
{
$data = $this->validateKeys ? array_keys($values) : array_values($values);
$diff = array_diff($data, $this->availableValues);
if (!empty($diff)) {
$this->errors[] = sprintf("Some data is out of range: %s", implode(', ', $diff));
return false;
}
$this->validData = $values;
return true;
}
/**
* Retrieve valid data.
*
* @return array
*/
public function getValidData() : array
{
return $this->validData;
}
/**
* Gets errors from validation.
*
* @return array
*/
public function getErrors() : array
{
return $this->errors;
}
}
<file_sep>/src/WebHemi/Validator/ValidatorInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Validator;
/**
* Interface ValidatorInterface
*/
interface ValidatorInterface
{
/**
* Validates data.
*
* @param array $values
* @return bool
*/
public function validate(array $values) : bool;
/**
* Retrieve valid data.
*
* @return array
*/
public function getValidData() : array;
/**
* Gets errors from validation.
*
* @return array
*/
public function getErrors() : array;
}
<file_sep>/progress.sh
#!/bin/bash
SAVE_CURSOR=$(tput sc)
RESTORE_CURSOR=$(tput rc)
CLEAR=$(tput el)
COUNTER=1
while (($COUNTER <= 100));
do
echo "{\"total\": 100, \"current\":$COUNTER}" > ./data/progress/test.json
((COUNTER++))
sleep 0.2
done
<file_sep>/tests/WebHemiTest/DependencyInjection/BaseAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\DependencyInjection;
use ArrayObject;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
use WebHemi\DateTime;
use WebHemi\DependencyInjection\ServiceAdapter\Base\ServiceAdapter as BaseAdapter;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionAdapterInterface;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\Configuration\ServiceInterface as ConfigInterface;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use WebHemiTest\TestExtension\InvokePrivateMethodTrait;
use WebHemiTest\TestService\EmptyEntity;
use WebHemiTest\TestService\EmptyService;
use PHPUnit\Framework\TestCase;
/**
* Class BaseAdapterTest.
*/
class BaseAdapterTest extends TestCase
{
/** @var Config */
private $config;
use AssertTrait;
use InvokePrivateMethodTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
}
/**
* Test constructor.
*/
public function testConstructor()
{
$adapter = new BaseAdapter($this->config);
$adapter->registerServiceInstance(ConfigInterface::class, $this->config)
->registerModuleServices('Global');
$this->assertInstanceOf(DependencyInjectionAdapterInterface::class, $adapter);
$this->assertAttributeInstanceOf(ConfigInterface::class, 'configuration', $adapter);
}
/**
* Tests initializer.
*/
public function testInitContainer()
{
$adapter = new BaseAdapter($this->config);
$this->assertInstanceOf(DependencyInjectionAdapterInterface::class, $adapter);
// The identifier is an instantiable class
$this->assertTrue($adapter->has(ArrayObject::class));
// The identifier is an alias and not registered yet
$this->assertFalse($adapter->has('actionOk'));
$adapter->registerModuleServices('Global');
// The identifier is an alias and registered
$this->assertTrue($adapter->has('actionOk'));
$adapter->get('actionBad');
// The identifier is an alias and the service is initialized already
$this->assertTrue($adapter->has('actionBad'));
$this->assertFalse($adapter->has('someSuperName'));
$adapter->registerServiceInstance('someSuperName', new EmptyService());
$this->assertTrue($adapter->has('someSuperName'));
}
/**
* Tests service registering.
*/
public function testRegisterService()
{
$adapter = new BaseAdapter($this->config);
$adapter->registerModuleServices('Website')
->registerModuleServices('SomeApp');
/** @var DateTime $actualDate */
$actualDate = $adapter->get('alias1');
$this->assertInstanceOf(DateTime::class, $actualDate);
$this->assertEquals('2016-04-05 01:02:03', $actualDate->format('Y-m-d H:i:s'));
// Get a non-registered service being registered with default parameters.
$serviceResult = $adapter->get(ArrayObject::class);
$this->assertInstanceOf(ArrayObject::class, $serviceResult);
// Get a service which called a method after initialization with another service as parameter.
/** @var ArrayObject $arrayService */
$arrayService = $adapter->get('special');
$this->assertInstanceOf(ArrayObject::class, $arrayService);
$this->assertTrue($arrayService->offsetExists('date'));
$this->assertInstanceOf(DateTime::class, $arrayService->offsetGet('date'));
$this->assertEquals('2016-04-05 01:02:03', $arrayService->offsetGet('date')->format('Y-m-d H:i:s'));
try {
$adapter->registerServiceInstance('custom_identifier', 'not object');
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
$this->assertSame(1001, $exception->getCode());
}
// With get a non registered service, will be able to test the registerServiceToContainer() method's exception
$this->expectException(InvalidArgumentException::class);
$adapter->get('something-not-existing');
}
/**
* Tests scalar argument
*/
public function testScalarArgument()
{
$keyData = DateTime::class;
$adapter = new BaseAdapter($this->config);
$adapter->registerModuleServices('OtherApp');
/** @var EmptyEntity $actualDate */
$actualObject = $adapter->get('aliasWithReference');
$this->assertInstanceOf(EmptyService::class, $actualObject);
$this->assertInstanceOf(DateTime::class, $actualObject->getTheKey());
try {
// In the config this reference belongs to a service which has a parameter that is not marked as literal
// but the alias cannot be identified as a class/service, so it must throw an error. This is the expected
// behavior, and not the one in the Symfony adapter...
$adapter->get('aliasWithFalseReference');
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
}
/** @var EmptyEntity $actualDate */
$actualObject = $adapter->get('aliasWithLiteral');
$this->assertInstanceOf(EmptyService::class, $actualObject);
$this->assertInternalType('string', $actualObject->getTheKey());
$this->assertSame($keyData, $actualObject->getTheKey());
}
/**
* Tests error
*/
public function testInstantiateError()
{
$adapter = new BaseAdapter($this->config);
$adapter->registerModuleServices('Website');
try {
$adapter->get('ThisWillHurt');
} catch (Throwable $exception) {
$this->assertInstanceOf(InvalidArgumentException::class, $exception);
}
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemDocumentList.sql
SELECT
fsd.`id_filesystem_document`,
fsd.`fk_parent_revision`,
fsd.`fk_author`,
fsd.`content_revision`,
fsd.`content_lead`,
fsd.`content_body`,
fsd.`date_created`,
fsd.`date_modified`
FROM
`webhemi_filesystem_document` AS fsd
ORDER BY
fsd.`id_filesystem_document`
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemCategoryById.sql
SELECT
fsc.`id_filesystem_category`,
fsc.`fk_application`,
fsc.`name`,
fsc.`title`,
fsc.`description`,
fsc.`item_order`,
fsc.`date_created`,
fsc.`date_modified`
FROM
`webhemi_filesystem_category` AS fsc
WHERE
fsc.`id_filesystem_category` = :idCategory
<file_sep>/src/WebHemi/Data/Entity/FilesystemDocumentEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemDocumentEntity
*/
class FilesystemDocumentEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_filesystem_document' => null,
'fk_parent_revision' => null,
'fk_author' => null,
'content_revision' => null,
'content_lead' => null,
'content_body' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return FilesystemDocumentEntity
*/
public function setFilesystemDocumentId(int $identifier) : FilesystemDocumentEntity
{
$this->container['id_filesystem_document'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemDocumentId() : ? int
{
return !is_null($this->container['id_filesystem_document'])
? (int) $this->container['id_filesystem_document']
: null;
}
/**
* @param null|int $parentRevisionIdentifier
* @return FilesystemDocumentEntity
*/
public function setParentRevisionId(? int $parentRevisionIdentifier) : FilesystemDocumentEntity
{
$this->container['fk_parent_revision'] = $parentRevisionIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getParentRevisionId() : ? int
{
return !is_null($this->container['fk_parent_revision'])
? (int) $this->container['fk_parent_revision']
: null;
}
/**
* @param null|int $authorIdentifier
* @return FilesystemDocumentEntity
*/
public function setAuthorId(? int $authorIdentifier) : FilesystemDocumentEntity
{
$this->container['fk_author'] = $authorIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getAuthorId() : ? int
{
return !is_null($this->container['fk_author'])
? (int) $this->container['fk_author']
: null;
}
/**
* @param int $contentRevision
* @return FilesystemDocumentEntity
*/
public function setContentRevision(? int $contentRevision) : FilesystemDocumentEntity
{
$this->container['content_revision'] = $contentRevision;
return $this;
}
/**
* @return int|null
*/
public function getContentRevision() : ? int
{
return !is_null($this->container['content_revision'])
? (int) $this->container['content_revision']
: null;
}
/**
* @param string $contentLead
* @return FilesystemDocumentEntity
*/
public function setContentLead(string $contentLead) : FilesystemDocumentEntity
{
$this->container['content_lead'] = $contentLead;
return $this;
}
/**
* @return null|string
*/
public function getContentLead() : ? string
{
return $this->container['content_lead'];
}
/**
* @param string $contentBody
* @return FilesystemDocumentEntity
*/
public function setContentBody(string $contentBody) : FilesystemDocumentEntity
{
$this->container['content_body'] = $contentBody;
return $this;
}
/**
* @return null|string
*/
public function getContentBody() : ? string
{
return $this->container['content_body'];
}
/**
* @param DateTime $dateTime
* @return FilesystemDocumentEntity
*/
public function setDateCreated(DateTime $dateTime) : FilesystemDocumentEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return FilesystemDocumentEntity
*/
public function setDateModified(DateTime $dateTime) : FilesystemDocumentEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/src/WebHemi/Session/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Session\ServiceAdapter\Base;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Session\ServiceInterface;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var string
*/
private $namespace;
/**
* @var string
*/
private $cookiePrefix;
/**
* @var string
*/
private $sessionNameSalt;
/**
* @var array
*/
private $readOnly = [];
/**
* @var array
*/
private $data = [];
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$configuration = $configuration->getData('session');
$this->namespace = $configuration['namespace'];
$this->cookiePrefix = $configuration['cookie_prefix'];
$this->sessionNameSalt = $configuration['session_name_salt'];
// @codeCoverageIgnoreStart
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
ini_set('session.entropy_file', '/dev/urandom');
ini_set('session.entropy_length', '16');
ini_set('session.hash_function', (string) $configuration['hash_function']);
ini_set('session.use_only_cookies', (string) $configuration['use_only_cookies']);
ini_set('session.use_cookies', (string) $configuration['use_cookies']);
ini_set('session.use_trans_sid', (string) $configuration['use_trans_sid']);
ini_set('session.cookie_httponly', (string) $configuration['cookie_http_only']);
ini_set('session.save_path', (string) $configuration['save_path']);
}
// @codeCoverageIgnoreEnd
}
/**
* Saves data back to session.
*/
public function __destruct()
{
$this->write();
// @codeCoverageIgnoreStart
if (defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
session_write_close();
}
// @codeCoverageIgnoreEnd
}
/**
* Reads PHP Session array to class property.
*
* @return void
*
* @codeCoverageIgnore
*/
private function read() : void
{
if (isset($_SESSION[$this->namespace])) {
$this->data = $_SESSION[$this->namespace];
}
}
/**
* Writes class property to PHP Session array.
*
* @return void
*
* @codeCoverageIgnore
*/
private function write() : void
{
if (defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
return;
}
$_SESSION[$this->namespace] = $this->data;
}
/**
* Check whether the session has already been started.
*
* @return bool
*
* @codeCoverageIgnore
*/
private function sessionStarted() : bool
{
// For unit test we give controllable result.
if (defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
return $this->namespace == 'TEST';
}
return session_status() === PHP_SESSION_ACTIVE;
}
/**
* Starts a session.
*
* @param string $name
* @param int $timeOut
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httpOnly
* @return ServiceInterface
*/
public function start(
string $name,
int $timeOut = 3600,
string $path = '/',
? string $domain = null,
bool $secure = false,
bool $httpOnly = false
) : ServiceInterface {
if ($this->sessionStarted()) {
throw new RuntimeException('Cannot start session. Session is already started.', 1000);
}
// @codeCoverageIgnoreStart
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
session_name($this->cookiePrefix.'-'.bin2hex($name.$this->sessionNameSalt));
session_set_cookie_params($timeOut, $path, $domain, $secure, $httpOnly);
session_start();
}
// @codeCoverageIgnoreEnd
$this->read();
return $this;
}
/**
* Regenerates session identifier.
*
* @return ServiceInterface
*/
public function regenerateId() : ServiceInterface
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot regenerate session identifier. Session is not started yet.', 1001);
}
// first save data.
$this->write();
// @codeCoverageIgnoreStart
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
if (!session_regenerate_id(true)) {
throw new RuntimeException('Cannot regenerate session identifier. Unknown error.', 1002);
}
}
// @codeCoverageIgnoreEnd
return $this;
}
/**
* Returns the session id.
*
* @return string
*/
public function getSessionId() : string
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot retrieve session identifier. Session is not started yet.', 1010);
}
// @codeCoverageIgnoreStart
if (defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
return '';
}
return session_id();
// @codeCoverageIgnoreEnd
}
/**
* Sets session data.
*
* @param string $name
* @param mixed $value
* @param bool $readOnly
* @throws RuntimeException
* @return ServiceInterface
*/
public function set(string $name, $value, bool $readOnly = false) : ServiceInterface
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot set session data. Session is not started yet.', 1005);
}
if (isset($this->readOnly[$name])) {
throw new RuntimeException('Unable to overwrite data. Permission denied.', 1006);
}
if ($readOnly) {
$this->readOnly[$name] = $name;
}
$this->data[$name] = $value;
return $this;
}
/**
* Checks whether a session data exists or not.
*
* @param string $name
* @throws RuntimeException
* @return bool
*/
public function has(string $name) : bool
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot set session data. Session is not started yet.', 1009);
}
return isset($this->data[$name]);
}
/**
* Gets session data.
*
* @param string $name
* @param bool $skipMissing
* @throws RuntimeException
* @return mixed
*/
public function get(string $name, bool $skipMissing = true)
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot set session data. Session is not started yet.', 1003);
}
if (isset($this->data[$name])) {
return $this->data[$name];
} elseif ($skipMissing) {
return null;
}
throw new RuntimeException('Cannot retrieve session data. Data is not set', 1004);
}
/**
* Deletes session data.
*
* @param string $name
* @param bool $forceDelete
* @throws RuntimeException
* @return ServiceInterface
*/
public function delete(string $name, bool $forceDelete = false) : ServiceInterface
{
if (!$this->sessionStarted()) {
throw new RuntimeException('Cannot delete session data. Session is not started.', 1007);
}
if (!$forceDelete && isset($this->readOnly[$name])) {
throw new RuntimeException('Unable to delete data. Permission denied.', 1008);
}
// hide errors if data not exists.
unset($this->readOnly[$name]);
unset($this->data[$name]);
return $this;
}
/**
* Unlocks readOnly data.
*
* @param string $name
* @return ServiceInterface
*/
public function unlock(string $name) : ServiceInterface
{
if (isset($this->readOnly[$name])) {
unset($this->readOnly[$name]);
}
return $this;
}
/**
* Returns the internal storage.
*
* @return array
*/
public function toArray() : array
{
return $this->data;
}
}
<file_sep>/src/WebHemi/Http/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param EnvironmentInterface $environmentManager
*/
public function __construct(EnvironmentInterface $environmentManager);
/**
* Returns the HTTP request.
*
* @return ServerRequestInterface
*/
public function getRequest() : ServerRequestInterface;
/**
* Returns the response being sent.
*
* @return ResponseInterface
*/
public function getResponse() : ResponseInterface;
}
<file_sep>/di.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Application\ServiceInterface as ApplicationInterface;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Configuration;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\DependencyInjection\ServiceAdapter\Symfony\ServiceAdapter as DependencyInjection;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionInterface;
use WebHemi\Environment\ServiceAdapter\Base\ServiceAdapter as Environment;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\MiddlewarePipeline\ServiceAdapter\Base\ServiceAdapter as MiddlewarePipeline;
use WebHemi\MiddlewarePipeline\ServiceInterface as MiddlewarePipelineInterface;
use WebHemi\Session\ServiceAdapter\Base\ServiceAdapter as Session;
use WebHemi\Session\ServiceInterface as SessionInterface;
require_once __DIR__.'/vendor/autoload.php';
// Set up core objects
$configurationData = require_once __DIR__.'/config/config.php';
// Get the service class names from the configuration, so no need to hardcode them.
// These global dependency definitions are mandatory and MUST exist
$applicationClass = $configurationData['dependencies']['Global'][ApplicationInterface::class]['class'];
$configurationClass = $configurationData['dependencies']['Global'][ConfigurationInterface::class]['class'];
$dependencyInjectionClass = $configurationData['dependencies']['Global'][DependencyInjectionInterface::class]['class'];
$environmentClass = $configurationData['dependencies']['Global'][EnvironmentInterface::class]['class'];
$middlewarePipelineClass = $configurationData['dependencies']['Global'][MiddlewarePipelineInterface::class]['class'];
$sessionClass = $configurationData['dependencies']['Global'][SessionInterface::class]['class'];
/** @var Configuration $configuration */
$configuration = new $configurationClass($configurationData);
/** @var Environment $environment */
$environment = new $environmentClass($configuration, $_GET, $_POST, $_SERVER, $_COOKIE, $_FILES, []);
/** @var MiddlewarePipeline $middlewarePipeline */
$middlewarePipeline = new $middlewarePipelineClass($configuration);
$middlewarePipeline->addModulePipeLine($environment->getSelectedModule());
/** @var Session $session */
$session = new $sessionClass($configuration);
/** @var DependencyInjection $dependencyInjection */
$dependencyInjection = new $dependencyInjectionClass($configuration);
// Add core and module services to the DI adapter
$dependencyInjection->registerServiceInstance(DependencyInjectionInterface::class, $dependencyInjection)
->registerServiceInstance(ConfigurationInterface::class, $configuration)
->registerServiceInstance(EnvironmentInterface::class, $environment)
->registerServiceInstance(MiddlewarePipelineInterface::class, $middlewarePipeline)
->registerServiceInstance(SessionInterface::class, $session)
->registerModuleServices('Global')
->registerModuleServices('Website')
->registerModuleServices('Admin');
$diList = [];
$fullConfig = $configuration->getData('dependencies');
foreach ($fullConfig as $module => $dependencies) {
if ($module == 'Cronjob') {
continue;
}
foreach ($dependencies as $reference => $config) {
$name = $reference;
if (isset($config['class'])) {
$name .= ' <span style="color:gray">('.$config['class'].')</span>';
}
$instance = '<span style="color:green">OK</span>';
$additional = '';
try {
$obj = $dependencyInjection->get($reference);
$objName = get_class($obj);
if ($obj instanceof ApplicationInterface) {
$obj->initSession();
}
if ($reference != $objName) {
$name = $reference.' <span style="color:gray">('.$objName.')</span>';
}
} catch (Throwable $error) {
$libdata = $dependencyInjection->getServiceConfiguration($reference);
$instance = '<span style="color:red">Error</span>: '.$error->getMessage();
$additional = '<ul>';
$additional .= '<li><strong>File</strong> '.$error->getFile().'</li>'.PHP_EOL;
$additional .= '<li><strong>Line</strong> '.$error->getLine().'</li>'.PHP_EOL;
foreach ($libdata as $key => $value) {
$additional .= '<li><strong>'.$key.'</strong> '.json_encode($value).'</li>'.PHP_EOL;
}
$additional .= '</ul>';
}
$diList[$name] = [
'name' => $name,
'status' => $instance,
'additional' => $additional
];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dependency Injection tester</title>
<style>
tr {
vertical-align: top;
}
tr:nth-child(2n) {
background-color: #e8e8e8;
}
</style>
</head>
<body>
<h1>Instantiate <?php echo count($diList); ?> objects with the DI adapter.</h1>
<table>
<thead>
<tr>
<th>Class</th>
<th>Status</th>
<th>Info</th>
</tr>
</thead>
<tbody>
<?php
foreach ($diList as $info) {
echo '<tr><td>'.$info['name'].'</td><td>'.$info['status'].'</td><td>'.$info['additional'].'</td></tr>'.PHP_EOL;
}
?>
</tbody>
</table>
<?php
$stat = render_stat();
?>
<p>Rendered in <?php echo $stat['duration']; ?> seconds.</p>
<p>Used <?php echo $stat['memory_bytes']; ?> of memory.</p>
</body>
</html>
<file_sep>/src/WebHemi/Auth/Result/Result.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth\Result;
use WebHemi\Auth\ResultInterface;
/**
* Class Result.
*/
class Result implements ResultInterface
{
/**
* @var int
*/
private $code;
/**
* @var array
*/
private $messages = [
self::FAILURE => 'Authentication failed.',
self::FAILURE_IDENTITY_NOT_FOUND => 'User is not found.',
self::FAILURE_IDENTITY_DISABLED => 'The given user is disabled.',
self::FAILURE_IDENTITY_INACTIVE => 'The given user is in inactive state.',
self::FAILURE_CREDENTIAL_INVALID => 'The provided credentials are not valid.',
self::FAILURE_OTHER => 'Authentication failed because of unknown reason.',
self::SUCCESS => 'Authenticated.'
];
/**
* Checks the authentication result.
*
* @return bool
*/
public function isValid() : bool
{
return $this->code == 1;
}
/**
* Sets the result code.
*
* @param int $code
* @return ResultInterface
*/
public function setCode(int $code) : ResultInterface
{
if (!isset($this->messages[$code])) {
$code = self::FAILURE_OTHER;
}
$this->code = $code;
return $this;
}
/**
* Gets the result code.
*
* @return int
*/
public function getCode() : int
{
return $this->code;
}
/**
* Gets the result message.
*
* @return string
*/
public function getMessage() : string
{
return $this->messages[$this->code];
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyAuthStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Auth\StorageInterface as AuthStorageInterface;
use WebHemi\Data\Entity\UserEntity;
/**
* Class EmptyAuthStorage
*/
class EmptyAuthStorage implements AuthStorageInterface
{
private $identity;
/**
* Sets the authenticated user.
*
* @param UserEntity $dataEntity
* @return AuthStorageInterface
*/
public function setIdentity(UserEntity $dataEntity) : AuthStorageInterface
{
$this->identity = $dataEntity;
return $this;
}
/**
* Checks if there is any authenticated user.
*
* @return bool
*/
public function hasIdentity() : bool
{
return !empty($this->identity);
}
/**
* Gets the authenticated user.
*
* @return UserEntity|null
*/
public function getIdentity() : ? UserEntity
{
return $this->identity;
}
/**
* Clears the session.
*
* @return AuthStorageInterface
*/
public function clearIdentity() : AuthStorageInterface
{
$this->identity = null;
return $this;
}
}
<file_sep>/tests/WebHemiTest/TestExtension/InvokePrivateMethodTrait.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestExtension;
/**
* Trait InvokePrivateMethodTrait.
*/
trait InvokePrivateMethodTrait
{
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
*
* @return mixed Method return.
*/
protected function invokePrivateMethod(&$object, $methodName, array $parameters = [])
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
<file_sep>/tests/WebHemiTest/Session/SessionManagerTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Session;
use Exception;
use RuntimeException;
use WebHemi\DateTime;
use WebHemi\Session\ServiceAdapter\Base\ServiceAdapter as SessionManager;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemiTest\TestExtension\AssertArraysAreSimilarTrait as AssertTrait;
use PHPUnit\Framework\TestCase;
/**
* Class SessionManagerTest
*/
class SessionManagerTest extends TestCase
{
/** @var Config */
private $config;
use AssertTrait;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$config = require __DIR__ . '/../test_config.php';
$this->config = new Config($config);
}
/**
* Tests constructor.
*/
public function testConstructor()
{
$sessionManager = new SessionManager($this->config);
$this->assertAttributeEmpty('data', $sessionManager);
$this->assertAttributeEquals(
$this->config->getData('session/namespace')[0],
'namespace',
$sessionManager
);
$this->assertAttributeEquals(
$this->config->getData('session/cookie_prefix')[0],
'cookiePrefix',
$sessionManager
);
$this->assertAttributeEquals(
$this->config->getData('session/session_name_salt')[0],
'sessionNameSalt',
$sessionManager
);
}
/**
* Test start() method.
*/
public function testSessionStart()
{
$config = require __DIR__ . '/../test_config.php';
// Change the namespace, so the sessionStarted() method will return false.
$config['session']['namespace'] = 'UNITTEST';
$this->config = new Config($config);
$sessionManager = new SessionManager($this->config);
$actualObject = $sessionManager->start('test');
$this->assertInstanceOf(SessionManager::class, $actualObject);
$this->assertTrue($actualObject === $sessionManager);
$config['session']['namespace'] = 'TEST';
$this->config = new Config($config);
$sessionManager = new SessionManager($this->config);
try {
$sessionManager->start('test');
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1000, $e->getCode());
}
}
/**
* Test regenerateId() method.
*/
public function testRegenerateId()
{
$sessionManager = new SessionManager($this->config);
$actualObject = $sessionManager->regenerateId();
$this->assertInstanceOf(SessionManager::class, $actualObject);
$this->assertTrue($actualObject === $sessionManager);
$config = require __DIR__ . '/../test_config.php';
$config['session']['namespace'] = 'UNITTEST';
$this->config = new Config($config);
$sessionManager = new SessionManager($this->config);
try {
$sessionManager->regenerateId();
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1001, $e->getCode());
}
}
/**
* Tests set() method
*/
public function testSetter()
{
$sessionManager = new SessionManager($this->config);
$name = 'test';
$value = 'value';
$readOnly = false;
// set value
$actualObject = $sessionManager->set($name, $value, $readOnly);
$this->assertInstanceOf(SessionManager::class, $actualObject);
$this->assertTrue($actualObject === $sessionManager);
$this->assertSame($value, $sessionManager->get($name));
// change value
$newValue = 'some other value';
$sessionManager->set($name, $newValue, $readOnly);
$this->assertSame($newValue, $sessionManager->get($name));
// change and lock value
$anotherNewValue = 'yet another value';
$readOnly = true;
$sessionManager->set($name, $anotherNewValue, $readOnly);
$this->assertSame($anotherNewValue, $sessionManager->get($name));
// try to change readonly data
try {
$sessionManager->set($name, 'will not work.');
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1006, $e->getCode());
}
// unlock and change readonly data
$sessionManager->unlock($name);
$sessionManager->set($name, $value);
$this->assertSame($value, $sessionManager->get($name));
$config = require __DIR__ . '/../test_config.php';
$config['session']['namespace'] = 'UNITTEST';
$this->config = new Config($config);
$sessionManager = new SessionManager($this->config);
try {
$sessionManager->set('some', 'value');
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1005, $e->getCode());
}
}
/**
* Tests get() method.
*/
public function testGetter()
{
$sessionManager = new SessionManager($this->config);
$name = 'test';
$value = 'value';
$sessionManager->set($name, $value);
$this->assertSame($value, $sessionManager->get($name));
// return NULL when non exists
$skipMissing = true;
$this->assertFalse($sessionManager->has('something non existing'));
$this->assertNull($sessionManager->get('something non existing', $skipMissing));
// get exception otherwise
$skipMissing = false;
try {
$this->assertNull($sessionManager->get('something non existing', $skipMissing));
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1004, $e->getCode());
}
$config = require __DIR__ . '/../test_config.php';
$config['session']['namespace'] = 'UNITTEST';
$this->config = new Config($config);
$sessionManager = new SessionManager($this->config);
try {
$sessionManager->get('something');
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1003, $e->getCode());
}
try {
$sessionManager->has('something');
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1009, $e->getCode());
}
try {
$sessionManager->getSessionId();
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1010, $e->getCode());
}
}
/**
* Tests delete() method.
*/
public function testDelete()
{
$sessionManager = new SessionManager($this->config);
$name = 'test';
$value = 'value';
// delete existing non-readonly
$sessionManager->set($name, $value, false);
$this->assertSame($value, $sessionManager->get($name));
$sessionManager->delete($name);
$this->assertNull($sessionManager->get($name, true));
// delete existing readonly, no force
$sessionManager->set($name, $value, true);
$this->assertSame($value, $sessionManager->get($name));
try {
$sessionManager->delete($name);
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1008, $e->getCode());
}
// delete existing readonly, force
$sessionManager->delete($name, true);
$this->assertNull($sessionManager->get($name, true));
// delete non-existing
$sessionManager->delete('something');
$config = require __DIR__ . '/../test_config.php';
$config['session']['namespace'] = 'UNITTEST';
$this->config = new Config($config);
$sessionManager = new SessionManager($this->config);
try {
$sessionManager->delete('something');
} catch (Exception $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(1007, $e->getCode());
}
}
/**
* Tests toArray() method
*/
public function testToArray()
{
$expectedData = [
'key1' => 'value1',
'key2' => 'value2',
'key3' => [
'complex' => 'data',
'date' => new DateTime()
]
];
$sessionManager = new SessionManager($this->config);
foreach ($expectedData as $key => $value) {
$sessionManager->set($key, $value);
}
$this->assertArraysAreSimilar($expectedData, $sessionManager->toArray());
}
}
<file_sep>/src/WebHemi/MiddlewarePipeline/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\MiddlewarePipeline\ServiceAdapter\Base;
use WebHemi\Middleware\Common;
use WebHemi\MiddlewarePipeline\ServiceAdapter\AbstractAdapter;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter extends AbstractAdapter
{
/**
* Initialize the listing properties (priorityList, pipelineList, keyMiddlewareList).
*
* @return void
*/
protected function initProperties() : void
{
$this->keyMiddlewareList = [
Common\RoutingMiddleware::class,
Common\DispatcherMiddleware::class,
Common\FinalMiddleware::class
];
// The FinalMiddleware should not be part of the queue.
$this->priorityList = [
0 => [Common\RoutingMiddleware::class],
100 => [Common\DispatcherMiddleware::class]
];
$this->pipelineList = [
Common\RoutingMiddleware::class,
Common\DispatcherMiddleware::class,
];
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyService.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
/**
* Class EmptyService
*/
class EmptyService
{
/** @var array */
public $storage = [];
/** @var string */
public $key;
/**
* EmptyEntity constructor.
*
* @param string $key
* @param mixed $keyData
*/
public function __construct($key = null, $keyData = null)
{
$this->storage[$key] = $keyData;
}
/**
* Handle getters and setters.
*
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
$matches = [];
$return = null;
if (preg_match('/^(?P<type>(get|set))(?P<property>.+)$/', $name, $matches)) {
$property = lcfirst($matches['property']);
if ($matches['type'] == 'set') {
$this->storage[$property] = $arguments[0];
$return = true;
} else {
if (isset($this->storage[$property])) {
$return = $this->storage[$property];
}
}
}
return $return;
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getUserList.sql
SELECT
u.`id_user`,
u.`username`,
u.`email`,
u.`password`,
u.`hash`,
u.`is_active`,
u.`is_enabled`,
u.`date_created`,
u.`date_modified`
FROM
`webhemi_user` AS u
ORDER BY
u.`username`
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Data/Query/SQLite/QueryAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Query\SQLite;
use WebHemi\Data\Query\MySQL;
/**
* Class QueryAdapter
*/
class QueryAdapter extends MySQL\QueryAdapter
{
/**
* @var string
*/
protected static $statementPath = __DIR__.'/../MySQL/statements/*.sql';
}
<file_sep>/index.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
use WebHemi\Application\ServiceAdapter\Base\ServiceAdapter as Application;
use WebHemi\Application\ServiceInterface as ApplicationInterface;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Configuration;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\DependencyInjection\ServiceAdapter\Symfony\ServiceAdapter as DependencyInjection;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionInterface;
use WebHemi\Environment\ServiceAdapter\Base\ServiceAdapter as Environment;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\MiddlewarePipeline\ServiceAdapter\Base\ServiceAdapter as MiddlewarePipeline;
use WebHemi\MiddlewarePipeline\ServiceInterface as MiddlewarePipelineInterface;
use WebHemi\Session\ServiceAdapter\Base\ServiceAdapter as Session;
use WebHemi\Session\ServiceInterface as SessionInterface;
require_once __DIR__.'/vendor/autoload.php';
// Set up core objects
$configurationData = require_once __DIR__.'/config/config.php';
// Get the service class names from the configuration, so no need to hardcode them.
// These global dependency definitions are mandatory and MUST exist
$applicationClass = $configurationData['dependencies']['Global'][ApplicationInterface::class]['class'];
$configurationClass = $configurationData['dependencies']['Global'][ConfigurationInterface::class]['class'];
$dependencyInjectionClass = $configurationData['dependencies']['Global'][DependencyInjectionInterface::class]['class'];
$environmentClass = $configurationData['dependencies']['Global'][EnvironmentInterface::class]['class'];
$middlewarePipelineClass = $configurationData['dependencies']['Global'][MiddlewarePipelineInterface::class]['class'];
$sessionClass = $configurationData['dependencies']['Global'][SessionInterface::class]['class'];
/** @var Configuration $configuration */
$configuration = new $configurationClass($configurationData);
/** @var Environment $environment */
$environment = new $environmentClass($configuration, $_GET, $_POST, $_SERVER, $_COOKIE, $_FILES, []);
/** @var MiddlewarePipeline $middlewarePipeline */
$middlewarePipeline = new $middlewarePipelineClass($configuration);
$middlewarePipeline->addModulePipeLine($environment->getSelectedModule());
/** @var Session $session */
$session = new $sessionClass($configuration);
/** @var DependencyInjection $dependencyInjection */
$dependencyInjection = new $dependencyInjectionClass($configuration);
// Add core and module services to the DI adapter
$dependencyInjection->registerServiceInstance(ConfigurationInterface::class, $configuration)
->registerServiceInstance(EnvironmentInterface::class, $environment)
->registerServiceInstance(MiddlewarePipelineInterface::class, $middlewarePipeline)
->registerServiceInstance(SessionInterface::class, $session)
->registerServiceInstance(DependencyInjectionInterface::class, $dependencyInjection)
->registerModuleServices('Global')
->registerModuleServices($environment->getSelectedModule());
/** @var Application $application */
$application = new $applicationClass($dependencyInjection);
$application
->initInternationalization()
->initSession()
->run()
->renderOutput();
<file_sep>/src/WebHemi/DateTime.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi;
use DateTime as PHPDateTime;
use DateTimeZone;
use WebHemi\I18n\TimeZoneInterface;
/**
* Class DateTime.
*
* Under php5-fpm the default DateTime object will be instantiated as TimeCopDateTime which makes issues in the
* dependency injection adapter, and also fails unit tests. So the idea is to create this empty extension and
* use this class instead of the default one or the TimeCopDateTime.
*/
class DateTime extends PHPDateTime implements TimeZoneInterface
{
/**
* @var string
*/
private $timeZoneDataPath;
/**
* @var array
*/
private $dateFormat = [];
/**
* DateTime constructor.
*
* @param string $time
* @param DateTimeZone|null $timeZone
*/
public function __construct($time = 'now', DateTimeZone $timeZone = null)
{
if (is_numeric($time)) {
$time = date('Y-m-d H:i:s', $time);
}
if (!$timeZone instanceof DateTimeZone) {
$currentTimeZone = new DateTimeZone(date_default_timezone_get());
} else {
$currentTimeZone = $timeZone;
}
$this->timeZoneDataPath = __DIR__.'/I18n/TimeZone';
$this->loadTimeZoneData($currentTimeZone->getName());
parent::__construct($time, $currentTimeZone);
}
/**
* Loads date format data regarding to the time zone.
*
* @param string $timeZone
*/
public function loadTimeZoneData(string $timeZone) : void
{
$normalizedTimeZone = StringLib::convertNonAlphanumericToUnderscore($timeZone, '-');
if (file_exists($this->timeZoneDataPath.'/'.$normalizedTimeZone.'.php')) {
$this->dateFormat = include $this->timeZoneDataPath.'/'.$normalizedTimeZone.'.php';
}
}
/**
* Returns date formatted according to given format.
*
* @param string $format
* @return string
* @link http://php.net/manual/en/datetime.format.php
*/
public function format($format)
{
if (isset($this->dateFormat[$format])) {
$timestamp = $this->getTimestamp();
$extraFromat = $this->dateFormat[$format];
if (strpos($extraFromat, '%Q') !== false) {
if ($this->dateFormat['ordinals']) {
$replace = date('jS', $timestamp);
} else {
$replace = '%d.';
}
$extraFromat = str_replace('%Q', $replace, $extraFromat);
}
$dateString = strftime($extraFromat, $timestamp);
} else {
$dateString = parent::format($format);
}
return $dateString;
}
/**
* Checks if stored timestamp belong to current day.
*
* @return bool
*/
public function isToday() : bool
{
return date('Ymd', $this->getTimestamp()) == date('Ymd');
}
/**
* Checks if stored timestamp belong to current month.
*
* @return bool
*/
public function isCurrentMonth() : bool
{
return date('Ym', $this->getTimestamp()) == date('Ym');
}
/**
* Checks if stored timestamp belong to current year.
*
* @return bool
*/
public function isCurrentYear() : bool
{
return date('Y', $this->getTimestamp()) == date('Y');
}
/**
* Returns the date with the default format.
*
* @return string
*/
public function __toString() : string
{
return $this->format('Y-m-d H:i:s');
}
}
<file_sep>/src/WebHemi/Renderer/FilterInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer;
/**
* Interface FilterInterface
*/
interface FilterInterface
{
/**
* Should return the name of the helper.
*
* @return string
*/
public static function getName() : string;
/**
* Should return the definition of the helper.
*
* @return string
*/
public static function getDefinition() : string;
/**
* Should return a description text.
*
* @return string
*/
public static function getDescription() : string;
/**
* Gets filter options for the render.
*
* @return array
*/
public static function getOptions() : array;
/**
* A renderer filter should be called with its name.
*
* @return mixed
*/
public function __invoke();
}
<file_sep>/src/WebHemi/Data/Storage/UserStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Storage;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Entity\UserGroupEntity;
use WebHemi\Data\Entity\UserMetaEntity;
use WebHemi\Data\Query\QueryInterface;
use WebHemi\StringLib;
/**
* Class UserStorage.
*/
class UserStorage extends AbstractStorage
{
/**
* Returns a set of users.
*
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getUserList(
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getUserList',
[
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(UserEntity::class, $data);
}
/**
* Returns user information identified by (unique) ID.
*
* @param int $identifier
* @return null|UserEntity
*/
public function getUserById(int $identifier) : ? UserEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getUserById',
[
':idUser' => $identifier
]
);
/** @var null|UserEntity $entity */
$entity = $this->getEntity(UserEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns user information by user name.
*
* @param string $username
* @return null|UserEntity
*/
public function getUserByUserName(string $username) : ? UserEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getUserByUsername',
[
':username' => $username
]
);
/** @var null|UserEntity $entity */
$entity = $this->getEntity(UserEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns user information by email.
*
* @param string $email
* @return null|UserEntity
*/
public function getUserByEmail(string $email) : ? UserEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getUserByEmail',
[
':email' => $email
]
);
/** @var null|UserEntity $entity */
$entity = $this->getEntity(UserEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Return a user information by credentials.
*
* @param string $username
* @param string $password
* @return null|UserEntity
*/
public function getUserByCredentials(string $username, string $password) : ? UserEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getUserByCredentials',
[
':username' => $username,
':password' => $<PASSWORD>
]
);
/** @var null|UserEntity $entity */
$entity = $this->getEntity(UserEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns a user meta list identified by user ID.
*
* @param int $identifier
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getUserMetaListByUser(
int $identifier,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getUserMetaListByUser',
[
':userId' => $identifier,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(UserMetaEntity::class, $data);
}
/**
* Returns a parsed/simplified form of the user meta list.
*
* @param int $identifier
* @param int $limit
* @param int $offset
* @return array
*/
public function getSimpleUserMetaListByUser(
int $identifier,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : array {
$metaInfo = [];
$entitySet = $this->getUserMetaListByUser($identifier, $limit, $offset);
foreach ($entitySet as $userMetaEntity) {
$data = $this->processMetaData($userMetaEntity);
$metaInfo[$data['key']] = $data['value'];
}
return $metaInfo;
}
/**
* Processes a user meta information.
*
* @param UserMetaEntity $userMetaEntity
* @return array
*/
private function processMetaData(UserMetaEntity $userMetaEntity) : array
{
$key = $userMetaEntity->getMetaKey() ?? '';
$value = $userMetaEntity->getMetaData() ?? '';
if ($key == 'avatar' && strpos($value, 'gravatar://') === 0) {
$value = str_replace('gravatar://', '', $value);
$value = 'http://www.gravatar.com/avatar/'.md5(strtolower($value)).'?s=256&r=g';
}
$jsonDataKeys = ['workplaces', 'instant_messengers', 'phone_numbers', 'social_networks', 'websites'];
if (in_array($key, $jsonDataKeys) && !empty($value)) {
$value = json_decode($value, true);
}
$data = [
'key' => lcfirst(StringLib::convertUnderscoreToCamelCase($key)),
'value' => $value
];
return $data;
}
/**
* Returns a set of user groups.
*
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getUserGroupList(
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getUserGroupList',
[
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(UserGroupEntity::class, $data);
}
/**
* Returns a set of user groups.
*
* @param int $identifier
* @param int $limit
* @param int $offset
* @return EntitySet
*/
public function getUserGroupListByUser(
int $identifier,
int $limit = QueryInterface::MAX_ROW_LIMIT,
int $offset = 0
) : EntitySet {
$this->normalizeLimitAndOffset($limit, $offset);
$data = $this->getQueryAdapter()->fetchData(
'getUserGroupListByUser',
[
':userId' => $identifier,
':limit' => $limit,
':offset' => $offset
]
);
return $this->getEntitySet(UserGroupEntity::class, $data);
}
/**
* Returns user group information identified by (unique) ID.
*
* @param int $identifier
* @return null|UserGroupEntity
*/
public function getUserGroupById(int $identifier) : ? UserGroupEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getUserGroupById',
[
':idUserGroup' => $identifier
]
);
/** @var null|UserGroupEntity $entity */
$entity = $this->getEntity(UserGroupEntity::class, $data[0] ?? []);
return $entity;
}
/**
* Returns a user group information by name.
*
* @param string $name
* @return null|UserGroupEntity
*/
public function getUserGroupByName(string $name) : ? UserGroupEntity
{
$data = $this->getQueryAdapter()->fetchData(
'getUserGroupByName',
[
':name' => $name
]
);
/** @var null|UserGroupEntity $entity */
$entity = $this->getEntity(UserGroupEntity::class, $data[0] ?? []);
return $entity;
}
}
<file_sep>/src/WebHemi/Renderer/ServiceAdapter/Twig/TwigExtension.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\ServiceAdapter\Twig;
use RuntimeException;
use Twig_Extension;
use Twig_SimpleFilter;
use Twig_SimpleFunction;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\DependencyInjection\ServiceInterface as DependencyInjectionInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Renderer\FilterInterface;
use WebHemi\Renderer\HelperInterface;
/**
* Class TwigExtension
*
* @codeCoverageIgnore - Test helpers and filters individually. It's only the shipped solution
* to add them to the renderer.
*/
class TwigExtension extends Twig_Extension
{
/**
* @var DependencyInjectionInterface
*/
private $dependencyInjectionAdapter;
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* TwigExtension constructor.
*/
public function __construct()
{
// Oh, this is a disgusting ugly hack...
global $dependencyInjection;
$this->dependencyInjectionAdapter = $dependencyInjection;
$this->configuration = $this->dependencyInjectionAdapter->get(ConfigurationInterface::class);
$this->environmentManager = $this->dependencyInjectionAdapter->get(EnvironmentInterface::class);
}
/**
* Returns extension filters.
*
* @return Twig_SimpleFilter[]
*/
public function getFilters()
{
return $this->getExtensions('filter');
}
/**
* Returns extension functions.
*
* @return Twig_SimpleFunction[]
*/
public function getFunctions() : array
{
return $this->getExtensions('helper');
}
/**
* Gets the specific type of extension
*
* @param string $type Must be `filter` or `helper`
* @return array
*/
private function getExtensions(string $type) : array
{
$extensions = [];
$extensionConfig = $this->getConfig($type);
foreach ($extensionConfig as $className) {
$callable = $this->dependencyInjectionAdapter->get($className);
$this->checkExtensionType($type, $callable);
if ($callable instanceof HelperInterface) {
$extensions[] = new Twig_SimpleFunction($callable::getName(), $callable, $callable::getOptions());
continue;
}
if ($callable instanceof FilterInterface) {
$extensions[] = new Twig_SimpleFilter($callable::getName(), $callable, $callable::getOptions());
}
}
return $extensions;
}
/**
* Checks whether the extension has the valid type.
*
* @param string $type
* @param object $callable
* @throws RuntimeException
*/
private function checkExtensionType(string $type, $callable) : void
{
if (($type == 'helper' && $callable instanceof HelperInterface)
|| ($type == 'filter' && $callable instanceof FilterInterface)
) {
return;
}
throw new RuntimeException(
sprintf(
'The class %s cannot be registered as Renderer/'.ucfirst($type).'!',
get_class($callable)
),
1000
);
}
/**
* Returns the renderer config by type.
*
* @param string $type
* @return array
*/
private function getConfig(string $type) : array
{
$module = $this->environmentManager->getSelectedModule();
$config = [];
if ($this->configuration->has('renderer/Global/'.$type)) {
$config = $this->configuration->getData('renderer/Global/'.$type);
}
if ($this->configuration->has('renderer/'.$module.'/'.$type)) {
$config = array_merge(
$config,
$this->configuration->getData('renderer/'.$module.'/'.$type)
);
}
return $config;
}
}
<file_sep>/src/WebHemi/Auth/Credential/NameAndPasswordCredential.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth\Credential;
use InvalidArgumentException;
use WebHemi\Auth\CredentialInterface;
/**
* Class NameAndPasswordCredential.
*/
class NameAndPasswordCredential implements CredentialInterface
{
/**
* @var string
*/
private $username = '';
/**
* @var string
*/
private $password = '';
/**
* Set a credential.
*
* @param string $key
* @param string $value
* @throws InvalidArgumentException
* @return CredentialInterface
*/
public function setCredential(string $key, string $value) : CredentialInterface
{
switch ($key) {
case 'username':
$this->username = $value;
break;
case 'password':
$this->password = $value;
break;
default:
throw new InvalidArgumentException(
sprintf(
'Parameter #1 must be either "username" or "password", %s given.',
$key
),
1000
);
}
return $this;
}
/**
* Returns the credentials in a key => value array.
*
* @return array
*/
public function getCredentials() : array
{
return ['username' => $this->username, 'password' => $this->password];
}
}
<file_sep>/src/WebHemi/Data/Entity/AbstractEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use InvalidArgumentException;
/**
* Class AbstractEntity
*/
abstract class AbstractEntity implements EntityInterface
{
/**
* @var array
*/
protected $container = [];
/**
* Returns entity data as an array.
*
* @return array
*/
public function toArray(): array
{
return $this->container;
}
/**
* Fills entity from an arrray.
*
* @param array $arrayData
*/
public function fromArray(array $arrayData): void
{
foreach ($arrayData as $key => $value) {
if (!array_key_exists($key, $this->container)) {
throw new InvalidArgumentException(
sprintf('"%s" is not defined in '.get_called_class(), $key),
1000
);
}
$this->container[$key] = $value;
}
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getUserMetaListByUser.sql
SELECT
um.`id_user_meta`,
um.`fk_user`,
um.`meta_key`,
um.`meta_data`,
um.`date_created`,
um.`date_modified`
FROM
`webhemi_user_meta` AS um
WHERE
um.`fk_user` = :userId
ORDER BY
um.`meta_key`
LIMIT
:limit
OFFSET
:offset
<file_sep>/tests/WebHemiTest/TestService/EmptyAuthAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Auth\ServiceAdapter\AbstractServiceAdapter;
use WebHemi\Auth\CredentialInterface as AuthCredentialInterface;
use WebHemi\Auth\ResultInterface as AuthResultInterface;
use WebHemi\Data\Entity\UserEntity;
/**
* Class EmptyAuthAdapter
*/
class EmptyAuthAdapter extends AbstractServiceAdapter
{
/**
* Authenticates the user.
*
* @param AuthCredentialInterface $credential
* @return AuthResultInterface
*/
public function authenticate(AuthCredentialInterface $credential) : AuthResultInterface
{
$crentialData = $credential->getCredentials();
$authResultShouldBe = $crentialData['authResultShouldBe'];
if ($authResultShouldBe < 1) {
return $this->getNewAuthResultInstance()
->setCode($authResultShouldBe);
}
/** @var UserEntity $userEntity */
$userEntity = $this->getDataStorage()->createEntity(UserEntity::class);
$userEntity->setUserId(123)
->setUserName('test');
$this->setIdentity($userEntity);
return $this->getNewAuthResultInstance()
->setCode(AuthResultInterface::SUCCESS);
}
}
<file_sep>/src/WebHemi/Renderer/Filter/TranslateFilter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Filter;
use WebHemi\I18n\DriverInterface;
use WebHemi\Renderer\FilterInterface;
/**
* Class TranslateFilter
*/
class TranslateFilter implements FilterInterface
{
/**
* @var DriverInterface
*/
private $driver;
/**
* TranslateFilter constructor.
*
* @param DriverInterface $driver
*/
public function __construct(DriverInterface $driver)
{
$this->driver = $driver;
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 't';
}
/**
* Should return the definition of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{{ "Some %s in English"|t("idea") }}';
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Translates the text into the language configured for the application.';
}
/**
* Gets filter options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* Parses the input text as a markdown script and outputs the HTML.
*
* @uses TagParserFilter::getCurrentUri()
*
* @return string
*/
public function __invoke() : string
{
$arguments = func_get_args() ?? [];
$text = array_shift($arguments);
$text = $this->driver->translate($text);
if (!empty($arguments)) {
array_unshift($arguments, $text);
$text = call_user_func_array('sprintf', $arguments);
}
return $text;
}
}
<file_sep>/config/settings/_global/logger.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
return [
'logger' => [
'access' => [
'path' => __DIR__.'/../../../data/log/access',
'file_name' => 'access-',
'file_extension' => 'log',
'date_format' => 'Y-m-d H:i:s.u',
'log_level' => 3
],
'event' => [
'path' => __DIR__.'/../../../data/log/event',
'file_name' => 'event-',
'file_extension' => 'log',
'date_format' => 'Y-m-d H:i:s.u',
'log_level' => 1
]
],
];
<file_sep>/src/WebHemi/Renderer/ServiceAdapter/Twig/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\ServiceAdapter\Twig;
use InvalidArgumentException;
use Psr\Http\Message\StreamInterface;
use Throwable;
use Twig_Environment;
use Twig_Extension_Debug;
use Twig_Loader_Filesystem;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\GeneralLib;
use WebHemi\I18n\ServiceInterface as I18nService;
use WebHemi\Renderer\ServiceInterface;
use WebHemi\Renderer\Traits\GetSelectedThemeResourcePathTrait;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var Twig_Environment
*/
private $adapter;
/**
* @var string
*/
private $defaultViewPath;
/**
* @var string
*/
private $templateViewPath;
/**
* @var string
*/
private $templateResourcePath;
/**
* @var string
*/
private $applicationBaseUri;
use GetSelectedThemeResourcePathTrait;
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* @var EnvironmentInterface
*/
protected $environmentManager;
/**
* @var I18nService
*/
protected $i18nService;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param I18nService $i18nService
* @throws Throwable
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
I18nService $i18nService
) {
$this->configuration = $configuration;
$this->environmentManager = $environmentManager;
$this->i18nService = $i18nService;
$documentRoot = $environmentManager->getDocumentRoot();
$selectedTheme = $environmentManager->getSelectedTheme();
$selectedThemeResourcePath = $this->getSelectedThemeResourcePath(
$selectedTheme,
$configuration,
$environmentManager
);
// Overwrite for later usage.
$this->configuration = $configuration->getConfig('themes/'.$selectedTheme);
$this->defaultViewPath = $documentRoot.EnvironmentInterface::DEFAULT_THEME_RESOURCE_PATH.'/view';
$this->templateViewPath = $documentRoot.$selectedThemeResourcePath.'/view';
$this->templateResourcePath = $selectedThemeResourcePath.'/static';
$this->applicationBaseUri = $environmentManager->getSelectedApplicationUri();
$loader = new Twig_Loader_Filesystem($this->templateViewPath);
$loader->addPath($this->defaultViewPath, 'WebHemi');
$loader->addPath($this->templateViewPath, 'Theme');
$this->adapter = new Twig_Environment($loader, array('debug' => true, 'cache' => false));
$this->adapter->addExtension(new Twig_Extension_Debug());
// @codeCoverageIgnoreStart
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
$this->adapter->addExtension(new TwigExtension());
}
// @codeCoverageIgnoreEnd
}
/**
* Renders the template for the output.
*
* @param string $template
* @param array $parameters
* @throws Throwable
* @return StreamInterface
*/
public function render(string $template, array $parameters = []) : StreamInterface
{
if ($this->configuration->has('map/'.$template)) {
$template = $this->configuration->getData('map/'.$template)[0];
}
if (!file_exists($this->templateViewPath.'/'.$template)) {
throw new InvalidArgumentException(
sprintf(
'Unable to render file: "%s". No such file: %s.',
$template,
$this->templateViewPath.'/'.$template
)
);
}
// Merge mandatory Application data.
$applicationParams['application'] = [
'selectedModule' => $this->environmentManager->getSelectedModule(),
'address' => $this->environmentManager->getAddress(),
'topDomain' => $this->environmentManager->getTopDomain(),
'domainName' => $this->environmentManager->getApplicationDomain(),
'domainAddress' => 'http'.($this->environmentManager->isSecuredApplication() ? 's' : '').'://'
.$this->environmentManager->getApplicationDomain(),
'resourcePath' => $this->templateResourcePath,
'baseUri' => $this->applicationBaseUri,
'currentUri' => $this->environmentManager->getRequestUri(),
'documentRoot' => $this->environmentManager->getDocumentRoot(),
'language' => $this->i18nService->getLanguage(),
'locale' => $this->i18nService->getLocale(),
];
$parameters = GeneralLib::mergeArrayOverwrite($parameters, $applicationParams);
$output = $this->adapter->render($template, $parameters);
// The ugliest shit ever. But that is how they made it... :/
return \GuzzleHttp\Psr7\stream_for($output);
}
}
<file_sep>/tests/WebHemiTest/TestService/TestActionMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use Exception;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class TestActionMiddleware.
*/
class TestActionMiddleware extends AbstractMiddlewareAction
{
/** @var boolean */
private $shouldSimulateError;
/** @var int */
private $errorCode;
/**
* TestActionMiddleware constructor.
*
* @param bool $shouldSimulateError
* @param int $errorCode
*/
public function __construct($shouldSimulateError = false, $errorCode = 1)
{
$this->shouldSimulateError = $shouldSimulateError;
$this->errorCode = $errorCode;
}
/**
* Gets template name.
*
* @return string
*/
public function getTemplateName() : string
{
return 'test-page';
}
/**
* Gets template data
*
* @throws Exception
*
* @return array
*/
public function getTemplateData() : array
{
if ($this->shouldSimulateError) {
throw new Exception('Simulated error', $this->errorCode);
}
// Make a small change in the response.
$this->response = $this->response->withHeader('SomeHeader', 'SomeValue');
return [];
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyRouteProxy.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemiTest\TestService;
use WebHemi\Router\ProxyInterface;
use WebHemi\Router\Result\Result;
/**
* Class EmptyRouteProxy.
*/
class EmptyRouteProxy implements ProxyInterface
{
/**
* Resolves the middleware class name for the application and URL.
*
* @param string $application
* @param Result $routeResult
* @return void
*/
public function resolveMiddleware(string $application, Result &$routeResult) : void
{
$parameters = $routeResult->getParameters();
unset($application);
switch ($parameters['basename']) {
case 'actionok.html':
$routeResult->setMatchedMiddleware('ActionOK')
->setStatus(Result::CODE_FOUND);
break;
case 'actionbad.html':
$routeResult->setMatchedMiddleware('ActionBad')
->setStatus(Result::CODE_FOUND);
break;
case 'directory':
$routeResult->setStatus(Result::CODE_FORBIDDEN)
->setMatchedMiddleware(null);
break;
default:
$routeResult->setStatus(Result::CODE_NOT_FOUND)
->setMatchedMiddleware(null);
}
$routeResult->setParameters($parameters);
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyCredential.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Auth\CredentialInterface;
/**
* Class EmptyCoupler.
*/
class EmptyCredential implements CredentialInterface
{
public $storage = [];
/**
* Set a credential.
*
* @param string $key
* @param string $value
* @return CredentialInterface
*/
public function setCredential(string $key, string $value) : CredentialInterface
{
$this->storage[$key] = $value;
return $this;
}
/**
* Returns the credentials in a key => value array.
*
* @return array
*/
public function getCredentials() : array
{
return $this->storage;
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemTagListByFilesystem.sql
SELECT
fst.`id_filesystem_tag`,
fst.`fk_application`,
fst.`name`,
fst.`title`,
fst.`description`,
fst.`date_created`,
fst.`date_modified`
FROM
`webhemi_filesystem_tag` AS fst
INNER JOIN `webhemi_filesystem_to_filesystem_tag` AS fstfst ON fst.`id_filesystem_tag` = fstfst.`fk_filesystem_tag`
WHERE
fstfst.`fk_filesystem` = :idFilesystem
ORDER BY
`name`
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getApplicationById.sql
SELECT
`id_application`,
`name`,
`title`,
`introduction`,
`subject`,
`description`,
`keywords`,
`copyright`,
`path`,
`theme`,
`type`,
`locale`,
`timezone`,
`is_read_only`,
`is_enabled`,
`date_created`,
`date_modified`
FROM
`webhemi_application`
WHERE
`id_application` = :idApplication
<file_sep>/src/WebHemi/Http/ServiceAdapter/GuzzleHttp/ServerRequest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http\ServiceAdapter\GuzzleHttp;
use GuzzleHttp\Psr7\ServerRequest as GuzzleServerRequest;
use WebHemi\Http\ServerRequestInterface;
/**
* Class ServerRequest.
*/
class ServerRequest extends GuzzleServerRequest implements ServerRequestInterface
{
/**
* Checks if it is an XML HTTP Request (Ajax) or not.
*
* @return bool
*/
public function isXmlHttpRequest() : bool
{
$serverParams = $this->getServerParams();
return (
isset($serverParams['HTTP_X_REQUESTED_WITH'])
&& $serverParams['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'
);
}
}
<file_sep>/src/WebHemi/Auth/ResultInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth;
/**
* Interface ResultInterface
*/
interface ResultInterface
{
public const FAILURE = 0;
public const FAILURE_IDENTITY_NOT_FOUND = -1;
public const FAILURE_IDENTITY_DISABLED = -2;
public const FAILURE_IDENTITY_INACTIVE = -3;
public const FAILURE_CREDENTIAL_INVALID = -4;
public const FAILURE_OTHER = -1000;
public const SUCCESS = 1;
/**
* Checks the authentication result.
*
* @return bool
*/
public function isValid() : bool;
/**
* Sets the result code.
*
* @param int $code
* @return ResultInterface
*/
public function setCode(int $code) : ResultInterface;
/**
* Gets the result code.
*
* @return int
*/
public function getCode() : int;
/**
* Gets the result message.
*
* @return string
*/
public function getMessage() : string;
}
<file_sep>/src/WebHemi/Auth/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Auth\ServiceAdapter\Base;
use WebHemi\Auth\CredentialInterface;
use WebHemi\Auth\ResultInterface;
use WebHemi\Auth\ServiceAdapter\AbstractServiceAdapter;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\UserStorage;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter extends AbstractServiceAdapter
{
/**
* Authenticates the user.
*
* @param CredentialInterface $credential
* @return ResultInterface
*/
public function authenticate(CredentialInterface $credential) : ResultInterface
{
/**
* @var ResultInterface $result
*/
$result = $this->getNewAuthResultInstance();
$credentials = $credential->getCredentials();
/**
* @var UserStorage $dataStorage
*/
$dataStorage = $this->getDataStorage();
$user = $dataStorage->getUserByUserName($credentials['username']);
if (!$user instanceof UserEntity) {
$result->setCode(ResultInterface::FAILURE_IDENTITY_NOT_FOUND);
} elseif (!$user->getIsEnabled()) {
$result->setCode(ResultInterface::FAILURE_IDENTITY_DISABLED);
} elseif (!$user->getIsActive()) {
$result->setCode(ResultInterface::FAILURE_IDENTITY_INACTIVE);
} elseif (!password_verify($credentials['password'], $user->getPassword())) {
$result->setCode(ResultInterface::FAILURE_CREDENTIAL_INVALID);
} else {
$this->setIdentity($user);
$result->setCode(ResultInterface::SUCCESS);
}
return $result;
}
}
<file_sep>/src/WebHemi/Data/Entity/EntityInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
/**
* Interface EntityInterface
*/
interface EntityInterface
{
/**
* Returns entity data as an array.
*
* @return array
*/
public function toArray() : array;
/**
* Fills entity from an arrray.
*
* @param array $arrayData
*/
public function fromArray(array $arrayData) : void;
}
<file_sep>/tests/WebHemiTest/Logger/KloggerAdapterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Logger;
use WebHemi\Logger\ServiceInterface as LogAdapterInterface;
use WebHemi\Logger\ServiceAdapter\Klogger\ServiceAdapter as KloggerAdapter;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use PHPUnit\Framework\TestCase;
/**
* Class TwigRendererAdapterTest.
*/
class KloggerAdapterTest extends TestCase
{
/** @var array */
protected $config;
/** @var string */
protected $dateToday;
/** @var string */
protected $dateYesterday;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$this->dateToday = date('Y-m-d');
$this->dateYesterday = date('Y-m-d', (time()-(60*60*24)));
// Check also in the setup in case of unexpected exception would cut the execution flow and teardown not called.
if (file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log')) {
unlink(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log');
}
// To make sure that the test doesn't provide extra log files because of a midnight date change, we also check
// for a "yesterday" log file.
if (file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateYesterday).'.log')) {
unlink(__DIR__.'/../../../data/log/testlog-'.($this->dateYesterday).'.log');
}
$this->config = require __DIR__.'/../test_config.php';
}
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*/
public function tearDown()
{
parent::tearDown();
if (file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log')) {
unlink(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log');
}
// To make sure that the test doesn't provide extra log files because of a midnight date change, we also check
// for a "yesterday" log file.
if (file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateYesterday).'.log')) {
unlink(__DIR__.'/../../../data/log/testlog-'.($this->dateYesterday).'.log');
}
}
/**
* Tests constructor
*/
public function testConstructor()
{
$config = new Config($this->config);
$testObj = new KloggerAdapter($config, 'unit');
$this->assertInstanceOf(LogAdapterInterface::class, $testObj);
}
/**
* Test log.
*/
public function testLog()
{
$config = new Config($this->config);
$testObj = new KloggerAdapter($config, 'unit');
$testObj->log(3, 'Warning test');
$testObj->log('notice', 'Notice test');
$testObj->log(4332, 'Default numeric warning test');
$testObj->log('some_level', 'Default string warning test');
$logfileExists = file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log')
|| file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateYesterday).'.log');
$this->assertTrue($logfileExists);
if (file_exists(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log')) {
$content = file(__DIR__.'/../../../data/log/testlog-'.($this->dateToday).'.log');
} else {
$content = file(__DIR__.'/../../../data/log/testlog-'.($this->dateYesterday).'.log');
}
$this->assertEquals(4, count($content));
$this->assertNotFalse(strpos($content[1], '[notice] Notice test'));
$this->assertNotFalse(strpos($content[3], '[warning] Default string warning test'));
}
}
<file_sep>/src/WebHemi/Ftp/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Ftp;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
public const FILE_MODE_TEXT = FTP_ASCII;
public const FILE_MODE_BINARY = FTP_BINARY;
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration);
/**
* Connect and login to remote host.
*
* @return ServiceInterface
*/
public function connect() : ServiceInterface;
/**
* Disconnect from remote host.
*
* @return ServiceInterface
*/
public function disconnect() : ServiceInterface;
/**
* Sets an option data.
*
* @param string $key
* @param mixed $value
* @return ServiceInterface
*/
public function setOption(string $key, $value) : ServiceInterface;
/**
* Sets a group of options.
*
* @param array $options
* @return ServiceInterface
*/
public function setOptions(array $options) : ServiceInterface;
/**
* Gets a specific option data.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function getOption(string $key, $default = null);
/**
* Toggles connection security level.
*
* @param bool $state
* @return ServiceInterface
*/
public function setSecureConnection(bool $state) : ServiceInterface;
/**
* Toggles connection passive mode.
*
* @param bool $state
* @return ServiceInterface
*/
public function setPassiveMode(bool $state) : ServiceInterface;
/**
* Sets remote path.
*
* @param string $path
* @return ServiceInterface
*/
public function setRemotePath(string $path) : ServiceInterface;
/**
* Gets remote path.
*
* @return string
*/
public function getRemotePath() : string;
/**
* Sets local path.
*
* @param string $path
* @return ServiceInterface
*/
public function setLocalPath(string $path) : ServiceInterface;
/**
* Gets local path.
*
* @return string
*/
public function getLocalPath() : string;
/**
* Lists remote path.
*
* @param null|string $path
* @param bool|null $changeToDirectory
* @return array
*/
public function getRemoteFileList(? string $path, ? bool $changeToDirectory) : array;
/**
* Uploads file to remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $sourceFileName
* @param string $destinationFileName
* @param int $fileMode
* @return ServiceInterface
*/
public function upload(
string $sourceFileName,
string $destinationFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface;
/**
* Downloads file from remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $remoteFileName
* @param string $localFileName
* @param int $fileMode
* @return ServiceInterface
*/
public function download(
string $remoteFileName,
string&$localFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface;
/**
* Moves file on remote host.
*
* @param string $currentPath
* @param string $newPath
* @return ServiceInterface
*/
public function moveRemoteFile(string $currentPath, string $newPath) : ServiceInterface;
/**
* Deletes file on remote host.
*
* @param string $path
* @return ServiceInterface
*/
public function deleteRemoteFile(string $path) : ServiceInterface;
}
<file_sep>/src/WebHemi/Application/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Application\ServiceAdapter\Base;
use Throwable;
use RuntimeException;
use Psr\Http\Message\StreamInterface;
use WebHemi\Application\ServiceInterface;
use WebHemi\Application\ServiceAdapter\AbstractAdapter;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\MiddlewarePipeline\ServiceInterface as PipelineInterface;
use WebHemi\Middleware\Common as CommonMiddleware;
use WebHemi\Middleware\MiddlewareInterface;
use WebHemi\Renderer\ServiceInterface as RendererInterface;
use WebHemi\Session\ServiceInterface as SessionInterface;
/**
* Class ServiceAdapter
*/
class ServiceAdapter extends AbstractAdapter
{
/**
* Starts the session.
*
* @return ServiceInterface
*
* @codeCoverageIgnore - not testing session (yet)
*/
public function initSession() : ServiceInterface
{
if (defined('PHPUNIT_WEBHEMI_TESTSUITE')) {
return $this;
}
/**
* @var SessionInterface $sessionManager
*/
$sessionManager = $this->container->get(SessionInterface::class);
/**
* @var EnvironmentInterface $environmentManager
*/
$environmentManager = $this->container->get(EnvironmentInterface::class);
$name = $environmentManager->getSelectedApplication();
$timeOut = 3600;
$path = $environmentManager->getSelectedApplicationUri();
$domain = $environmentManager->getApplicationDomain();
$secure = $environmentManager->isSecuredApplication();
$httpOnly = true;
$sessionManager->start($name, $timeOut, $path, $domain, $secure, $httpOnly);
return $this;
}
/**
* Runs the application. This is where the magic happens.
* According tho the environment settings this must build up the middleware pipeline and execute it.
*
* a Pre-Routing Middleware can be; priority < 0:
* - LockCheck - check if the client IP is banned > S102|S403
* - Auth - if the user is not logged in, but there's a "Remember me" cookie, then logs in > S102
*
* Routing Middleware is fixed (RoutingMiddleware::class); priority = 0:
* - A middleware that routes the incoming Request and delegates to the matched middleware. > S102|S404|S405
* The RouteResult should be attached to the Request.
* If the Routing is not defined explicitly in the pipeline, then it will be injected with priority 0.
*
* a Post-Routing Middleware can be; priority between 0 and 100:
* - Acl - checks if the given route is available for the client. Also checks the auth > S102|S401|S403
* - CacheReader - checks if a suitable response body is cached. > S102|S200
*
* Dispatcher Middleware is fixed (DispatcherMiddleware::class); priority = 100:
* - A middleware which gets the corresponding Action middleware and applies it > S102
* If the Dispatcher is not defined explicitly in the pipeline, then it will be injected with priority 100.
* The Dispatcher should not set the response Status Code to 200 to let Post-Dispatchers to be called.
*
* a Post-Dispatch Middleware can be; priority > 100:
* - CacheWriter - writes response body into DataStorage (DB, File etc.) > S102
*
* Final Middleware is fixed (FinalMiddleware:class):
* - This middleware behaves a bit differently. It cannot be ordered, it's always the last called middleware:
* - when the middleware pipeline reached its end (typically when the Status Code is still 102)
* - when one item of the middleware pipeline returns with return response (status code is set to 200|40*|500)
* - when during the pipeline process an Exception is thrown.
*
* When the middleware pipeline is finished the application prints the header and the output.
*
* If a middleware other than the Routing, Dispatcher and Final Middleware has no priority set, it will be
* considered to have priority = 50.
*
* @return ServiceInterface
*/
public function run() : ServiceInterface
{
/**
* @var PipelineInterface $pipelineManager
*/
$pipelineManager = $this->container->get(PipelineInterface::class);
try {
/**
* @var string $middlewareClass
*/
$middlewareClass = $pipelineManager->start();
while (!empty($middlewareClass)
&& is_string($middlewareClass)
&& $this->response->getStatusCode() == ResponseInterface::STATUS_PROCESSING
) {
$this->invokeMiddleware($middlewareClass);
$middlewareClass = $pipelineManager->next();
};
// If there was no error, we mark as ready for output.
if ($this->response->getStatusCode() == ResponseInterface::STATUS_PROCESSING) {
$this->response = $this->response->withStatus(ResponseInterface::STATUS_OK);
}
} catch (Throwable $exception) {
$code = ResponseInterface::STATUS_INTERNAL_SERVER_ERROR;
if (in_array(
$exception->getCode(),
[
ResponseInterface::STATUS_BAD_REQUEST,
ResponseInterface::STATUS_UNAUTHORIZED,
ResponseInterface::STATUS_FORBIDDEN,
ResponseInterface::STATUS_NOT_FOUND,
ResponseInterface::STATUS_BAD_METHOD,
ResponseInterface::STATUS_NOT_IMPLEMENTED,
]
)
) {
$code = $exception->getCode();
}
$this->response = $this->response->withStatus($code);
$this->request = $this->request
->withAttribute(ServerRequestInterface::REQUEST_ATTR_MIDDLEWARE_EXCEPTION, $exception);
}
/**
* @var CommonMiddleware\FinalMiddleware $finalMiddleware
*/
$finalMiddleware = $this->container->get(CommonMiddleware\FinalMiddleware::class);
// Check response and log errors if necessary
$finalMiddleware($this->request, $this->response);
return $this;
}
/**
* Renders the response body and sends it to the client.
*
* @return void
*
* @codeCoverageIgnore - no output for tests
*/
public function renderOutput() : void
{
// Create template only when there's no redirect
if (!$this->request->isXmlHttpRequest()
&& ResponseInterface::STATUS_REDIRECT != $this->response->getStatusCode()
) {
/**
* @var RendererInterface $templateRenderer
*/
$templateRenderer = $this->container->get(RendererInterface::class);
/**
* @var string $template
*/
$template = $this->request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_TEMPLATE);
/**
* @var array $data
*/
$data = $this->request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA);
/**
* @var null|Throwable $exception
*/
$exception = $this->request->getAttribute(ServerRequestInterface::REQUEST_ATTR_MIDDLEWARE_EXCEPTION);
// If there was any error, change the remplate
if (!empty($exception)) {
$template = 'error-'.$this->response->getStatusCode();
$data['exception'] = $exception;
}
/**
* @var StreamInterface $body
*/
$body = $templateRenderer->render($template, $data);
$this->response = $this->response->withBody($body);
}
$this->sendOutput();
}
/**
* Sends the response body to the client.
*
* @return void
*
* @codeCoverageIgnore - no output for tests
*/
public function sendOutput() : void
{
// @codeCoverageIgnoreStart
if (!defined('PHPUNIT_WEBHEMI_TESTSUITE') && headers_sent()) {
throw new RuntimeException('Unable to emit response; headers already sent', 1000);
}
// @codeCoverageIgnoreEnd
$output = $this->response->getBody();
$contentLength = $this->response->getBody()->getSize();
if ($this->request->isXmlHttpRequest()) {
/**
* @var array $templateData
*/
$templateData = $this->request->getAttribute(ServerRequestInterface::REQUEST_ATTR_DISPATCH_DATA);
$templateData['output'] = (string) $output;
/**
* @var null|Throwable $exception
*/
$exception = $this->request->getAttribute(ServerRequestInterface::REQUEST_ATTR_MIDDLEWARE_EXCEPTION);
if (!empty($exception)) {
$templateData['exception'] = $exception;
}
$output = json_encode($templateData);
$contentLength = strlen($output);
$this->response = $this->response->withHeader('Content-Type', 'application/json; charset=UTF-8');
}
$this->injectContentLength($contentLength);
$this->sendHttpHeader();
$this->sendOutputHeaders($this->response->getHeaders());
echo $output;
}
/**
* Instantiates and invokes a middleware
*
* @param string $middlewareClass
* @return void
*/
protected function invokeMiddleware(string $middlewareClass) : void
{
/**
* @var MiddlewareInterface $middleware
*/
$middleware = $this->container->get($middlewareClass);
$requestAttributes = $this->request->getAttributes();
// As an extra step if an action middleware is resolved, it should be invoked by the dispatcher.
if (isset($requestAttributes[ServerRequestInterface::REQUEST_ATTR_RESOLVED_ACTION_CLASS])
&& $middleware instanceof CommonMiddleware\DispatcherMiddleware
) {
/**
* @var MiddlewareInterface $actionMiddleware
*/
$actionMiddleware = $this->container
->get($requestAttributes[ServerRequestInterface::REQUEST_ATTR_RESOLVED_ACTION_CLASS]);
$this->request = $this->request->withAttribute(
ServerRequestInterface::REQUEST_ATTR_ACTION_MIDDLEWARE,
$actionMiddleware
);
}
$middleware($this->request, $this->response);
}
/**
* Inject the Content-Length header if is not already present.
*
* NOTE: if there will be chunk content displayed, check if the response getSize counts the real size correctly
*
* @param null|int $contentLength
* @return void
*
* @codeCoverageIgnore - no putput for tests.
*/
protected function injectContentLength(? int $contentLength) : void
{
$contentLength = intval($contentLength);
if (!$this->response->hasHeader('Content-Length') && $contentLength > 0) {
$this->response = $this->response->withHeader('Content-Length', (string) $contentLength);
}
}
/**
* Filter a header name to word case.
*
* @param string $headerName
* @return string
*/
protected function filterHeaderName(string $headerName) : string
{
$filtered = str_replace('-', ' ', $headerName);
$filtered = ucwords($filtered);
return str_replace(' ', '-', $filtered);
}
/**
* Sends the HTTP header.
*
* @return void
*
* @codeCoverageIgnore - vendor and core function calls
*/
protected function sendHttpHeader() : void
{
$reasonPhrase = $this->response->getReasonPhrase();
header(
sprintf(
'HTTP/%s %d%s',
$this->response->getProtocolVersion(),
$this->response->getStatusCode(),
($reasonPhrase ? ' '.$reasonPhrase : '')
)
);
}
/**
* Sends out output headers.
*
* @param array $headers
* @return void
*
* @codeCoverageIgnore - vendor and core function calls in loop
*/
protected function sendOutputHeaders(array $headers) : void
{
foreach ($headers as $headerName => $values) {
$name = $this->filterHeaderName($headerName);
$first = true;
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), $first);
$first = false;
}
}
}
}
<file_sep>/src/WebHemi/Acl/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Acl\ServiceAdapter\Base;
use WebHemi\Acl\ServiceAdapter\AbstractServiceAdapter;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\PolicyEntity;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Entity\UserGroupEntity;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter extends AbstractServiceAdapter
{
/**
* Checks if a User can access to a Resource in an Application
*
* @param UserEntity $userEntity
* @param ResourceEntity|null $resourceEntity
* @param ApplicationEntity|null $applicationEntity
* @param string|null $method
* @return bool
*/
public function isAllowed(
UserEntity $userEntity,
? ResourceEntity $resourceEntity = null,
? ApplicationEntity $applicationEntity = null,
? string $method = null
) : bool {
// By default we block everything.
$allowed = false;
$policies = $this->getUserPolicies($userEntity);
$policies->merge($this->getUserGroupPolicies($userEntity));
/** @var PolicyEntity $policyEntity */
foreach ($policies as $policyEntity) {
if ($this->isPolicyAllowed($policyEntity, $resourceEntity, $applicationEntity, $method)) {
$allowed = true;
break;
}
}
return $allowed;
}
/**
* Gets the policies assigned to the user.
*
* @param UserEntity $userEntity
* @return EntitySet
*/
private function getUserPolicies(UserEntity $userEntity) : EntitySet
{
return $this->policyStorage->getPolicyListByUser((int) $userEntity->getUserId());
}
/**
* Gets the policies assigned to the group in which the user is.
*
* @param UserEntity $userEntity
* @return EntitySet
*/
private function getUserGroupPolicies(UserEntity $userEntity) : EntitySet
{
$userGroups = $this->userStorage->getUserGroupListByUser((int) $userEntity->getUserId());
$groupPolicies = $this->userStorage->createEntitySet();
/** @var UserGroupEntity $userGroupEntity */
foreach ($userGroups as $userGroupEntity) {
$policyList = $this->policyStorage->getPolicyListByUserGroup((int) $userGroupEntity->getUserGroupId());
if (!empty($policyList)) {
$groupPolicies->merge($policyList);
}
}
return $groupPolicies;
}
}
<file_sep>/tests/WebHemiTest/TestService/TestExceptionMiddleware.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use InvalidArgumentException;
use WebHemi\Http\ResponseInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Middleware\MiddlewareInterface;
/**
* Class TestExceptionMiddleware
*/
class TestExceptionMiddleware implements MiddlewareInterface
{
/**
* TestMiddleware constructor.
*/
public function __construct()
{
throw new InvalidArgumentException('it should cause an error');
}
/**
* Invokes the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @return void
*/
public function __invoke(ServerRequestInterface &$request, ResponseInterface&$response) : void
{
$method = $request->getMethod();
$response = $response->withHeader('request-method', $method);
}
}
<file_sep>/tests/WebHemiTest/Data/Entity/FilesystemDocumentEntityTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use WebHemi\Data\Entity\FilesystemDocumentEntity;
use WebHemi\DateTime;
/**
* Class FilesystemDocumentEntityTest
*/
class FilesystemDocumentEntityTest extends AbstractEntityTestCase
{
/** @var array */
protected $testData = [
'id_filesystem_document' => 1,
'fk_parent_revision' => 2,
'fk_author' => 2,
'content_revision' => 1,
'content_lead' => 'test lead',
'content_body' => 'test body',
'date_created' => '2016-04-26 23:21:19',
'date_modified' => '2016-04-26 23:21:19',
];
/** @var array */
protected $expectedGetters = [
'getFilesystemDocumentId' => 1,
'getParentRevisionId' => 2,
'getAuthorId' => 2,
'getContentRevision' => 1,
'getContentLead' => 'test lead',
'getContentBody' => 'test body',
'getDateCreated' => null,
'getDateModified' => null,
];
/** @var array */
protected $expectedSetters = [
'setFilesystemDocumentId' => 1,
'setParentRevisionId' => 2,
'setAuthorId' => 2,
'setContentRevision' => 1,
'setContentLead' => 'test lead',
'setContentBody' => 'test body',
'setDateCreated' => null,
'setDateModified' => null,
];
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$dateTime = new DateTime('2016-04-26 23:21:19');
$this->expectedGetters['getDateCreated'] = $dateTime;
$this->expectedGetters['getDateModified'] = $dateTime;
$this->expectedSetters['setDateCreated'] = $dateTime;
$this->expectedSetters['setDateModified'] = $dateTime;
$this->entity = new FilesystemDocumentEntity();
}
}
<file_sep>/tests/WebHemiTest/DateTimeTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest;
use DateTimeZone;
use PHPUnit\Framework\TestCase;
use WebHemi\DateTime;
/**
* Class DateTimeTest.
*/
class DateTimeTest extends TestCase
{
/**
* Tests class constructor.
*/
public function testConstructor()
{
$originalTimezone = date_default_timezone_get();
$expectedTimestamp = mktime(12, 13, 14, 5, 6, 2017);
$expectedTimeZone = date_default_timezone_get();
$dateTime = new DateTime($expectedTimestamp);
$this->assertSame($expectedTimestamp, $dateTime->getTimestamp());
$this->assertSame($expectedTimeZone, $dateTime->getTimezone()->getName());
date_default_timezone_set('Europe/London');
$expectedTimeZone = 'Europe/London';
$timeZone = new DateTimeZone($expectedTimeZone);
$date = date('Y-m-d H:i:s', $expectedTimestamp);
$dateTime = new DateTime($date, $timeZone);
$this->assertSame($expectedTimestamp, $dateTime->getTimestamp());
$this->assertSame($expectedTimeZone, $dateTime->getTimezone()->getName());
date_default_timezone_set($originalTimezone);
}
/**
* Data provider for checker test.
*
* @return array
*/
public function checkerProvider()
{
$notThisDay = date('d') == 1 ? 2 : (date('d') - 1);
$notThisMonth = date('m') == 1 ? 2 : (date('m') - 1);
$today = time();
$thisMonth = mktime(1, 2, 3, date('m'), $notThisDay, date('Y'));
$thisYear = mktime(1, 2, 3, $notThisMonth, 1, date('Y'));
$notThisYear = mktime(1, 2, 3, 1, 1, 2000);
return [
[date('Y-m-d', $today), true, true, true],
[date('Y-m-d', $thisMonth), false, true, true],
[date('Y-m-d', $thisYear), false, false, true],
[date('Y-m-d', $notThisYear), false, false, false],
];
}
/**
* Tests checker functions.
*
* @covers \WebHemi\DateTime::isToday()
* @covers \WebHemi\DateTime::isCurrentMonth()
* @covers \WebHemi\DateTime::isCurrentYear()
* @dataProvider checkerProvider
*/
public function testCheckers($date, $isToday, $isCurrentMonth, $isCurrentYear)
{
$originalTimezone = date_default_timezone_get();
date_default_timezone_set('Europe/London');
$timeZone = new DateTimeZone('Europe/London');
$dateTime = new DateTime($date, $timeZone);
$this->assertSame($isToday, $dateTime->isToday());
$this->assertSame($isCurrentMonth, $dateTime->isCurrentMonth());
$this->assertSame($isCurrentYear, $dateTime->isCurrentYear());
date_default_timezone_set($originalTimezone);
}
/**
* Tests format method.
*/
public function testFormatter()
{
$originalTimezone = date_default_timezone_get();
$timeZoneWithNoDataInWebhemi = new DateTimeZone('Africa/Abidjan');
$timeZoneWithDataInWebhemi = new DateTimeZone('Europe/London');
$timeZoneWithDataInWebhemiHu = new DateTimeZone('Europe/Budapest');
$testDate = '2017-09-10 11:12:13';
date_default_timezone_set('Africa/Abidjan');
$dateTime = new DateTime($testDate, $timeZoneWithNoDataInWebhemi);
$resultDate = $dateTime->format('BDT');
// The expected result is a strange format, since we didn't have a definition for this named format.
$expectedDate = '508SunGMT';
$this->assertSame($expectedDate, $resultDate);
date_default_timezone_set('Europe/London');
$dateTime = new DateTime($testDate, $timeZoneWithDataInWebhemi);
$resultDate = $dateTime->format('BDT');
// The expected result is a translated.
$expectedDate = '10th September, 11:12 am';
$this->assertSame(strtolower($expectedDate), strtolower($resultDate));
date_default_timezone_set('Europe/Budapest');
$dateTime = new DateTime($testDate, $timeZoneWithDataInWebhemiHu);
$resultDate = $dateTime->format('BDT');
// The expected result is a translated.
$expectedDate = 'September 10. 11:12';
$this->assertSame($expectedDate, $resultDate);
date_default_timezone_set($originalTimezone);
}
/**
* Tests the toString method.
*/
public function testToString()
{
$originalTimezone = date_default_timezone_get();
date_default_timezone_set('Europe/London');
$timeZone = new DateTimeZone('Europe/London');
$timestamp = mktime(12, 13, 14, 5, 6, 2017);
$dateTime = new DateTime($timestamp, $timeZone);
$expectedDate = date('Y-m-d H:i:s', $timestamp);
$currentDate = $dateTime->__toString();
$this->assertSame($expectedDate, $currentDate);
date_default_timezone_set($originalTimezone);
}
}
<file_sep>/tests/WebHemiTest/Middleware/DispatcherMiddlewareTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Middleware;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\ServerRequest;
use WebHemi\Http\ServiceAdapter\GuzzleHttp\Response;
use WebHemi\Middleware\Common\DispatcherMiddleware;
use WebHemiTest\TestService\TestMiddleware;
use WebHemiTest\TestService\TestActionMiddleware;
/**
* Class DispatcherMiddlewareTest.
*/
class DispatcherMiddlewareTest extends TestCase
{
/**
* Tears down the fixture, for example, close a network connection.
* This method is called after a test is executed.
*/
public function tearDown()
{
parent::tearDown();
TestMiddleware::$counter = 0;
TestMiddleware::$trace = [];
}
/**
* Tests middleware when all the injections work as expected.
*/
public function testMiddleware()
{
$middlewareAction = new TestActionMiddleware();
$request = new ServerRequest('GET', '/');
$request = $request
->withAttribute(ServerRequest::REQUEST_ATTR_ACTION_MIDDLEWARE, $middlewareAction)
->withAttribute(ServerRequest::REQUEST_ATTR_DISPATCH_TEMPLATE, 'test')
->withAttribute(ServerRequest::REQUEST_ATTR_DISPATCH_DATA, ['test' => 'test']);
$response = new Response(Response::STATUS_PROCESSING);
$middleware = new DispatcherMiddleware();
$responseBeforeMiddleware = $response;
$this->assertTrue($response === $responseBeforeMiddleware);
$middleware($request, $response);
$this->assertTrue($response !== $responseBeforeMiddleware);
$this->assertEquals(Response::STATUS_PROCESSING, $response->getStatusCode());
}
/**
* Tests middleware when no action middleware is given.
*/
public function testMiddlewareNoActionGiven()
{
$request = new ServerRequest('GET', '/');
$response = new Response(Response::STATUS_PROCESSING);
$middleware = new DispatcherMiddleware();
$this->expectException(RuntimeException::class);
$middleware($request, $response);
}
/**
* Tests middleware when given object is not an action middleware.
*/
public function testMiddlewareObjectIsNotAction()
{
$middlewareAction = new TestMiddleware('x');
$request = new ServerRequest('GET', '/');
$request = $request->withAttribute(ServerRequest::REQUEST_ATTR_ACTION_MIDDLEWARE, $middlewareAction);
$response = new Response(Response::STATUS_PROCESSING);
$middleware = new DispatcherMiddleware();
$this->expectException(RuntimeException::class);
$middleware($request, $response);
}
}
<file_sep>/tests/WebHemiTest/Data/Entity/FilesystemCategoryEntityTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Data\Entity;
use WebHemi\Data\Entity\FilesystemCategoryEntity;
use WebHemi\DateTime;
/**
* Class FilesystemCategoryEntityTest
*/
class FilesystemCategoryEntityTest extends AbstractEntityTestCase
{
/** @var array */
protected $testData = [
'id_filesystem_category' => 1,
'fk_application' => 1,
'name' => '<NAME>',
'title' => 'test title',
'description' => 'test description',
'item_order' => 'test order',
'date_created' => '2016-04-26 23:21:19',
'date_modified' => '2016-04-26 23:21:19',
];
/** @var array */
protected $expectedGetters = [
'getFilesystemCategoryId' => 1,
'getApplicationId' => 1,
'getName' => 'test name',
'getTitle' => 'test title',
'getDescription' => 'test description',
'getItemOrder' => 'test order',
'getDateCreated' => null,
'getDateModified' => null,
];
/** @var array */
protected $expectedSetters = [
'setFilesystemCategoryId' => 1,
'setApplicationId' => 1,
'setName' => 'test name',
'setTitle' => 'test title',
'setDescription' => 'test description',
'setItemOrder' => 'test order',
'setDateCreated' => null,
'setDateModified' => null,
];
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
parent::setUp();
$dateTime = new DateTime('2016-04-26 23:21:19');
$this->expectedGetters['getDateCreated'] = $dateTime;
$this->expectedGetters['getDateModified'] = $dateTime;
$this->expectedSetters['setDateCreated'] = $dateTime;
$this->expectedSetters['setDateModified'] = $dateTime;
$this->entity = new FilesystemCategoryEntity();
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getUserGroupList.sql
SELECT
ug.`id_user_group`,
ug.`name`,
ug.`title`,
ug.`description`,
ug.`is_read_only`,
ug.`date_created`,
ug.`date_modified`
FROM
`webhemi_user_group` AS ug
ORDER BY
ug.`name`
LIMIT
:limit
OFFSET
:offset
<file_sep>/tests/WebHemiTest/TestService/EmptyEntity2.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
/**
* Class EmptyEntity.
*/
class EmptyEntity2 extends EmptyEntity
{
}
<file_sep>/src/WebHemi/I18n/DriverAdapter/Gettext/DriverAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\I18n\DriverAdapter\Gettext;
use RuntimeException;
use WebHemi\I18n\ServiceInterface;
use WebHemi\I18n\DriverInterface;
/**
* Interface DriverInterface.
*
* @codeCoverageIgnore - uses PHP extension
*/
class DriverAdapter implements DriverInterface
{
/**
* @var string
*/
private $translationPath;
/**
* @var ServiceInterface
*/
private $i18nService;
/**
* @var string
*/
private $textDomain;
/**
* DriverInterface constructor.
*
* @param ServiceInterface $i18nService
*/
public function __construct(ServiceInterface $i18nService)
{
$this->i18nService = $i18nService;
$this->translationPath = realpath(__DIR__.'/../../Translation');
$this->textDomain = 'messages';
if (!extension_loaded('gettext') || !function_exists('bindtextdomain')) {
throw new RuntimeException('The gettext module is not loaded!');
}
$this->initDriver();
}
/**
* Initializes the driver.
*/
private function initDriver()
{
bind_textdomain_codeset($this->textDomain, $this->i18nService->getCodeSet());
bindtextdomain($this->textDomain, $this->translationPath);
textdomain($this->textDomain);
}
/**
* Translates the given text.
*
* @param string $text
* @return string
*/
public function translate(string $text) : string
{
return gettext($text);
}
}
<file_sep>/src/WebHemi/Router/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Router\ServiceAdapter\Base;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Http\ServerRequestInterface;
use WebHemi\Router\ProxyInterface;
use WebHemi\Router\Result\Result;
use WebHemi\Router\ServiceInterface;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var Result
*/
private $result;
/**
* @var array
*/
private $routes;
/**
* @var string
*/
private $module;
/**
* @var string
*/
private $application;
/**
* @var string
*/
private $applicationPath;
/**
* @var null|ProxyInterface
*/
private $proxy;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
* @param Result $routeResult
* @param null|ProxyInterface $routerProxy
*/
public function __construct(
ConfigurationInterface $configuration,
EnvironmentInterface $environmentManager,
Result $routeResult,
? ProxyInterface $routerProxy = null
) {
$module = $environmentManager->getSelectedModule();
$this->routes = $configuration->getData('router/'.$module);
$this->proxy = $routerProxy;
$this->result = $routeResult;
$this->module = $environmentManager->getSelectedModule();
$this->application = $environmentManager->getSelectedApplication();
$this->applicationPath = $environmentManager->getSelectedApplicationUri();
}
/**
* Processes the Request and give a Result.
*
* @param ServerRequestInterface $request
* @return Result
*/
public function match(ServerRequestInterface $request) : Result
{
$httpMethod = $request->getMethod();
$uri = $this->getApplicationRouteUri($request);
$result = clone $this->result;
$result->setStatus(Result::CODE_FOUND);
$routeDefinition = $this->findRouteDefinition($uri);
if (empty($routeDefinition)) {
return $result->setStatus(Result::CODE_NOT_FOUND);
}
if (!in_array($httpMethod, $routeDefinition['allowed_methods'])) {
return $result->setStatus(Result::CODE_BAD_METHOD);
}
$result->setParameters($routeDefinition['parameters'])
->setResource($routeDefinition['resource'])
->setMatchedMiddleware($routeDefinition['middleware']);
// Check if we marked the middleware to be resolved by the proxy
if ($routeDefinition['middleware'] === 'proxy' && $this->proxy instanceof ProxyInterface) {
$this->proxy->resolveMiddleware($this->application, $result);
}
return $result;
}
/**
* According to the application path, determines the route uri
*
* @param ServerRequestInterface $request
* @return string
*/
private function getApplicationRouteUri(ServerRequestInterface $request) : string
{
$uri = $request->getUri()->getPath();
if ($this->applicationPath != '/' && strpos($uri, $this->applicationPath) === 0) {
$uri = substr($uri, strlen($this->applicationPath));
}
return empty($uri) ? '/' : $uri;
}
/**
* Searches definition and returns data is found. First find, first served.
*
* @param string $uri
* @return array|null
*/
private function findRouteDefinition(string $uri) : ? array
{
$routeDefinition = [];
$matches = [];
foreach ($this->routes as $resource => $routeData) {
$pattern = '#'.$routeData['path'].'#';
if (preg_match_all($pattern, $uri, $matches, PREG_SET_ORDER, 0)) {
$parameters = $this->getMatchParameters($matches);
$routeDefinition = [
'uri' => $uri,
'middleware' => $routeData['middleware'],
'parameters' => $parameters,
'resource' => $resource,
'allowed_methods' => $routeData['allowed_methods']
];
break;
}
}
return $routeDefinition;
}
/**
* Gets the paramters from the route pattern match result.
*
* @param array $matches
* @return array
*/
private function getMatchParameters(array $matches) : array
{
$parameters = [];
foreach ($matches[0] as $index => $value) {
if (!is_numeric($index)) {
$parameters[$index] = $value;
}
}
if ($this->module == 'Website') {
$parameters['path'] = !empty($matches[0]['path']) ? $matches[0]['path'] : '/';
$parameters['basename'] = !empty($matches[0]['basename']) ? $matches[0]['basename'] : 'index.html';
}
return $parameters;
}
}
<file_sep>/src/WebHemi/Middleware/Action/Auth/LoginAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Auth;
use Exception;
use InvalidArgumentException;
use WebHemi\Auth\CredentialInterface;
use WebHemi\Auth\Result\Result;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Form\Element\Html\HtmlElement;
use WebHemi\Form\ElementInterface;
use WebHemi\Form\PresetInterface;
use WebHemi\Form\ServiceAdapter\Base\ServiceAdapter as HtmlForm;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class LoginAction.
*/
class LoginAction extends AbstractMiddlewareAction
{
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var CredentialInterface
*/
private $authCredential;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* @var PresetInterface
*/
private $loginFormPreset;
/**
* LoginAction constructor.
*
* @param AuthInterface $authAdapter
* @param CredentialInterface $authCredential
* @param EnvironmentInterface $environmentManager
* @param PresetInterface $loginFormPreset
*/
public function __construct(
AuthInterface $authAdapter,
CredentialInterface $authCredential,
EnvironmentInterface $environmentManager,
PresetInterface $loginFormPreset
) {
$this->authAdapter = $authAdapter;
$this->authCredential = $authCredential;
$this->environmentManager = $environmentManager;
$this->loginFormPreset = $loginFormPreset;
}
/**
* Gets template map name or template file path.
* This middleware does not have any output.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-login';
}
/**
* Gets template data.
*
* @throws Exception
* @return array
*/
public function getTemplateData() : array
{
$form = $this->getLoginForm();
if ($this->request->getMethod() == 'POST') {
/** @var array $postData */
$postData = $this->request->getParsedBody();
if (!is_array($postData)) {
throw new InvalidArgumentException('Post data must be an array!');
}
$this->authCredential->setCredential('username', $postData['login']['identification'] ?? '')
->setCredential('password', $postData['login']['password'] ?? '');
/**
* @var Result $result
*/
$result = $this->authAdapter->authenticate($this->authCredential);
if (!$result->isValid()) {
$form = $this->getLoginForm($result->getMessage());
// load back faild data.
unset($postData['login']['password']);
$form->loadData($postData);
} else {
/**
* @var null|UserEntity $userEntity
*/
$userEntity = $this->authAdapter->getIdentity();
if ($userEntity instanceof UserEntity) {
$this->authAdapter->setIdentity($userEntity);
}
// Don't redirect upon Ajax request
if (!$this->request->isXmlHttpRequest()) {
$url = 'http'.($this->environmentManager->isSecuredApplication() ? 's' : '').'://'.
$this->environmentManager->getApplicationDomain().
$this->environmentManager->getSelectedApplicationUri();
$this->response = $this->response
->withStatus(302, 'Found')
->withHeader('Location', $url);
}
}
}
return [
'loginForm' => $form,
];
}
/**
* Gets the login form.
*
* @param string $customError
* @return HtmlForm
*/
private function getLoginForm(string $customError = '') : HtmlForm
{
/**
* @var HtmlForm $form
*/
$form = $this->loginFormPreset->getPreset();
if (!empty($customError)) {
/**
* @var ElementInterface[] $elements
*/
$elements = $form->getElements();
/**
* @var ElementInterface $element
*/
foreach ($elements as $element) {
if ($element->getType() == HtmlElement::HTML_ELEMENT_INPUT_PASSWORD) {
$element->setError(AuthInterface::class, $customError);
// Since the name attribute didn't change, adding to the form will overwrite the old one.
$form->addElement($element);
break;
}
}
}
return $form;
}
}
<file_sep>/src/WebHemi/Middleware/Action/Admin/DashboardAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Admin;
use WebHemi\Data\Entity\EntitySet;
use WebHemi\Data\Entity\UserGroupEntity;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Auth\ServiceInterface as AuthInterface;
use WebHemi\Middleware\Action\AbstractMiddlewareAction;
/**
* Class DashboardAction.
*/
class DashboardAction extends AbstractMiddlewareAction
{
/**
* @var AuthInterface
*/
private $authAdapter;
/**
* @var EnvironmentInterface
*/
private $environmentManager;
/**
* DashboardAction constructor.
*
* @param AuthInterface $authAdapter
* @param EnvironmentInterface $environmentManager
*/
public function __construct(
AuthInterface $authAdapter,
EnvironmentInterface $environmentManager
) {
$this->authAdapter = $authAdapter;
$this->environmentManager = $environmentManager;
}
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return 'admin-dashboard';
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
global $dependencyInjection;
$userEntity = $this->authAdapter->getIdentity();
if ($userEntity instanceof $userEntity) {
/**
* @var \WebHemi\Data\Storage\UserStorage $userStorage
*/
$userStorage = $dependencyInjection->get(\WebHemi\Data\Storage\UserStorage::class);
/**
* @var \WebHemi\Data\Storage\PolicyStorage $policyStorage
*/
$policyStorage = $dependencyInjection->get(\WebHemi\Data\Storage\PolicyStorage::class);
$userGroups = ($userStorage instanceof \WebHemi\Data\Storage\UserStorage)
? $userStorage->getUserGroupListByUser((int) $userEntity->getUserId())
: new EntitySet();
$userPolicies = ($policyStorage instanceof \WebHemi\Data\Storage\PolicyStorage)
? $policyStorage->getPolicyListByUser((int) $userEntity->getUserId())
: new EntitySet();
/** @var EntitySet $userGroupPolicies */
$userGroupPolicies = new EntitySet();
/** @var UserGroupEntity $userGroupEntity */
foreach ($userGroups as $userGroupEntity) {
$policyList = ($policyStorage instanceof \WebHemi\Data\Storage\PolicyStorage)
? $policyStorage->getPolicyListByUserGroup((int) $userGroupEntity->getUserGroupId())
: new EntitySet();
$userGroupPolicies->merge($policyList);
}
// @TODO TBD
return [
'user' => $userEntity ?? false,
'user_groups' => $userGroups ?? false,
'user_policies' => $userPolicies ?? false,
'user_group_policies' => $userGroupPolicies ?? false,
];
}
return [];
}
}
<file_sep>/src/WebHemi/Renderer/Filter/Tags/Url.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Filter\Tags;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Renderer\TagFilterInterface;
/**
* Class Url
*/
class Url implements TagFilterInterface
{
private $environmentManager;
/**
* Url constructor.
*
* @param EnvironmentInterface $environmentManager
*/
public function __construct(EnvironmentInterface $environmentManager)
{
$this->environmentManager = $environmentManager;
}
/**
* Apply the filter.
*
* @param string $text
* @return string
*/
public function filter(string $text) : string
{
$uri = rtrim($this->environmentManager->getRequestUri(), '/');
return str_replace('#Url#', $uri, $text);
}
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemMetaListByFilesystem.sql
SELECT
fsm.`id_filesystem_meta`,
fsm.`fk_filesystem`,
fsm.`meta_key`,
fsm.`meta_data`,
fsm.`date_created`,
fsm.`date_modified`
FROM
`webhemi_filesystem_meta` AS fsm
WHERE
fsm.`fk_filesystem` = :idFilesystem
ORDER BY
fsm.`meta_key`
LIMIT
:limit
OFFSET
:offset
<file_sep>/src/WebHemi/Data/Entity/FilesystemEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class FilesystemEntity
*/
class FilesystemEntity extends AbstractEntity
{
public const TYPE_DOCUMENT = 'document';
public const TYPE_BINARY = 'binary';
public const TYPE_DIRECTORY = 'directory';
public const TYPE_SYMLINK = 'symlink';
/**
* @var array
*/
protected $container = [
'id_filesystem' => null,
'fk_application' => null,
'fk_category' => null,
'fk_parent_node' => null,
'fk_filesystem_document' => null,
'fk_filesystem_file' => null,
'fk_filesystem_directory' => null,
'fk_filesystem_link' => null,
'path' => null,
'basename' => null,
'uri' => null,
'title' => null,
'description' => null,
'is_hidden' => null,
'is_read_only' => null,
'is_deleted' => null,
'date_created' => null,
'date_modified' => null,
'date_published' => null,
];
/**
* @return null|string
*/
public function getType() : ? string
{
if (!empty($this->container['fk_filesystem_file'])) {
return self::TYPE_BINARY;
}
if (!empty($this->container['fk_filesystem_directory'])) {
return self::TYPE_DIRECTORY;
}
if (!empty($this->container['fk_filesystem_link'])) {
return self::TYPE_SYMLINK;
}
return self::TYPE_DOCUMENT;
}
/**
* @param int $identifier
* @return FilesystemEntity
*/
public function setFilesystemId(int $identifier) : FilesystemEntity
{
$this->container['id_filesystem'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemId() : ? int
{
return !is_null($this->container['id_filesystem'])
? (int) $this->container['id_filesystem']
: null;
}
/**
* @param int $applicationIdentifier
* @return FilesystemEntity
*/
public function setApplicationId(int $applicationIdentifier) : FilesystemEntity
{
$this->container['fk_application'] = $applicationIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getApplicationId() : ? int
{
return !is_null($this->container['fk_application'])
? (int) $this->container['fk_application']
: null;
}
/**
* @param int $categoryIdentifier
* @return FilesystemEntity
*/
public function setCategoryId(int $categoryIdentifier) : FilesystemEntity
{
$this->container['fk_category'] = $categoryIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getCategoryId() : ? int
{
return !is_null($this->container['fk_category'])
? (int) $this->container['fk_category']
: null;
}
/**
* @param null|int $parentNodeIdentifier
* @return FilesystemEntity
*/
public function setParentNodeId(? int $parentNodeIdentifier) : FilesystemEntity
{
$this->container['fk_parent_node'] = $parentNodeIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getParentNodeId() : ? int
{
return !is_null($this->container['fk_parent_node'])
? (int) $this->container['fk_parent_node']
: null;
}
/**
* @param null|int $documentIdentifier
* @return FilesystemEntity
*/
public function setFilesystemDocumentId(? int $documentIdentifier) : FilesystemEntity
{
$this->container['fk_filesystem_document'] = $documentIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemDocumentId() : ? int
{
return !is_null($this->container['fk_filesystem_document'])
? (int) $this->container['fk_filesystem_document']
: null;
}
/**
* @param null|int $fileIdentifier
* @return FilesystemEntity
*/
public function setFilesystemFileId(? int $fileIdentifier) : FilesystemEntity
{
$this->container['fk_filesystem_file'] = $fileIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemFileId() : ? int
{
return !is_null($this->container['fk_filesystem_file'])
? (int) $this->container['fk_filesystem_file']
: null;
}
/**
* @param null|int $directoryIdentifier
* @return FilesystemEntity
*/
public function setFilesystemDirectoryId(? int $directoryIdentifier) : FilesystemEntity
{
$this->container['fk_filesystem_directory'] = $directoryIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemDirectoryId() : ? int
{
return !is_null($this->container['fk_filesystem_directory'])
? (int) $this->container['fk_filesystem_directory']
: null;
}
/**
* @param null|int $linkIdentifier
* @return FilesystemEntity
*/
public function setFilesystemLinkId(? int $linkIdentifier) : FilesystemEntity
{
$this->container['fk_filesystem_link'] = $linkIdentifier;
return $this;
}
/**
* @return int|null
*/
public function getFilesystemLinkId() : ? int
{
return !is_null($this->container['fk_filesystem_link'])
? (int) $this->container['fk_filesystem_link']
: null;
}
/**
* @param string $path
* @return FilesystemEntity
*/
public function setPath(string $path) : FilesystemEntity
{
$this->container['path'] = $path;
return $this;
}
/**
* @return null|string
*/
public function getPath() : ? string
{
return $this->container['path'];
}
/**
* @param string $baseName
* @return FilesystemEntity
*/
public function setBaseName(string $baseName) : FilesystemEntity
{
$this->container['basename'] = $baseName;
return $this;
}
/**
* @return null|string
*/
public function getBaseName() : ? string
{
return $this->container['basename'];
}
/**
* @param string $uri
* @return FilesystemEntity
*/
public function setUri(string $uri) : FilesystemEntity
{
$this->container['uri'] = $uri;
return $this;
}
/**
* @return null|string
*/
public function getUri() : ? string
{
return $this->container['uri'];
}
/**
* @param string $title
* @return FilesystemEntity
*/
public function setTitle(string $title) : FilesystemEntity
{
$this->container['title'] = $title;
return $this;
}
/**
* @return null|string
*/
public function getTitle() : ? string
{
return $this->container['title'];
}
/**
* @param string $description
* @return FilesystemEntity
*/
public function setDescription(string $description) : FilesystemEntity
{
$this->container['description'] = $description;
return $this;
}
/**
* @return null|string
*/
public function getDescription() : ? string
{
return $this->container['description'];
}
/**
* @param bool $isHidden
* @return FilesystemEntity
*/
public function setIsHidden(bool $isHidden) : FilesystemEntity
{
$this->container['is_hidden'] = $isHidden ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsHidden() : bool
{
return !empty($this->container['is_hidden']);
}
/**
* @param bool $isReadonly
* @return FilesystemEntity
*/
public function setIsReadOnly(bool $isReadonly) : FilesystemEntity
{
$this->container['is_read_only'] = $isReadonly ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsReadOnly() : bool
{
return !empty($this->container['is_read_only']);
}
/**
* @param bool $isDeleted
* @return FilesystemEntity
*/
public function setIsDeleted(bool $isDeleted) : FilesystemEntity
{
$this->container['is_deleted'] = $isDeleted ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsDeleted() : bool
{
return !empty($this->container['is_deleted']);
}
/**
* @param DateTime $dateTime
* @return FilesystemEntity
*/
public function setDateCreated(DateTime $dateTime) : FilesystemEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return FilesystemEntity
*/
public function setDateModified(DateTime $dateTime) : FilesystemEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
/**
* @param DateTime $dateTime
* @return FilesystemEntity
*/
public function setDatePublished(DateTime $dateTime) : FilesystemEntity
{
$this->container['date_published'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDatePublished() : ? DateTime
{
return !empty($this->container['date_published'])
? new DateTime($this->container['date_published'])
: null;
}
}
<file_sep>/src/WebHemi/Data/Driver/PDO/SQLite/DriverAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Driver\PDO\SQLite;
use PDO;
use WebHemi\Data\Driver\DriverInterface;
/**
* Class DriverAdapter.
*
* Extends PDO and implements the DriverInterface, so the Dependency Manager can reference it.
*/
class DriverAdapter extends PDO implements DriverInterface
{
}
<file_sep>/src/WebHemi/Parser/ServiceAdapter/Parsedown/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Parser\ServiceAdapter\Parsedown;
use Parsedown;
use WebHemi\Parser\ServiceInterface;
/**
* Class ServiceAdapter
*
* @codeCoverageIgnore - no need to test external library
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var Parsedown
*/
private $adapter;
/**
* ServiceAdapter constructor.
*/
public function __construct()
{
$this->adapter = new Parsedown();
}
/**
* Parses the input.
*
* @param string $text
* @return string
*/
public function parse(string $text) : string
{
return $this->adapter->text($text);
}
}
<file_sep>/src/WebHemi/Configuration/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Configuration;
use InvalidArgumentException;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param array $config
*/
public function __construct(array $config);
/**
* Checks whether the key-path does exist or not.
*
* @param string $path
* @return bool
*/
public function has(string $path) : bool;
/**
* Returns the configuration data for a specific key.
*
* @param string $path
* @throws InvalidArgumentException
* @return array
*/
public function getData(string $path) : array;
/**
* Returns the configuration instance for a specific key. Also add the possibility to merge additional information
* into it.
*
* @param string $path
* @throws InvalidArgumentException
* @return ServiceInterface
*/
public function getConfig(string $path) : ServiceInterface;
/**
* Returns the stored raw config array.
*
* @return array
*/
public function toArray() : array;
}
<file_sep>/src/WebHemi/Data/Entity/EntitySet.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use ArrayAccess;
use InvalidArgumentException;
use Iterator;
/**
* Class EntitySet.
*
* We have some strictness additions to the original ArrayAccess and Iterator interfaces.
* A) The offset must be Integer.
* B) The value must be an object that implements the EntityInterface.
*/
class EntitySet implements ArrayAccess, Iterator
{
/**
* @var array
*/
private $container = [];
/**
* Checks whether an offset exists.
*
* @param int $offset
* @throws InvalidArgumentException
* @return bool
*/
public function offsetExists($offset) : bool
{
if (!is_int($offset)) {
throw new InvalidArgumentException(
sprintf(__METHOD__.' requires parameter 1 to be integer, %s given.', gettype($offset)),
1000
);
}
return isset($this->container[$offset]);
}
/**
* Returns the value at an offset.
*
* @param int $offset
* @throws InvalidArgumentException
* @return null|EntityInterface
*/
public function offsetGet($offset)
{
if (!is_int($offset)) {
throw new InvalidArgumentException(
sprintf(__METHOD__.' requires parameter 1 to be integer, %s given.', gettype($offset)),
1001
);
}
return $this->container[$offset] ?? null;
}
/**
* Sets a value for an offset. It appends it if offset is Null.
*
* @param null|int $offset
* @param EntityInterface $value
* @throws InvalidArgumentException
*/
public function offsetSet($offset, $value) : void
{
if (is_null($offset)) {
$offset = empty($this->container) ? 0 : max(array_keys($this->container)) + 1;
}
if (!is_int($offset)) {
throw new InvalidArgumentException(
sprintf(__METHOD__.' requires parameter 1 to be integer, %s given.', gettype($offset)),
1002
);
}
if (!$value instanceof EntityInterface) {
$valueType = is_object($value) ? get_class($value) : gettype($value);
throw new InvalidArgumentException(
sprintf(__METHOD__.' requires parameter 2 to be an instance of EntityInterface, %s given.', $valueType),
1003
);
}
$this->container[$offset] = $value;
}
/**
* Deletes a record from the container at an offset. It will not reorder the container.
*
* @param mixed $offset
* @throws InvalidArgumentException
*/
public function offsetUnset($offset) : void
{
if (!is_int($offset)) {
throw new InvalidArgumentException(
sprintf(__METHOD__.' requires parameter 1 to be integer, %s given.', gettype($offset)),
1004
);
}
if ($this->offsetExists($offset)) {
unset($this->container[$offset]);
}
}
/**
* Rewinds the Iterator to the first element.
*/
public function rewind() : void
{
reset($this->container);
}
/**
* Returns the current element.
*
* @return mixed
*/
public function current()
{
return current($this->container);
}
/**
* Returns the key of the current element.
*
* @return int|mixed|null|string
*/
public function key()
{
return key($this->container);
}
/**
* Moves forward to next element.
*/
public function next() : void
{
next($this->container);
}
/**
* Checks if current position is valid.
*
* @return bool
*/
public function valid() : bool
{
return key($this->container) !== null;
}
/**
* Return the raw container
*
* @return array
*/
public function toArray() : array
{
return $this->container;
}
/**
* Merges another EntitySet into the current container.
*
* @param EntitySet $entitySet
*/
public function merge(EntitySet $entitySet) : void
{
$this->container = array_merge($this->container, $entitySet->toArray());
}
}
<file_sep>/src/WebHemi/MiddlewarePipeline/ServiceAdapter/AbstractAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\MiddlewarePipeline\ServiceAdapter;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Middleware\MiddlewareInterface;
use WebHemi\MiddlewarePipeline\ServiceInterface;
/**
* Class AbstractAdapter.
*/
abstract class AbstractAdapter implements ServiceInterface
{
/**
* @var ConfigurationInterface
*/
protected $configuration;
/**
* @var array
*/
protected $priorityList;
/**
* @var array
*/
protected $pipelineList;
/**
* @var array
*/
protected $keyMiddlewareList;
/**
* @var int
*/
protected $index;
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$this->configuration = $configuration->getConfig('middleware_pipeline');
$this->initProperties();
$this->buildPipeline();
}
/**
* Initialize the listing properties (priorityList, pipelineList, keyMiddlewareList).
*
* @return void
*/
abstract protected function initProperties() : void;
/**
* Add middleware definitions to the pipeline.
*
* @param string $moduleName
* @return void
*/
protected function buildPipeline(string $moduleName = 'Global') : void
{
$pipelineConfig = $this->configuration->getData($moduleName);
foreach ($pipelineConfig as $middlewareData) {
if (!isset($middlewareData['priority'])) {
$middlewareData['priority'] = 50;
}
$this->queueMiddleware($middlewareData['service'], $middlewareData['priority']);
}
}
/**
* Checks the given class against Middleware Criteria.
*
* @param string $middleWareClass
* @throws RuntimeException
* @return bool
*/
protected function checkMiddleware(string $middleWareClass) : bool
{
if (isset($this->index)) {
throw new RuntimeException('You are forbidden to add new middleware after start.', 1000);
}
if (in_array($middleWareClass, $this->pipelineList)) {
throw new RuntimeException(
sprintf('The service "%s" is already added to the pipeline.', $middleWareClass),
1001
);
}
if (class_exists($middleWareClass)
&& !array_key_exists(MiddlewareInterface::class, class_implements($middleWareClass))
) {
throw new RuntimeException(
sprintf('The service "%s" is not a middleware.', $middleWareClass),
1002
);
}
return true;
}
/**
* Adds module specific pipeline.
*
* @param string $moduleName
* @return ServiceInterface
*/
public function addModulePipeLine(string $moduleName) : ServiceInterface
{
$this->buildPipeline($moduleName);
return $this;
}
/**
* Adds a new middleware to the pipeline queue.
*
* @param string $middleWareClass
* @param int $priority
* @throws RuntimeException
* @return ServiceInterface
*/
public function queueMiddleware(string $middleWareClass, int $priority = 50) : ServiceInterface
{
$this->checkMiddleware($middleWareClass);
if (in_array($middleWareClass, $this->keyMiddlewareList)) {
// Don't throw error if the user defines the default middleware classes.
return $this;
}
if ($priority === 0 || $priority == 100) {
$priority++;
}
if (!isset($this->priorityList[$priority])) {
$this->priorityList[$priority] = [];
}
if (!in_array($middleWareClass, $this->pipelineList)) {
$this->priorityList[$priority][] = $middleWareClass;
$this->pipelineList[] = $middleWareClass;
}
return $this;
}
/**
* Sorts the pipeline elements according to the priority.
*
* @return void
*/
protected function sortPipeline() : void
{
ksort($this->priorityList);
$this->pipelineList = [];
foreach ($this->priorityList as $middlewareList) {
$this->pipelineList = array_merge($this->pipelineList, $middlewareList);
}
}
/**
* Starts the pipeline.
*
* @return null|string
*/
public function start() : ? string
{
$this->index = 0;
$this->sortPipeline();
return $this->next();
}
/**
* Gets next element from the pipeline.
*
* @return null|string
*/
public function next() : ? string
{
if (!isset($this->index)) {
throw new RuntimeException('Unable to get the next element until the pipeline is not started.', 1003);
}
return isset($this->pipelineList[$this->index]) ? $this->pipelineList[$this->index++] : null;
}
/**
* Gets the full pipeline list.
*
* @return array
*/
public function getPipelineList() : array
{
return $this->pipelineList;
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyStorage.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Data\Entity\EntityInterface as DataEntityInterface;
use WebHemi\Data\Storage\AbstractStorage as AbstractDataStorage;
/**
* Class EmptyStorage.
*
*/
class EmptyStorage extends AbstractDataStorage
{
/** @var string */
protected $dataGroup;
/** @var string */
protected $idKey;
/**
* Populates an entity with storage data.
*
* @param DataEntityInterface $entity
* @param array $data
* @return void
*/
protected function populateEntity(DataEntityInterface &$entity, array $data) : void
{
foreach ($data as $key => $value) {
$method = 'set' . ucfirst($key);
$entity->{$method}($value);
}
}
/**
* Get data from an entity.
*
* @param DataEntityInterface $entity
* @return array
*/
protected function getEntityData(DataEntityInterface $entity) : array
{
/** @var EmptyEntity $entity */
return $entity->storage;
}
/**
* Sets id key fir the storage. Only for unit test.
*
* @param string $idKey
*
* @return EmptyStorage
*/
public function setIdKey($idKey)
{
$this->idKey = $idKey;
return $this;
}
/**
* Sets data group for the storage. Only for unit test.
*
* @param string $dataGroup
*
* @return EmptyStorage
*/
public function setDataGroup($dataGroup)
{
$this->dataGroup = $dataGroup;
return $this;
}
}
<file_sep>/src/WebHemi/Form/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Form\ServiceAdapter\Base;
use JsonSerializable;
use RuntimeException;
use InvalidArgumentException;
use WebHemi\Form\ElementInterface;
use WebHemi\Form\ServiceInterface;
use WebHemi\StringLib;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface, JsonSerializable
{
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $action;
/**
* @var string
*/
private $method;
/**
* @var array
*/
private $formElements = [];
/**
* ServiceAdapter constructor.
*
* @param string $name
* @param string $action
* @param string $method
*/
public function __construct(string $name = '', string $action = '', string $method = 'POST')
{
$this->name = $name;
$this->action = $action;
$this->method = $method;
}
/**
* Initializes the form if it didn't happen in the constructor. (Used mostly in presets).
*
* @param string $name
* @param string $action
* @param string $method
* @throws RuntimeException
* @return ServiceInterface
*/
public function initialize(string $name, string $action, string $method = 'POST') : ServiceInterface
{
if (!empty($this->name) || !empty($this->action)) {
throw new RuntimeException('The form had been already initialized!', 1000);
}
$this->name = $name;
$this->action = $action;
$this->method = $method;
return $this;
}
/**
* Gets form name.
*
* @return string
*/
public function getName() : string
{
return $this->name;
}
/**
* Gets form action.
*
* @return string
*/
public function getAction() : string
{
return $this->action;
}
/**
* Gets form method.
*
* @return string
*/
public function getMethod() : string
{
return $this->method;
}
/**
* Adds an element to the form.
*
* @param ElementInterface $formElement
* @throws InvalidArgumentException
* @return ServiceInterface
*/
public function addElement(ElementInterface $formElement) : ServiceInterface
{
$elementName = $formElement->getName();
$elementName = $this->name.'['.$elementName.']';
if (isset($this->formElements[$elementName])) {
throw new InvalidArgumentException(
sprintf('The element "%s" in field list is ambiguous.', $elementName),
1001
);
}
$formElement->setName($elementName);
$this->formElements[$elementName] = $formElement;
return $this;
}
/**
* Returns an element
*
* @param string $elementName
* @throws InvalidArgumentException
* @return ElementInterface
*/
public function getElement(string $elementName) : ElementInterface
{
$elementNames = array_keys($this->formElements);
$elementName = StringLib::convertNonAlphanumericToUnderscore($elementName);
$matchingElementNames = preg_grep('/.*\['.$elementName.'\]/', $elementNames);
if (empty($matchingElementNames)) {
throw new InvalidArgumentException(
sprintf('The element "%s" does not exist in this form.', $elementName),
1002
);
}
return $this->formElements[current($matchingElementNames)];
}
/**
* Returns all the elements assigned.
*
* @return ElementInterface[]
*/
public function getElements() : array
{
return $this->formElements;
}
/**
* Loads data into the form.
*
* @param array $data
* @return ServiceInterface
*/
public function loadData(array $data) : ServiceInterface
{
$formData = $data[$this->name] ?? [];
foreach ($formData as $elementName => $elementValue) {
$fullName = $this->name.'['.$elementName.']';
/**
* @var ElementInterface $formElement
*/
$formElement = $this->formElements[$fullName] ?? null;
if ($formElement) {
if (!is_array($elementValue)) {
$elementValue = [$elementValue];
}
$formElement->setValues($elementValue);
}
}
return $this;
}
/**
* Validates the form.
*
* @return bool
*/
public function validate() : bool
{
$isValid = true;
/**
* @var string $index
* @var ElementInterface $formElement
*/
foreach ($this->formElements as $index => $formElement) {
$this->formElements[$index] = $formElement->validate();
if (!empty($formElement->getErrors())) {
$isValid = false;
}
}
return $isValid;
}
/**
* Defines the data which are presented during the json serialization.
*
* @return array
*/
public function jsonSerialize() : array
{
$formData = [
'name' => $this->name,
'action' => $this->action,
'method' => $this->method,
'data' => [],
'errors' => []
];
/**
* @var string $elementName
* @var ElementInterface $formElement
*/
foreach ($this->formElements as $formElement) {
$formData['data'][$formElement->getId()] = $formElement->getValues();
$errors = $formElement->getErrors();
if (!empty($errors)) {
$formData['errors'][$formElement->getId()] = $errors;
}
}
return $formData;
}
}
<file_sep>/tests/WebHemiTest/TestService/TestTrueValidator.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\Validator\ValidatorInterface;
/**
* Class TestTrueValidator.
*/
class TestTrueValidator implements ValidatorInterface
{
private $data;
/**
* Validates data.
*
* @param array $values
* @return boolean
*/
public function validate(array $values) : bool
{
$this->data = $values;
return true;
}
/**
* Retrieve valid data.
*
* @return array
*/
public function getValidData() : array
{
return $this->data;
}
/**
* Gets error from validation.
*
* @return array
*/
public function getErrors() : array
{
return [];
}
}
<file_sep>/tests/WebHemiTest/TestService/EmptyI18nService.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\TestService;
use WebHemi\I18n\ServiceAdapter\Base\ServiceAdapter as I18nService;
/**
* Class EmptyI18nService
*/
class EmptyI18nService extends I18nService
{
/**
* Sets the locale.
*
* @param string $locale
* @return I18nService
*/
public function setLocale(string $locale) : I18nService
{
$matches = [];
if (preg_match('/^(?P<language>[a-z]+)_(?P<territory>[A-Z]+)(?:\.(?P<codeSet>.*))?/', $locale, $matches)) {
$this->language = $matches['language'];
$this->territory = $matches['territory'];
$this->codeSet = $matches['codeSet'] ?? 'utf8';
$this->locale = $locale;
}
return $this;
}
/**
* Sets the time zone.
*
* @param string $timeZone
* @return I18nService
*/
public function setTimeZone(string $timeZone) : I18nService
{
$this->timeZone = $timeZone;
return $this;
}
}
<file_sep>/src/WebHemi/Middleware/Action/Website/Directory/TagAction.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Middleware\Action\Website\Directory;
use RuntimeException;
use WebHemi\Data\Entity;
use WebHemi\Middleware\Action\Website\IndexAction;
/**
* Class TagAction.
*/
class TagAction extends IndexAction
{
/**
* @var string
*/
protected $templateName = 'website-post-list';
/**
* Gets template map name or template file path.
*
* @return string
*/
public function getTemplateName() : string
{
return $this->templateName;
}
/**
* Gets template data.
*
* @return array
*/
public function getTemplateData() : array
{
$blogPosts = [];
$parameters = $this->getRoutingParameters();
/**
* @var string $tagName
*/
$tagName = $parameters['basename'] ?? null;
if ($parameters['path'] == '/' || empty($tagName)) {
throw new RuntimeException('Forbidden', 403);
}
/**
* @var Entity\ApplicationEntity $applicationEntity
*/
$applicationEntity = $this->getApplicationStorage()
->getApplicationByName($this->environmentManager->getSelectedApplication());
/**
* @var Entity\FilesystemTagEntity $tagEntity
*/
$tagEntity = $this->getFilesystemStorage()
->getFilesystemTagByApplicationAndName(
(int) $applicationEntity->getApplicationId(),
$tagName
);
if (!$tagEntity instanceof Entity\FilesystemTagEntity) {
throw new RuntimeException('Not Found', 404);
}
/**
* @var Entity\EntitySet $publications
*/
$publications = $this->getFilesystemStorage()
->getFilesystemPublishedDocumentListByTag(
(int) $applicationEntity->getApplicationId(),
(int) $tagEntity->getFilesystemTagId()
);
if (empty($publications)) {
$this->templateName = 'website-post-list-empty';
}
/**
* @var Entity\FilesystemPublishedDocumentEntity $publishedDocumentEntity
*/
foreach ($publications as $publishedDocumentEntity) {
$blogPosts[] = $this->getBlobPostData($applicationEntity, $publishedDocumentEntity);
}
return [
'page' => [
'title' => $tagEntity->getTitle(),
'name' => $tagEntity->getName(),
'description' => $tagEntity->getDescription(),
'type' => 'Tags',
],
'activeMenu' => $tagName,
'application' => $this->getApplicationData($applicationEntity),
'blogPosts' => $blogPosts,
];
}
}
<file_sep>/src/WebHemi/Http/ClientInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Http;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
/**
* Interface ClientInterface.
*/
interface ClientInterface
{
/**
* Get data.
*
* @param string $url
* @param array $data
* @return PsrResponseInterface
*/
public function get(string $url, array $data) : PsrResponseInterface;
/**
* Posts data.
*
* @param string $url
* @param array $data
* @return PsrResponseInterface
*/
public function post(string $url, array $data) : PsrResponseInterface;
}
<file_sep>/tests/WebHemiTest/Renderer/Filter/TagparserFilterTest.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
namespace WebHemiTest\Renderer\Filter;
use PHPUnit\Framework\TestCase;
use WebHemi\Configuration\ServiceAdapter\Base\ServiceAdapter as Config;
use WebHemi\DependencyInjection\ServiceAdapter\Symfony\ServiceAdapter as DependencyInjectionAdapter;
use WebHemi\Environment;
use WebHemi\Renderer;
use WebHemi\Renderer\Filter\TagParserFilter;
use WebHemi\Renderer\Filter\Tags\Url;
use WebHemiTest\TestService\EmptyEnvironmentManager;
/**
* Class TagparserFilterTest.
*/
class TagparserFilterTest extends TestCase
{
/** @var EmptyEnvironmentManager */
protected $environmentManager;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*/
public function setUp()
{
parent::setUp();
$configData = [
'applications' => [],
'dependencies' => [
'Global' => [
Environment\ServiceInterface::class => [
'class' => EmptyEnvironmentManager::class,
],
Renderer\Filter\Tags\Url::class => [
'arguments' => [
Environment\ServiceInterface::class
],
'shared' => true,
],
]
]
];
$config = new Config($configData);
$server = [
'HTTP_HOST' => 'unittest.dev',
'SERVER_NAME' => 'unittest.dev',
'REQUEST_URI' => '/',
'QUERY_STRING' => '',
];
$this->environmentManager = new EmptyEnvironmentManager($config, [], [], $server, [], []);
}
/**
* Test the filter class.
*/
public function testFilter()
{
$this->environmentManager->setRequestUri('/some/folders/for/test.html');
$tagFilter = new Url($this->environmentManager);
$filter = new TagparserFilter($tagFilter);
$url = '/some/folders/for/test.html';
$input = 'Lorem ipsum dolor #sit# amet consectetur adipiscing #Url#. #Sed# ut auctor mauris.';
$expectedResult = 'Lorem ipsum dolor #sit# amet consectetur adipiscing '.$url.'. #Sed# ut auctor mauris.';
$actualResult = $filter($input);
$this->assertSame($expectedResult, $actualResult);
}
}
<file_sep>/src/WebHemi/Logger/ServiceInterface.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Logger;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
/**
* Interface ServiceInterface.
*/
interface ServiceInterface
{
/**
* ServiceInterface constructor.
*
* @param ConfigurationInterface $configuration
* @param string $section
*/
public function __construct(ConfigurationInterface $configuration, string $section);
/**
* Logs with an arbitrary level.
*
* @param mixed $level Either the numeric level (0-7) or the name of the level (debug ... emergency)
* @param string $message
* @param array $context
* @return void
*/
public function log($level, string $message, array $context = []) : void;
}
<file_sep>/src/WebHemi/Data/Query/MySQL/statements/getFilesystemDocumentById.sql
SELECT
fsd.`id_filesystem_document`,
fsd.`fk_parent_revision`,
fsd.`fk_author`,
fsd.`content_revision`,
fsd.`content_lead`,
fsd.`content_body`,
fsd.`date_created`,
fsd.`date_modified`
FROM
`webhemi_filesystem_document` AS fsd
WHERE
fsd.`id_filesystem_document` = :idDocument
<file_sep>/src/WebHemi/Acl/ServiceAdapter/AbstractServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Acl\ServiceAdapter;
use WebHemi\Acl;
use WebHemi\Data\Entity\PolicyEntity;
use WebHemi\Data\Entity\ResourceEntity;
use WebHemi\Data\Entity\ApplicationEntity;
use WebHemi\Data\Entity\UserEntity;
use WebHemi\Data\Storage\PolicyStorage;
use WebHemi\Data\Storage\UserStorage;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
/**
* Class AbstractServiceAdapter.
*/
abstract class AbstractServiceAdapter implements Acl\ServiceInterface
{
/**
* @var EnvironmentInterface
*/
protected $environment;
/**
* @var UserStorage
*/
protected $userStorage;
/**
* @var PolicyStorage
*/
protected $policyStorage;
/**
* ServiceAdapter constructor.
*
* @param EnvironmentInterface $environment
* @param UserStorage $userStorage
* @param PolicyStorage $policyStorage
*/
public function __construct(
EnvironmentInterface $environment,
UserStorage $userStorage,
PolicyStorage $policyStorage
) {
$this->environment = $environment;
$this->userStorage = $userStorage;
$this->policyStorage = $policyStorage;
}
/**
* Checks if a User can access to a Resource in an Application
*
* @param UserEntity $userEntity
* @param ResourceEntity|null $resourceEntity
* @param ApplicationEntity|null $applicationEntity
* @return bool
*/
abstract public function isAllowed(
UserEntity $userEntity,
? ResourceEntity $resourceEntity = null,
? ApplicationEntity $applicationEntity = null
) : bool;
/**
* Checks a given policy against a resource, application and method.
*
* The user has access when the user or the user's group has a policy which:
* - is connected to the current resource OR any resource AND
* - is connected to the current application OR any application AND
* - allows the current request method.
*
* @param PolicyEntity $policyEntity
* @param null|ResourceEntity $resourceEntity
* @param null|ApplicationEntity $applicationEntity
* @param null|string $method
* @return bool
*/
protected function isPolicyAllowed(
PolicyEntity $policyEntity,
? ResourceEntity $resourceEntity = null,
? ApplicationEntity $applicationEntity = null,
? string $method = null
) : bool {
return $this->isResourceAllowed($policyEntity, $resourceEntity)
&& $this->isApplicationAllowed($policyEntity, $applicationEntity)
&& $this->isRequestMethodAllowed($policyEntity, $method);
}
/**
* Checks whether the given resource is allowed for the given policy.
*
* @param PolicyEntity $policyEntity
* @param ResourceEntity|null $resourceEntity
* @return bool
*/
private function isResourceAllowed(
PolicyEntity $policyEntity,
? ResourceEntity $resourceEntity = null
) : bool {
$policyResourceId = $policyEntity->getResourceId();
$resourceId = $resourceEntity ? $resourceEntity->getResourceId() : null;
return is_null($policyResourceId) || $policyResourceId === $resourceId;
}
/**
* Checks whether the given application is allowed for the given policy.
*
* @param PolicyEntity $policyEntity
* @param null|ApplicationEntity|null $applicationEntity
* @return bool
*/
private function isApplicationAllowed(
PolicyEntity $policyEntity,
? ApplicationEntity $applicationEntity = null
) : bool {
$policyApplicationId = $policyEntity->getApplicationId();
$applicationId = $applicationEntity ? $applicationEntity->getApplicationId() : null;
return is_null($policyApplicationId) || $policyApplicationId === $applicationId;
}
/**
* Checks whether the request method is allowed for the given policy.
*
* @param PolicyEntity $policyEntity
* @param null|string $method
* @return bool
*/
private function isRequestMethodAllowed(PolicyEntity $policyEntity, ? string $method = null) : bool
{
$policyRequestMethod = $policyEntity->getMethod();
$requestMethod = $method ?? $this->environment->getRequestMethod();
$allowRequestMethod = is_null($policyRequestMethod) || $policyRequestMethod === $requestMethod;
return $allowRequestMethod;
}
}
<file_sep>/src/WebHemi/Ftp/ServiceAdapter/AbstractServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Ftp\ServiceAdapter;
use RuntimeException;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Ftp\ServiceInterface;
/**
* Class AbstractServiceAdapter
*/
abstract class AbstractServiceAdapter implements ServiceInterface
{
/**
* @var string
*/
protected $localPath = __DIR__;
/**
* @var array
*/
protected $options = [];
/**
* ServiceAdapter constructor.
*
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$this->setOptions($configuration->getData('ftp'));
}
/**
* Connect and login to remote host.
*
* @return ServiceInterface
*/
abstract public function connect() : ServiceInterface;
/**
* Disconnect from remote host.
*
* @return ServiceInterface
*/
abstract public function disconnect() : ServiceInterface;
/**
* Sets an option data.
*
* @param string $key
* @param mixed $value
* @return ServiceInterface
*/
public function setOption(string $key, $value) : ServiceInterface
{
$this->options[$key] = $value;
return $this;
}
/**
* Sets a group of options.
*
* @param array $options
* @return ServiceInterface
*/
public function setOptions(array $options) : ServiceInterface
{
$this->options = array_merge($this->options, $options);
return $this;
}
/**
* Gets a specific option data.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function getOption(string $key, $default = null)
{
return $this->options[$key] ?? $default;
}
/**
* Toggles connection security level.
*
* @param bool $state
* @return ServiceInterface
*/
abstract public function setSecureConnection(bool $state) : ServiceInterface;
/**
* Toggles connection passive mode.
*
* @param bool $state
* @return ServiceInterface
*/
abstract public function setPassiveMode(bool $state) : ServiceInterface;
/**
* Sets remote path.
*
* @param string $path
* @return ServiceInterface
*/
abstract public function setRemotePath(string $path) : ServiceInterface;
/**
* Gets remote path.
*
* @return string
*/
abstract public function getRemotePath() : string;
/**
* Sets local path.
*
* @param string $path
* @return ServiceInterface
*/
public function setLocalPath(string $path) : ServiceInterface
{
// if it's not an absolute path, we take it relative to the current folder
if (strpos($path, '/') !== 0) {
$path = __DIR__.'/'.$path;
}
if (!realpath($path) || !is_dir($path)) {
throw new RuntimeException(sprintf('No such directory: %s', $path), 1003);
}
// @codeCoverageIgnoreStart
// docker is root. Can't test these cases...
if (!is_readable($path)) {
throw new RuntimeException(sprintf('Cannot read directory: %s; Permission denied.', $path), 1004);
}
if (!is_writable($path)) {
throw new RuntimeException(
sprintf('Cannot write data into directory: %s; Permission denied.', $path),
1005
);
}
// @codeCoverageIgnoreEnd
$this->localPath = $path;
return $this;
}
/**
* Checks local file, and generates new unique name if necessary.
*
* @param string $localFileName
* @param bool $forceUnique
* @throws RuntimeException
*/
protected function checkLocalFile(string&$localFileName, bool $forceUnique = false) : void
{
$pathInfo = pathinfo($localFileName);
if ($pathInfo['dirname'] != '.') {
$this->setLocalPath($pathInfo['dirname']);
}
$localFileName = $pathInfo['basename'];
if (!$forceUnique) {
return;
}
$variant = 0;
$fileName = $pathInfo['filename'];
$extension = $pathInfo['extension'];
while (file_exists($this->localPath.'/'.$fileName.'.'.$extension) && $variant++ < 20) {
$fileName = $pathInfo['filename'].'.('.($variant).')';
}
if (preg_match('/\.\(20\)$/', $fileName)) {
throw new RuntimeException(
sprintf('Too many similar files in folder %s, please cleanup first.', $this->localPath),
1009
);
}
$localFileName = $fileName.'.'.$extension;
}
/**
* Converts file rights string into octal value.
*
* @param string $permissions The UNIX-style permission string, e.g.: 'drwxr-xr-x'
* @return string
*/
protected function getOctalChmod(string $permissions) : string
{
$mode = 0;
$mapper = [
0 => [], // type like d as directory, l as link etc.
// Owner
1 => ['r' => 0400],
2 => ['w' => 0200],
3 => [
'x' => 0100,
's' => 04100,
'S' => 04000
],
// Group
4 => ['r' => 040],
5 => ['w' => 020],
6 => [
'x' => 010,
's' => 02010,
'S' => 02000
],
// World
7 => ['r' => 04],
8 => ['w' => 02],
9 => [
'x' => 01,
't' => 01001,
'T' => 01000
],
];
for ($i = 1; $i <= 9; $i++) {
$mode += $mapper[$i][$permissions[$i]] ?? 00;
}
return '0'.decoct($mode);
}
/**
* Check remote file name.
*
* @param string $remoteFileName
*/
abstract protected function checkRemoteFile(string&$remoteFileName) : void;
/**
* Gets local path.
*
* @return string
*/
public function getLocalPath() : string
{
return $this->localPath;
}
/**
* Lists remote path.
*
* @param null|string $path
* @param bool|null $changeToDirectory
* @return array
*/
abstract public function getRemoteFileList(? string $path, ? bool $changeToDirectory) : array;
/**
* Uploads file to remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $sourceFileName
* @param string $destinationFileName
* @param int $fileMode
* @return ServiceInterface
*/
abstract public function upload(
string $sourceFileName,
string $destinationFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface;
/**
* Downloads file from remote host.
*
* @see self::setRemotePath
* @see self::setLocalPath
*
* @param string $remoteFileName
* @param string $localFileName
* @param int $fileMode
* @return ServiceInterface
*/
abstract public function download(
string $remoteFileName,
string&$localFileName,
int $fileMode = self::FILE_MODE_BINARY
) : ServiceInterface;
/**
* Moves file on remote host.
*
* @param string $currentPath
* @param string $newPath
* @return ServiceInterface
*/
abstract public function moveRemoteFile(string $currentPath, string $newPath) : ServiceInterface;
/**
* Deletes file on remote host.
*
* @param string $path
* @return ServiceInterface
*/
abstract public function deleteRemoteFile(string $path) : ServiceInterface;
}
<file_sep>/src/WebHemi/Data/Entity/UserEntity.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Data\Entity;
use WebHemi\DateTime;
/**
* Class UserEntity
*/
class UserEntity extends AbstractEntity
{
/**
* @var array
*/
protected $container = [
'id_user' => null,
'username' => null,
'email' => null,
'password' => <PASSWORD>,
'hash' => null,
'is_active' => null,
'is_enabled' => null,
'date_created' => null,
'date_modified' => null,
];
/**
* @param int $identifier
* @return UserEntity
*/
public function setUserId(int $identifier) : UserEntity
{
$this->container['id_user'] = $identifier;
return $this;
}
/**
* @return int|null
*/
public function getUserId() : ? int
{
return !is_null($this->container['id_user'])
? (int) $this->container['id_user']
: null;
}
/**
* @param string $userName
* @return UserEntity
*/
public function setUserName(string $userName) : UserEntity
{
$this->container['username'] = $userName;
return $this;
}
/**
* @return null|string
*/
public function getUserName() : ? string
{
return $this->container['username'];
}
/**
* @param string $email
* @return UserEntity
*/
public function setEmail(string $email) : UserEntity
{
$this->container['email'] = $email;
return $this;
}
/**
* @return null|string
*/
public function getEmail() : ? string
{
return $this->container['email'];
}
/**
* @param string $password
* @return UserEntity
*/
public function setPassword(string $password) : UserEntity
{
$this->container['password'] = $password;
return $this;
}
/**
* @return null|string
*/
public function getPassword() : ? string
{
return $this->container['password'];
}
/**
* @param string $hash
* @return UserEntity
*/
public function setHash(string $hash) : UserEntity
{
$this->container['hash'] = $hash;
return $this;
}
/**
* @return null|string
*/
public function getHash() : ? string
{
return $this->container['hash'];
}
/**
* @param bool $isActive
* @return UserEntity
*/
public function setIsActive(bool $isActive) : UserEntity
{
$this->container['is_active'] = $isActive ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsActive() : bool
{
return !empty($this->container['is_active']);
}
/**
* @param bool $isEnabled
* @return UserEntity
*/
public function setIsEnabled(bool $isEnabled) : UserEntity
{
$this->container['is_enabled'] = $isEnabled ? 1 : 0;
return $this;
}
/**
* @return bool
*/
public function getIsEnabled() : bool
{
return !empty($this->container['is_enabled']);
}
/**
* @param DateTime $dateTime
* @return UserEntity
*/
public function setDateCreated(DateTime $dateTime) : UserEntity
{
$this->container['date_created'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateCreated() : ? DateTime
{
return !empty($this->container['date_created'])
? new DateTime($this->container['date_created'])
: null;
}
/**
* @param DateTime $dateTime
* @return UserEntity
*/
public function setDateModified(DateTime $dateTime) : UserEntity
{
$this->container['date_modified'] = $dateTime->format('Y-m-d H:i:s');
return $this;
}
/**
* @return null|DateTime
*/
public function getDateModified() : ? DateTime
{
return !empty($this->container['date_modified'])
? new DateTime($this->container['date_modified'])
: null;
}
}
<file_sep>/src/WebHemi/Validator/NotEmptyValidator.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Validator;
/**
* class NotEmptyValidator.
*/
class NotEmptyValidator implements ValidatorInterface
{
/**
* @var array
*/
private $errors;
/**
* @var array
*/
private $validData;
/**
* Validates data. Returns true when data is not empty.
*
* @param array $values
* @return bool
*/
public function validate(array $values) : bool
{
$isEmpty = true;
foreach ($values as $key => $data) {
if (is_string($data)) {
$data = trim($data);
}
if (!empty($data)) {
$isEmpty = false;
$this->validData[$key] = $data;
}
}
if ($isEmpty) {
$this->errors[] = 'This field is mandatory and cannot be empty';
return false;
}
return true;
}
/**
* Retrieve valid data.
*
* @return array
*/
public function getValidData() : array
{
return $this->validData;
}
/**
* Gets errors from validation.
*
* @return array
*/
public function getErrors() : array
{
return $this->errors;
}
}
<file_sep>/src/WebHemi/Renderer/Helper/DefinedHelper.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Renderer\Helper;
use WebHemi\Configuration\ServiceInterface as ConfigurationInterface;
use WebHemi\Environment\ServiceInterface as EnvironmentInterface;
use WebHemi\Renderer\HelperInterface;
use WebHemi\Renderer\Traits\GetSelectedThemeResourcePathTrait;
/**
* Class DefinedHelper.
*/
class DefinedHelper implements HelperInterface
{
/**
* @var string
*/
private $templateViewPath;
/**
* @var string
*/
private $defaultTemplateViewPath;
use GetSelectedThemeResourcePathTrait;
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getName() : string
{
return 'defined';
}
/**
* Should return the name of the helper.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDefinition() : string
{
return '{% if defined("templateFileName") %}';
}
/**
* Should return a description text.
*
* @return string
* @codeCoverageIgnore - plain text
*/
public static function getDescription() : string
{
return 'Checks if the given filepath exists in the template\'s path. Use @WebHemi for the default theme and '
. '@Theme for the actual (custom) theme.';
}
/**
* Gets helper options for the render.
*
* @return array
* @codeCoverageIgnore - empty array
*/
public static function getOptions() : array
{
return [];
}
/**
* DefinedHelper constructor.
*
* @param ConfigurationInterface $configuration
* @param EnvironmentInterface $environmentManager
*/
public function __construct(ConfigurationInterface $configuration, EnvironmentInterface $environmentManager)
{
$documentRoot = $environmentManager->getDocumentRoot();
$selectedTheme = $environmentManager->getSelectedTheme();
$selectedThemeResourcePath = $this->getSelectedThemeResourcePath(
$selectedTheme,
$configuration,
$environmentManager
);
$this->defaultTemplateViewPath = $documentRoot.EnvironmentInterface::DEFAULT_THEME_RESOURCE_PATH.'/view';
$this->templateViewPath = $documentRoot.$selectedThemeResourcePath.'/view';
}
/**
* A renderer helper should be called with its name.
*
* @return bool
*/
public function __invoke() : bool
{
$fileName = func_get_args()[0];
$pattern = [
'@WebHemi',
'@Theme',
];
$replacement = [
$this->defaultTemplateViewPath,
$this->templateViewPath,
];
$fileName = str_replace($pattern, $replacement, $fileName);
return file_exists($fileName);
}
}
<file_sep>/src/WebHemi/Configuration/ServiceAdapter/Base/ServiceAdapter.php
<?php
/**
* WebHemi.
*
* PHP version 7.1
*
* @copyright 2012 - 2018 Gixx-web (http://www.gixx-web.com)
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
*
* @link http://www.gixx-web.com
*/
declare(strict_types = 1);
namespace WebHemi\Configuration\ServiceAdapter\Base;
use InvalidArgumentException;
use WebHemi\Configuration\ServiceInterface;
/**
* Class ServiceAdapter.
*/
class ServiceAdapter implements ServiceInterface
{
/**
* @var array
*/
private $pathMap = [];
/**
* @var array
*/
private $rawConfig;
/**
* ServiceAdapter constructor.
*
* @param array $config
*/
public function __construct(array $config)
{
$this->rawConfig = $config;
$this->processConfig('', $config);
}
/**
* Processes the config into a one dimensional array.
*
* @param string $path
* @param array $config
* @return void
*/
private function processConfig(string $path, array $config) : void
{
foreach ($config as $key => $value) {
$this->pathMap[$path.$key] = $value;
if (is_array($value) && !empty($value)) {
$this->processConfig($path.$key.'/', $value);
}
}
}
/**
* Checks whether the key-path does exist or not.
*
* @param string $path
* @return bool
*/
public function has(string $path) : bool
{
return isset($this->pathMap[$path]);
}
/**
* Retrieves configuration data for a specific key.
*
* @param string $path
* @throws InvalidArgumentException
* @return array
*/
public function getData(string $path) : array
{
if (!$this->has($path)) {
throw new InvalidArgumentException(sprintf('Configuration for path "%s" not found', $path), 1000);
}
$data = $this->pathMap[$path];
return is_array($data) ? $data : [$data];
}
/**
* Returns the configuration instance for a specific key. Also add the possibility to merge additional information
* into it.
*
* @param string $path
* @throws InvalidArgumentException
* @return ServiceInterface
*/
public function getConfig(string $path) : ServiceInterface
{
if (!$this->has($path)) {
throw new InvalidArgumentException(sprintf('Configuration for path "%s" not found', $path), 1001);
}
return new self($this->getData($path));
}
/**
* Returns the stored raw config array.
*
* @return array
*/
public function toArray() : array
{
return $this->rawConfig;
}
}
|
90926bdede43b8ef80eeb0ed434762d59daaef3a
|
[
"SQL",
"Markdown",
"JavaScript",
"PHP",
"Shell"
] | 247 |
PHP
|
dzsi1994/WebHemi
|
c633046671380165922606e2fe5e66f075f18d4b
|
ca4938c960e5e23a191e0144a5b48c694e258243
|
refs/heads/main
|
<file_sep>const video = document.querySelector("#video")
const play = document.querySelector("#play")
const pause = document.querySelector("#pause")
const adelantar = document.querySelector("#forward")
const retroceder = document.querySelector("#backward")
const progreso = document.querySelector("#rango")
const volumen = document.querySelector("#volumen")
play.addEventListener('click', handlePlay = () =>{
video.play()
play.hidden= true
pause.hidden = false
})
pause.addEventListener('click', handlePause = () =>{
video.pause()
play.hidden= false
pause.hidden = true
})
adelantar.addEventListener('click', handleForward = () =>{
video.currentTime += 10
})
retroceder.addEventListener('click' , handleBackward = () =>{
video.currentTime -= 10
})
video.addEventListener('loadedmetadata', loadrango = () => {
progreso.max = video.duration
})
video.addEventListener('timeupdate',handleTimeUpdate = () => { progreso.value = video.currentTime
console.log(video.currentTime)
if(video.currentTime == video.duration ){
play.hidden= false
pause.hidden = true
}
})
progreso.addEventListener('input', handleInput = () => {
video.currentTime = progreso.value
})
// volumen.addEventListener('change', vol = (ev) =>{
// video.volume = ev.target.value;
// }, true)
console.log(video.duration)
console.log(video.currentTime)
|
67ef10e8d0a6437c3792b33ebc29611523372f51
|
[
"JavaScript"
] | 1 |
JavaScript
|
HervikM/Video-Player
|
ca04881f7fc353530f6436faeeebf63da276a803
|
d24f1d18dece085096884cd9224bbcf487e98192
|
refs/heads/main
|
<repo_name>hyun3586/new-year-countdown<file_sep>/js/script.js
// getEl
const daysEl = document.getElementById("days");
const hoursEl = document.getElementById("hours");
const minsEl = document.getElementById("mins");
const secondsEl = document.getElementById("seconds");
const currentYear = new Date().getFullYear(); // 2021
const newYearTime = new Date(`${currentYear + 1}-01-01 00:00:00`); // 2022-01-01 00:00:00
function updateCountdown() {
const currentTime = new Date(); // 2021-09-08 20:22
const diffTime = newYearTime - currentTime; // 2022 - (2021-09-08 20:22)
const days = Math.floor(diffTime / 1000 / 60 / 60 / 24);
const hours = Math.floor(diffTime / 1000 / 60 / 60) % 24;
const min = Math.floor(diffTime / 1000 / 60) % 60;
const seconds = Math.floor(diffTime / 1000) % 60;
daysEl.innerHTML = days;
hoursEl.innerHTML = timeNotationConversion(hours);
minsEl.innerHTML = timeNotationConversion(min);
secondsEl.innerHTML = timeNotationConversion(seconds);
}
function timeNotationConversion(time) {
return time < 10 ? '0' + time : time;
}
setInterval(updateCountdown, 1000);
|
cb47124d6e4303b82c7041f03c71bb5b84565cd4
|
[
"JavaScript"
] | 1 |
JavaScript
|
hyun3586/new-year-countdown
|
f27953a8c7ec9c45d2499218c9eb2a01ea5fc1db
|
12816b1bd0b57a42c6feb3ea2e529134f5cb0752
|
refs/heads/master
|
<repo_name>Moshabanat/APKanalysis<file_sep>/README.md
# APKanalysis
This script is created to help to automate the analysis process for APK files. The script can analyze multiple APKs at the same time.
The script is capable of doing the following:
1. unzipping apk file
2. converting files to strings
3. search through the files for actionable information (emails, urls, IPs)
4. Extracting apps permissions
5. uplading the apk to VT
6. Generate a Report
Requirements :
1. Python 2.7
2. Strings.exe from Microsoft sysinternals placed in C:\
3. Virustotal API or remove the function
Packages:
1. pip install AxmlParserPY
2. pip install requests
Command Example:
"python.exe C:\Users\H\Download\APKAnalyzer.py C:\Users\H\Downloads\apps"
<file_sep>/APKAnalyzer.py
import subprocess
import hashlib
import argparse
import zipfile
from fileinput import filename
from xml.dom import minidom
from xml.dom.minidom import parse, parseString
import axmlparserpy.axmlprinter as axmlprinter
import axmlparserpy.apk as apk
import os
import sys
import time
import re
import axmlparserpy.apk as apk
import urllib
import urllib2
import json
import requests
import webbrowser
import timeit
import argparse
import shutil
#This part needs to be modified in order to have the script running successfully
string_exe_file="C:\\strings.exe" #using strings.exe from Microsoft Sysinternals
#Timer:
tic = time.clock()
# Create target directory that shall store all related analysis files, and shall be deleted later on after the analysis is done.
# No need to modify this as all files shall be dropped in the temp folder
dirName = 'C:\\Windows\\Temp\AppAnalysis'
os.makedirs(dirName)
unz = dirName + '\\unzipped\\'
os.makedirs(unz)
txt_file_path= dirName + '\\txt_files\\'
os.makedirs(txt_file_path)
#----------------------
#initialzaion
apps_path = sys.argv[1] #receiving the path of APKs from the user
path = apps_path + '\\'
#initialzaion
url_list=[]
#Reporting format
f = open('report.html','w')
f.write("""<html>""")
f.write("""<head> <h1> Mobile App Technical Analysis: Report </h1>
< br>
<p> Starting the process in seconds: """+str(tic)+"""
<style>
table, th, td {
border: 1px solid black;
}
</style></head>>""")
f.write("""<body>""")
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def print_hash_local():
output_txt_file = dirName + 'output.txt'
f.write("""<table><tr><h1 style="color:red;">Hashing the applications locally and comparing hashes to the ones on the device :</h1></tr>
<tr>
<th>App Names</th>
<th>Hash Value</th>
<th><p style="color:red;"> Match or Not Match</p></th>
</tr>""")
for filename in os.listdir(path):
if "apk" in filename:
file_path=path+filename
f.write("<tr>")
hash_value=(md5(file_path))
f.write("""<th>"""+ filename + """</th>"""
"""<th>"""+ hash_value+"""</th>""")
if hash_value in open(output_txt_file).read():
f.write("<th> match</th>")
else:
f.write("<th> Not match</th>")
f.write("</tr>")
f.write("""</table>""")
def extract_zip(input_zip,path):
time.sleep(3)
fh = open(input_zip, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
z.extract(name, path)
fh.close()
def unpack_apps():
for filename in os.listdir(path):
if 'apk'in filename:
p=(path+filename)
s=os.makedirs(unz+filename)
unz_path= (unz+filename)
extract_zip(p,unz_path)
unz_path= (unz+filename)
time.sleep(4)
print ("Currently, the program is unzipping this apk" + filename)
def converting_files_to_string():
for filename in os.listdir(unz):
full_path= unz +filename
txtfile=txt_file_path+filename
s=os.system(string_exe_file+' -s '+full_path+' >'+txtfile+".txt")
def unique(list1):
# insert the list to the set
list_set = set(list1)
# convert the set to the list
unique_list = (list(list_set))
for x in unique_list:
f.write("""<tr><th><p>"""+x+"""</p></th></tr>""")
def filtering_links(txt_file):
f.write("""<tr><th><h1 style="color:blue;">HTTPs links</h1></th></tr>""")
url_list = []
txt_file=open(txt_file,'rb')
for urls in txt_file:
if re.search(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' , urls):
url_list.append("http"+ urls.split("http",1)[-1])
unique(url_list)
txt_file.close()
def filtering_emails(txt_file):
txt_file=open(txt_file,'rb')
f.write("""<tr><th><h1 style="color:blue;">Emails :</h1></th></tr>""")
email_list = []
for email in txt_file:
if re.search(r'\w+[.|\w]\w+@\w+[.]\w+[.|\w+]\w+' , email):
email_list.append(email.split("*")[-1] )
unique(email_list)
txt_file.close()
def filtering_ips(txt_file):
txt_file=open(txt_file,'rb')
ip_list = []
f.write("""<tr><th><h1 style="color:blue;">IP addresses:</h1></th></tr>""")
for ip in txt_file:
if re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' , ip):
ip_list.append(ip.split("*")[-1])
unique(ip_list)
txt_file.close()
def reading_txt_files():
for filename in os.listdir(txt_file_path):
f.write("""<table>""")
f.write("<br><br>")
if "txt"in filename:
f.write("""<tr>""")
f.write("""<th><h1 style="color:red;"> Actionable information of this app :"""+filename+"""</h1></th>""")
full_path=txt_file_path+filename
filtering_links(full_path)
filtering_emails(full_path)
filtering_ips(full_path)
f.write("""</tr>""")
f.write("""</table>""")
def print_permission():
f.write("""<table><tr><h1 style="color:red;">Printing the permissions of each app :</h1></tr>
<tr>
<th>App Names</th>
<th>permissions</th>
</tr>""")
for filename in os.listdir(path):
if "apk" in filename:
f.write("<tr>")
f.write("""<th>"""+ filename + """</th>""")
perm = apk.APK(path+filename)
f.write("""<th>"""+ str(perm.get_permissions()) +"""</th>""")
f.write("</tr>")
f.write("""</table>""")
def upload_file(filename):
baseurl = "https://www.virustotal.com/vtapi/v2/"
api = "******************Enter your VT API HERE****************"
url = baseurl + "file/scan"
f = open(filename, "rb")
files = {"file": f}
values = {"apikey":api}
r = requests.post(url, values, files=files)
result=(r.json())
return ("""%s """
% (result['permalink']))
def print_virustotal():
f.write("""<table><tr><h1 style="color:red;">Printing Virus Total Links of this app :</h1></tr>
<tr>
<th>App Names</th>
<th>Links</th>
</tr>""")
for filename in os.listdir(path):
if "apk" in filename:
f.write("""<tr>""")
f.write("""<th>"""+ filename + """</th>""")
f.write("""<th> <a href="""""+upload_file(path+filename)+""">Click here to see the result of virus total </a></th>""")
f.write("""</tr>""")
continue
f.write("</table>")
#print (print_virustotal())
def design_html_page():
tac = time.clock()
total_time=tac-tic
f.write("""<h1 style="color:red;">Total processing time in seconds is """+str(total_time)+"</h1>""")
f.write(
"""
</body>
</html>""")
f.close()
webbrowser.open_new_tab('report.html')
#this function is to delete the related files and artifcats
def remove_directory():
shutil.rmtree(dirName)
unpack_apps()
converting_files_to_string()
print_permission()
print_virustotal()
reading_txt_files()
design_html_page()
remove_directory()
|
79e7d27818b3f44b8d04b248414c941d52862c34
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
Moshabanat/APKanalysis
|
6d45f067ab166c95a480825bf553f832bd4726b8
|
36ebad5070a74db1cd19ae97435a1a1dd2c8b1dd
|
refs/heads/master
|
<repo_name>hpAks/BlogEntries<file_sep>/js/blogscript.js
let blogs = [
{ title: "Blog A", urltitle: "blog-a", customtitle: "CustomBlogA" },
{ title: "Blog B", urltitle: "blog-b", customtitle: "CustomBlogB" },
{ title: "Blog C", urltitle: "blog-c", customtitle: "CustomBlogC" },
{ title: "Blog D", urltitle: "blog-d", customtitle: "CustomBlogD" },
{ title: "Blog E", urltitle: "blog-e", customtitle: "CustomBlogE" }
];
var arrHead = new Array();
arrHead = ['Blog Title', 'Blog URL', 'Custom Blog Title'];
function searchblog() {
var title = document.getElementById("blogTitle").value;
title = isNullOrEmpty(title);
var index = searchblogEntry(title);
createResultTable(index);
}
function createResultTable(index){
var resulttable=document.getElementById("resultsettable");
var tr = resulttable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // TABLE HEADER.
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
tr = resulttable.insertRow(-1);
var td = document.createElement('td');
td = tr.insertCell(-1); // TABLE HEADER.
td.innerHTML = blogs[index]["title"];
tr.appendChild(th);
console.log(document.getElementById("resultsettable").className);
}
function searchblogEntry(title){
for(i =0;i<blogs.length;i++){
var blog = blogs[i];
if((blog["title"]) == title){
return i;
}
}
return null;
}
function isNullOrEmpty(value) {
if(value == null || value === ""){
return ""
}else{
return value;
}
}<file_sep>/README.md
# BlogEntries
Adding/Editing blog
|
86d54f3345efe9edb1e2c269015d5bf07aa0851c
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
hpAks/BlogEntries
|
06f7bfa56ea35d8d9d4cae06c2216270cee47db4
|
fba271a50b3feebca83387a64a59be7d9be4cb1e
|
refs/heads/master
|
<repo_name>passedbylove/Audio-SampleConvert-And-BitWidthConvert-And-trackConvert<file_sep>/android/RecordManager.cpp
//
// Created by Administrator on 2018/12/18.
//
#include "RecordManager.h"
#include "com_kehwin_recorder_utils_AudioUtils.h"
#include "AudioHandle.h"
JNIEXPORT void JNICALL Java_com_kehwin_recorder_utils_AudioUtils_resampler
(JNIEnv *env, jclass cls, jbyteArray srcData, jint srcSampleRate, jint srcSize, jbyteArray desData, jint desSampleRate,jint desSize){
const int16_t * tempSrcData = (const int16_t *)env->GetByteArrayElements(srcData, 0);
int16_t * tempDesData = (int16_t *)env->GetByteArrayElements(desData,0);
AudioHandle::resampleData(tempSrcData,srcSampleRate,srcSize,tempDesData,desSampleRate,desSize);
env->ReleaseByteArrayElements(srcData,(jbyte*)tempSrcData,0);
env->ReleaseByteArrayElements(desData,(jbyte*)tempDesData,0);
}
JNIEXPORT jbyteArray JNICALL Java_com_kehwin_recorder_utils_AudioUtils_doubleChannel2SingleChannel
(JNIEnv *env, jclass cls, jbyteArray doubleChannelData, jint size, jint nPerSampleBytesPerChannle){
unsigned char * tempSrcData = (unsigned char *)env->GetByteArrayElements(doubleChannelData,0);
unsigned char * tempDesData = AudioHandle::getSingleChannelAudio(tempSrcData,size,nPerSampleBytesPerChannle);
env->ReleaseByteArrayElements(doubleChannelData,(jbyte*)tempSrcData,0);
jbyteArray jbarray = env->NewByteArray(size/2);
env->SetByteArrayRegion(jbarray,0,size/2,(jbyte*)tempDesData);
return jbarray;
}
JNIEXPORT jbyteArray JNICALL Java_com_kehwin_recorder_utils_AudioUtils_bitWidthConvert
(JNIEnv *env, jclass cls, jbyteArray data, jint size, jint oldBitWidth, jint newBitWidth){
if(oldBitWidth==newBitWidth){
return data;
}
//位宽转换之后,需要改变的数据大小
int changeSize=0;
//位宽转换之后,目标数据的大小
int targetSize=0;
//源数据的采样点
int samplerRate = (size% (oldBitWidth/8)) ==0 ? ( size/ (oldBitWidth/8) ) : (int)( (float)(size/(oldBitWidth/8)) +1 );
if(oldBitWidth > newBitWidth){
changeSize = ( (oldBitWidth-newBitWidth) /8 ) *samplerRate;
targetSize = size-changeSize;
}else{//oldBitWidth < newBitWidth
changeSize = ( (newBitWidth-oldBitWidth) /8 ) *samplerRate;
targetSize = size+changeSize;
}
unsigned char * tempSrcData = (unsigned char *)env->GetByteArrayElements(data,0);
unsigned char * tempDesData = AudioHandle::bitWidthConvert(tempSrcData,size,oldBitWidth, newBitWidth,targetSize ,samplerRate);
env->ReleaseByteArrayElements(data,(jbyte*)tempSrcData,0);
jbyteArray jbarray = env->NewByteArray(targetSize);//samplerRate *(oldBitWidth/8)
env->SetByteArrayRegion(jbarray,0,targetSize,(jbyte*)tempDesData);
return jbarray;
}
JNIEXPORT jintArray JNICALL Java_com_kehwin_recorder_utils_AudioUtils_byteArray2SamplerArray
(JNIEnv *env, jclass cls , jbyteArray orgPcmBuf, jint size,jint bitWidth){
int byteCountPreSampler = (bitWidth /8);
if (orgPcmBuf==NULL || size==0){
return NULL;
}
int samplerCount=0;
if (size% byteCountPreSampler==0){
samplerCount = size/byteCountPreSampler;
}else{
samplerCount = size/byteCountPreSampler+1;
}
if (samplerCount==0){
return NULL;
}
int tempData =0;
int* tempSamplerData=new int[samplerCount];
LOGDV("samplerCount=%d byteCountPreSampler=%d",samplerCount,byteCountPreSampler);
signed char *data =(signed char *)env->GetByteArrayElements(orgPcmBuf, 0);
int j=0;
for(int i=0;i<samplerCount;i++){
tempData=0;
for(int k=0;k<byteCountPreSampler;k++){
signed int tempBuf =0;
if ((j+k)<size){
tempBuf = ( data[j+k] << (k*8) );
}
tempData = (tempData | tempBuf);
/*if(i>300 && i<400){
LOGDV("tempBuf=%d,k=%d,tempData=%d,i=%d",tempBuf,k,tempData,i);
}*/
}
// LOGDV("tempData=%d i=%d",tempData,i);
tempSamplerData[i]=tempData;
// LogUtils.v("i="+i+" tempSamplerData.len="+tempSamplerData.length);
j+=byteCountPreSampler;
}
jintArray tempBufs = env->NewIntArray(samplerCount);//samplerRate *(oldBitWidth/8)
env->SetIntArrayRegion(tempBufs, 0, samplerCount,(jint*)(tempSamplerData));
env->ReleaseByteArrayElements(orgPcmBuf,(jbyte*)data,0);
// LogUtils.v("samplerCount="+samplerCount+" byteCountPreSampler="+byteCountPreSampler);
return tempBufs;
}
<file_sep>/README.md
# Audio SampleConvert And BitWidthConvert And trackConvert
Audio SampleConvert And BitWidthConvert And trackConvert
音频之声道、采样位宽、采样率转换原理及其代码实现
https://blog.csdn.net/qq_33750826/article/details/80244784
http://samples.mplayerhq.hu/
<file_sep>/audio_sample_convert.cpp
#include "audio_sample_convert.h"
/*****************************************************************************
name : insert8_24k
description : none
Arguments : none
Returns : none
designer : commemt by syf
*****************************************************************************/
void insert8_24k(k_int16 *psi_input, k_int16 *psi_output,k_uint32
ui_samples)
{
static k_int16 s_sample_prev = 0;
k_uint32 i;
k_uint32 j = 3;
k_uint16 us_step = 0;
us_step = ((psi_input[0] - s_sample_prev)) / 3; //
psi_output[0] = s_sample_prev + us_step;
psi_output[1] = s_sample_prev + (us_step*2);
psi_output[2] = psi_input[0]; //us_data_pre + (us_step*3)
for(i = 1;i < ui_samples;i++)
{
us_step = (psi_input[i] - psi_input[i-1]) / 3;
psi_output[j] = psi_input[i-1] + us_step;
psi_output[j+1] = psi_input[i-1] + (us_step*2);
psi_output[j+2] = psi_input[i]; //psi_input[i-1] + (us_step*3)
j += 3;
}
s_sample_prev = psi_input[i-1];
}
/*****************************************************************************
name : convert12_8k
description : none
Arguments : none
Returns : none
designer : commemt by syf
*****************************************************************************/
static k_int16 s_sample_prev = 0;
void setpresample(k_int16 sampe)
{
s_sample_prev = sampe;
}
void convert8_16k(k_int16 *psi_buff, k_int16* psi_outbuf,k_uint32 ui_samples){
k_uint32 i,j = 2;
k_uint16 us_step = 0;
us_step = ((psi_buff[0] - s_sample_prev)) / 2; //
psi_outbuf[0] = s_sample_prev + us_step;
psi_outbuf[1] = psi_buff[0]; //us_data_pre + (us_step*3)
for(i=1;i<ui_samples;i++){
us_step = (psi_buff[i] - psi_buff[i-1]) / 2;
psi_outbuf[j] = psi_buff[i-1]+us_step;
psi_outbuf[j+1] = psi_buff[i];
j+=2;
}
s_sample_prev = psi_buff[i-1];
}
void convert24_12k(k_int16 *psi_buff,k_int16* psi_outbuf,k_uint32 ui_samples)
{
k_uint32 i;
k_uint32 j;
for(i = 0, j = 0; i < ui_samples; i += 2)
{
psi_outbuf[j++] = psi_buff[i];
}
}
void convert24_8k(k_int16 *psi_buff,k_int16 *psi_output,k_uint32 ui_samples)
{
k_uint32 i;
k_uint32 j;
for(i = 0, j = 0; i < ui_samples; i += 3)
{
psi_output[j++] = psi_buff[i];
}
}
/*****************************************************************************
name : insert12_48k
description : none
Arguments : none
Returns : none
designer : commemt by syf
*****************************************************************************/
void convert12_24k(k_int16 *psi_input, k_int16 *psi_output,k_uint32 ui_samples)
{
static k_int16 us_data_pre = 0;
k_uint32 i;
k_uint32 j = 2;
psi_output[0] = (us_data_pre+psi_input[0]) >> 1;
psi_output[1] = psi_input[0];
for(i = 1;i < ui_samples;i++)
{
psi_output[j] = (psi_input[i-1]+psi_input[i]) >> 1;
psi_output[j+1] = psi_input[i];
j += 2;
}
us_data_pre = psi_input[i-1];
}
void convert12_48k(k_int16 *psi_input, k_int16 *psi_output,k_uint32 ui_samples)
{
static k_int16 us_data_pre = 0;
k_uint32 i;
k_uint32 j = 4;
k_uint16 us_step = 0;
us_step = (psi_input[0]-us_data_pre) /4;
psi_output[0] = us_data_pre+us_step;
psi_output[1] = us_data_pre+us_step*2;
psi_output[2] = us_data_pre+us_step*3;
psi_output[3] = psi_input[0];
for(i = 1;i < ui_samples;i++)
{
us_step = (psi_input[i]-psi_input[i-1]) /4;
psi_output[j] = psi_input[i-1]+us_step;
psi_output[j+1] = psi_input[i-1]+us_step*2;
psi_output[j+2] = psi_input[i-1]+us_step*3;
psi_output[j+3] = psi_input[i];
j += 4;
}
us_data_pre = psi_input[i-1];
}
void convert48_16k(k_int16 *psi_buff,k_int16 *psi_output,k_uint32 ui_samples)
{
k_uint32 i;
k_uint32 j;
for(i = 0, j = 0; i < ui_samples; i += 3)
{
psi_output[j++] = psi_buff[i];
}
}<file_sep>/audio_sample_convert.h
#ifndef _AUDIO_SAMPLE_H_
#define _AUDIO_SAMPLE_H_
typedef signed char k_sint8; //注意编译把char认为是有符号还是无符号。
typedef char k_int8; //注意编译把char认为是有符号还是无符号。
typedef unsigned char k_uint8;
typedef signed short int k_int16;
typedef unsigned short int k_uint16;
typedef signed int k_int32;
typedef unsigned int k_uint32;
typedef signed long k_intL32;
typedef unsigned long k_uintL32;
typedef signed long long k_intLL64;
typedef unsigned long long k_uintLL64;
typedef float k_float32;
typedef double k_double64;
void insert8_24k(k_int16 *psi_input, k_int16 *psi_output,k_uint32 ui_samples);
void convert8_16k(k_int16 *psi_buff, k_int16* psi_outbuf,k_uint32 ui_samples);
void convert24_12k(k_int16 *psi_buff,k_int16* psi_outbuf,k_uint32 ui_samples);
void convert24_8k(k_int16 *psi_buff,k_int16 *psi_output,k_uint32 ui_samples);
void convert12_24k(k_int16 *psi_input, k_int16 *psi_output,k_uint32 ui_samples);
void convert12_48k(k_int16 *psi_input, k_int16 *psi_output,k_uint32 ui_samples);
void convert48_16k(k_int16 *psi_buff,k_int16 *psi_output,k_uint32 ui_samples);
void setpresample(k_int16 sampe);
#endif<file_sep>/android/RecordManager.h
//
// Created by Administrator on 2018/12/18.
//
#ifndef KEHWINRECORD_RECORDMANAGER_H
#define KEHWINRECORD_RECORDMANAGER_H
class RecordManager{
public:
RecordManager();
virtual ~RecordManager();
};
#endif //KEHWINRECORD_RECORDMANAGER_H
<file_sep>/android/AudioHandle.h
#ifndef AUDIOHANDLE_H
#define AUDIOHANDLE_H
#include<stdio.h>
#include<string.h>
#include "android_logcat.h"
#define BIT_8_WIDTH 8
#define BIT_16_WIDTH 16
#define BIT_24_WIDTH 24
#define BIT_32_WIDTH 32
class AudioHandle{
public:
static unsigned char * getSingleChannelAudio(unsigned char * pDoubleChannelBuf, int nLen, int nPerSampleBytesPerChannle)
{
int nOneChannelLen = nLen / 2;
unsigned char * pOneChannelBuf = new unsigned char[nOneChannelLen];
for (int i = 0; i < nOneChannelLen / 2; i++)
{
memcpy((uint16_t*)pOneChannelBuf + i, ((uint32_t *)(pDoubleChannelBuf)) + i, nPerSampleBytesPerChannle);
}
return pOneChannelBuf;
}
static unsigned char * audioTrackConvert(unsigned char * srcTrackBuf, int srcTrackLen, int nPerSampleBytesPerTrack,bool isSingleConvertDoubleTrack)
{
int targetBuflLen=0;
int offset=0;
unsigned char * targetTrackBuf;
if(isSingleConvertDoubleTrack){//单声道转双声道
targetBuflLen== srcTrackLen * 2;
targetTrackBuf= new unsigned char[targetBuflLen];
for (int i = 0; i < srcTrackLen; i+=nPerSampleBytesPerTrack)
{
for (int j = 0; j < 2; j++)
{
memcpy(targetTrackBuf + offset,
srcTrackBuf + (i*nPerSampleBytesPerTrack), nPerSampleBytesPerTrack);
offset+=nPerSampleBytesPerTrack;
}
}
}else{//双声道转单声道
targetBuflLen== srcTrackLen /2;
targetTrackBuf= new unsigned char[targetBuflLen];
for (int i = 0; i < targetBuflLen; i+=nPerSampleBytesPerTrack)
{
memcpy(targetTrackBuf + (i*nPerSampleBytesPerTrack),
srcTrackBuf + ((i+1)*nPerSampleBytesPerTrack), nPerSampleBytesPerTrack);
}
}
return targetTrackBuf;
}
static unsigned char * bitWidthConvert(unsigned char * data, int nLen, int oldBitWidth,int newBitWidth,int targetSize,int samplerRate)
{
if(oldBitWidth==newBitWidth){
return data;
}
//新的位宽的字节数
int newBitWidthByteCount= newBitWidth/8;
//旧的位宽的字节数
int oldBitWidthByteCount= oldBitWidth/8;
//目标数据
unsigned char * targetBuf = new unsigned char[targetSize];
//LOGDV("tempBitWidthTimes=%d,targetSize=%d,samplerRate=%d",tempBitWidthTimes,targetSize,samplerRate);
//临时的源数据的每个采样点的数据
uint32_t tempData;
//目标数据偏移量
int newBitWidthOffset=0;
int oldBitWidthOffset=0;
// uint32_t* data32bit=(uint32_t*)data;
if (oldBitWidth < newBitWidth){
for (int i = 0; i < samplerRate; ++i) {
memcpy(&tempData,data+oldBitWidthOffset, oldBitWidthByteCount);
oldBitWidthOffset+=oldBitWidthByteCount;
memcpy(targetBuf+newBitWidthOffset,&tempData, newBitWidthByteCount);
newBitWidthOffset+=newBitWidthByteCount;
}
}else{
for (int i = 0; i < samplerRate; ++i) {
memcpy(&tempData,data+oldBitWidthOffset, oldBitWidthByteCount);
oldBitWidthOffset+=oldBitWidthByteCount;
//去除低位
tempData = (tempData >> (oldBitWidth-newBitWidth) );
memcpy(targetBuf+newBitWidthOffset,&tempData, newBitWidthByteCount);
newBitWidthOffset+=newBitWidthByteCount;
}
}
/* u_int8_t* data8bit;
uint16_t* data16bit;
uint32_t* data32bit;
if (oldBitWidth < newBitWidth){
switch (oldBitWidth){
case BIT_8_WIDTH:
data8bit=(u_int8_t*)data;
for (int i = 0; i < samplerRate; ++i) {
tempData = *(data8bit+i) ;
memcpy(targetBuf+count,&tempData, newBitWidthByteCount);
count+=newBitWidthByteCount;
}
break;
case BIT_16_WIDTH:
// data16bit=(uint16_t*)data;
for (int i = 0; i < nLen; ++i) {
tempData = *(data16bit+i) ;
memcpy(targetBuf+count,&tempData, newBitWidthByteCount);
count+=newBitWidthByteCount;
}
break;
case BIT_24_WIDTH:
case BIT_32_WIDTH:
data32bit=(uint32_t*)data;
for (int i = 0; i < samplerRate; ++i) {
tempData = *(data32bit+i) ;
memcpy(targetBuf+count,&tempData, newBitWidthByteCount);
count+=newBitWidthByteCount;
}
break;
}
}else{
switch (oldBitWidth){
case BIT_8_WIDTH:
data8bit=(u_int8_t*)data;
for (int i = 0; i < samplerRate; ++i) {
//去除低位
tempData = ((*(data8bit+i)) >> (oldBitWidth-newBitWidth) );
memcpy(targetBuf+count,&tempData, newBitWidthByteCount);
count+=newBitWidthByteCount;
}
break;
case BIT_16_WIDTH:
data16bit=(uint16_t*)data;
for (int i = 0; i < samplerRate; ++i) {
//去除低位
tempData = ((*(data16bit+i)) >> (oldBitWidth-newBitWidth) );
memcpy(targetBuf+count,&tempData, newBitWidthByteCount);
count+=newBitWidthByteCount;
}
break;
case BIT_24_WIDTH:
case BIT_32_WIDTH:
data32bit=(uint32_t*)data;
for (int i = 0; i < samplerRate; ++i) {
//去除低位
// tempData = ((*(data32bit+i)) >> (oldBitWidth-newBitWidth) );
tempData = ((*(data32bit+i)) );
memcpy(targetBuf+count,&tempData, newBitWidthByteCount);
count+=newBitWidthByteCount;
}
break;
}
}*/
return targetBuf;
}
static void resampleData(const int16_t *sourceData, int32_t sampleRate, uint32_t srcSize, int16_t *destinationData, int32_t newSampleRate,uint32_t dstSize)
{
if (sampleRate == newSampleRate)
{
memcpy(destinationData, sourceData, srcSize * sizeof(int16_t));
return;
}
uint32_t last_pos = srcSize - 1;
//LOGDV("srcSize=%d,dstSize=%d",srcSize,dstSize);
for (uint32_t idx = 0; idx < dstSize; idx++)
{
float index = ((float) idx * sampleRate) / (newSampleRate);
uint32_t p1 = (uint32_t) index;
float coef = index - p1;
uint32_t p2 = (p1 == last_pos) ? last_pos : p1 + 1;
destinationData[idx] = (int16_t) ((1.0f - coef) * sourceData[p1] + coef * sourceData[p2]);
// LOGDV("index=%f,p1=%d,coef=%f,p2=%d",index,p1,coef,p2);
}
}
};
#endif // AUDIOHANDLE_H
<file_sep>/android/android_logcat.h
#ifndef _ANDROID_H_
#define _ANDROID_H_
#include <android/log.h>
#undef LOG_TAG
#define LOG_TAG "KW_LOG"
#if 1
#define LOGDD(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#else
#define LOGDD(...)
#endif
#define LOGDV(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#endif
|
2e15cd3b4651ad80be8380c912f5ec232df39073
|
[
"Markdown",
"C",
"C++"
] | 7 |
C++
|
passedbylove/Audio-SampleConvert-And-BitWidthConvert-And-trackConvert
|
9512d25246562a35366d8f8eba9495fedfaa8c26
|
3df65e3bf11b3582e9619aca2c1e6ce6da806e4f
|
refs/heads/master
|
<repo_name>himanshu010/folder-structure<file_sep>/folder-structure.md
# Folder Structue
```
├───folder-structure
│ ├───himanshu
│ │ ├───New folder2-1
│ │ ├───New folder2-2
│ ├───New folder
│ ├───New folder (3)
│ │ ├───aa
│ │ │ ├───ss
│ ├───New folder (4)
```
<file_sep>/README.md
# folder-structure
**This repo makes the folder structure dynamic.**
## Steps:-
i. Clone the repo<br>
ii. Run the command "node folderstruct.js"<br>
iii. Now you can see that the folder-structure.md file has the latest folder-structure<br><br>
### **Files and Folder other than the .js file and .md file is only for demostration purposes.**
<file_sep>/folderstruct.js
var fs = require('fs')
var path = require("path");
var util = require("util");
var logFile = fs.createWriteStream("folder-structure.md", { flags: "w" });
var logStdout = process.stdout;
console.log = function() {
logFile.write(util.format.apply(null, arguments) + "\n");
logStdout.write(util.format.apply(null, arguments) + "\n");
};
console.error = console.log;
var FolderNamesArray = [];
// var levels=[0];
var level = 0;
var spacing = "";
console.log("# Folder Structue\n\n```")
function crawl(spacing, dir, level) {
var folderName = path.basename(dir);
FolderNamesArray.push(folderName);
console.log(spacing + "├───" + folderName);
var files = fs.readdirSync(dir);
for (var x in files) {
//ignored folders
if (files[x] !== ".git" && files[x] !== "New folder (2)") {
var next = path.join(dir, files[x]);
if (fs.lstatSync(next).isDirectory() === true) {
crawl(spacing +"│" + " ", next, level + 1);
}
}
}
}
crawl(spacing, __dirname, level);
console.log("```");
|
77f24f620e5cd63fbbc777c3771d63d166e3ac31
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
himanshu010/folder-structure
|
e46d7c6273c674e0c7225241751afb7732deabff
|
a9096c37bce226b155cc99068104c27f033cb3dd
|
refs/heads/main
|
<repo_name>GermanoMacieira/ADS_Projeto_de_Arquitetura_de_Sistema_CRUD<file_sep>/src/Controller/Main.java
package Controller;
import Model.Funcionario;
import Model.Loja;
import View.InOut;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// Declaração:
int numeroDigitado;
//Menu Principal que faz o direcionamento para os Sistemas
do {
String sistema = "Qual sistema deseja acessar:\n"+
"1 - Cadastro de Funcionarios\n"+
"2 - Cadastro de Lojas\n"+
"0 - Sair";
numeroDigitado = InOut.InInt(sistema);
//SubMenu de Tratamento para manutenção de Funcionário
switch(numeroDigitado){
case 1:
do{
String opcoes = "Digite um dos Numeros abaixo:\n"+
"1 - Cadastrar Novo Funcionario\n"+
"2 - Lista de todos os Funcionario\n"+
"3 - Alterar um Funcionarios\n"+
"4 - Procurar por Funcionario\n"+
"5 - Deletar um Funcionario\n"+
"6 - Apagar Todos os funcionarios\n"+
"0 - Finalizar ";
numeroDigitado = InOut.InInt(opcoes);
switch(numeroDigitado){
case 0:
InOut.OutMessage("O programa será Finalizado", "Atenção");
break;
case 1:
Funcionario.cadastrarFunc();
break;
case 2:
Funcionario.listarFunc();
break;
case 3:
Funcionario.alterarFunc();
break;
case 4:
Funcionario.procurarFunc();
break;
case 5:
Funcionario.deletarFunc();
break;
case 6:
Funcionario.apagarFunc();
break;
default:
InOut.OutMessage("Opção Invalida!", "Erro!");
break;
}
}while(numeroDigitado != 0);
break;
//Menu de Cadastro de Lojas:
case 2:
do {
String opcoes = "Digite um dos Numeros abaixo:\n"+
"1 - Cadastrar Nova Loja \n"+
"2 - Lista de todos as Lojas\n"+
"3 - Alterar o nome de uma loja\n"+
"4 - Procurar uma loja\n"+
"5 - Deletar uma loja\n"+
"6 - Apagar todas as lojas\n"+
"0 - Finalizar ";
numeroDigitado = InOut.InInt(opcoes);
switch(numeroDigitado){
case 0:
InOut.OutMessage("O programa será Finalizado", "Atenção");
break;
case 1:
Loja.cadastrarLoja();
break;
case 2:
Loja.listarLoja();
break;
case 3:
Loja.alterarLoja();
break;
case 4:
Loja.procurarLoja();
break;
case 5:
Loja.deletarLoja();
break;
case 6:
Loja.apagarLoja();
break;
default:
InOut.OutMessage("Opção Invalida!", "Erro!");
break;
}
}while(numeroDigitado != 0);
}
}while(numeroDigitado != 0);
System.out.println("Programa Finzalizado");
}
}
<file_sep>/README.md
## Projeto de Arquitetura de Sistema - CRUD
Trata-se de um pequeno trabalho acadêmico realizado na disciplina de Projeto de Arquitetura de Sistema, onde foi requisitado a construção de um **CRUD (Create, Read, Update e Delete)** para algum tipo de aplicação(escolha livre) e qualquer linguagem orientada a objetos.
*This is a small academic work carried out in the discipline of System Architecture Design, where the construction of a CRUD (Create, Read, Update and Delete) was requested for some type of application (free choice) and any object-oriented language.*
Meu [Linkedin](https://www.linkedin.com/in/germano-macieira).
<file_sep>/src/Model/Funcionario.java
package Model;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import View.InOut;
public class Funcionario {
// Atributos:
private int Cod_Func;
private String Cpf_Func;
private String Nome_Func;
private String Funcao_Func;
private double Salario;
private static int contadorRegistros = 0;
// Declaração dos ArrayLists:
private static ArrayList<Funcionario> listaFuncionarios = new ArrayList<Funcionario>();
/*
public Funcionario(){
contadorRegistros++;
this.Cod_Func = contadorRegistros;
}*/
// Construtor:
public Funcionario(String Cpf, String Nome, String Funcao, double Salario) {
contadorRegistros++;
this.Cod_Func = contadorRegistros;
this.Cpf_Func = Cpf;
this.Nome_Func = Nome;
this.Funcao_Func = Funcao;
this.Salario = Salario;
}
// Gets e Sets:
public int getCod_Func() {
return Cod_Func;
}
public String getNome_Func() {
return Nome_Func;
}
public void setNome_Func(String Nome) {
this.Nome_Func = Nome;
}
public double getSalario() {
return Salario;
}
public void setSalario(double Salario) {
this.Salario = Salario;
}
public String getCpf_Func() {
return Cpf_Func;
}
public void setCpf(String Cpf) {
Cpf_Func = Cpf;
}
public String getFuncao_Func() {
return Funcao_Func;
}
public void setFuncao_Func(String Funcao) {
Funcao_Func = Funcao;
}
// Métodos para Manutenção de Funcionários:
public static void cadastrarFunc() {
String Nome = InOut.InString("Insira o Nome do Funcionario:");
String Cpf = InOut.InString("Insira o CPF do Funcionario:");
String Funcao = InOut.InString("Insira a função do Funcionario:");
double Salario = InOut.InInt("Digite o Salario do Funcionario:");
Funcionario funcionario = new Funcionario(Cpf, Nome, Funcao, Salario);
listaFuncionarios.add(funcionario);
}
public static void listarFunc() throws IOException {
if(listaFuncionarios.isEmpty()){
InOut.OutMessage("Nenhum Funcionario consta no Cadastrado!");
return;
}
FileWriter arq1 = new FileWriter("listafuncionarios.txt");
PrintWriter gravaArq = new PrintWriter(arq1);
String relatorio = "";
gravaArq.printf("---------Lista de Funcionarios---------\r\n");
for(int i = 0; i < listaFuncionarios.size(); i++){
Funcionario func = listaFuncionarios.get(i);
gravaArq.printf(" - |CODIGO| %d |CPF| %s |NOME| %s |FUNCAO| %s |SALARIO| %f\r\n",
func.getCod_Func(), func.getCpf_Func(), func.getNome_Func(), func.getFuncao_Func(), func.getSalario());
relatorio += "\nCodigo do Funcionário: " + func.getCod_Func() +
"\nCPF: " + func.getCpf_Func() +
"\nNome do Funcionário: " + func.getNome_Func() +
"\nFunção: " + func.getFuncao_Func() +
"\nSalario: R$" + func.getSalario()+
"\n----------------------------------------------------------\r";
}
gravaArq.close();
InOut.OutMessage(relatorio);
}
public static void alterarFunc(){
if(listaFuncionarios.size() == 0){
InOut.OutMessage("Lista Vazia");
return;
}
String nomeFuncionarioPesquisar = InOut.InString("Digite o Nome do Funcionario que deseja pesquisar:");
for(int i=0; i < listaFuncionarios.size(); i++){
Funcionario funcionario = listaFuncionarios.get(i);
if(nomeFuncionarioPesquisar.equalsIgnoreCase(funcionario.getNome_Func())){
String nomeNovo = InOut.InString("Digite o novo Nome do Funcionario:");
funcionario.setNome_Func(nomeNovo);
InOut.OutMessage("Nome alterado com sucesso");
break;
}
}
InOut.OutMessage("Funcionario não encontrado");
}
public static void procurarFunc(){
String exibir = "";
String nomeArq = "listafuncionarios.txt";
String linha = "";
File arq = new File(nomeArq);
if(arq.exists()){
exibir = "RELATORIO";
try{
FileReader abrindo = new FileReader(nomeArq);
BufferedReader leitor = new BufferedReader(abrindo);
while(true){
linha = leitor.readLine();
if(linha == null)
break;
exibir += linha + "\n";
}
leitor.close();
}catch(Exception e){
InOut.OutMessage("Erro: \n"+e.getMessage(), "ERRO");
}
InOut.OutMessage(exibir, "LISTA DE FUNCIONARIOS");
}else{
InOut.OutMessage("Arquivo inexistente", "ERRO");
}
}
public static void deletarFunc(){
if(listaFuncionarios.size() == 0){
InOut.OutMessage("Lista Vazia");
return;
}
String nomeFuncionarioPesquisar = InOut.InString("Digite o Nome do Funcionario que deseja Deletar:");
for(int i=0; i < listaFuncionarios.size(); i++){
Funcionario funcionario = listaFuncionarios.get(i);
if(nomeFuncionarioPesquisar.equalsIgnoreCase(funcionario.getNome_Func())){
listaFuncionarios.remove(i);
InOut.OutMessage("Funcionario excluido com Sucesso!");
break;
}
}
InOut.OutMessage("Nome do Funcionario alterado com sucesso");
}
public static void apagarFunc() {
if(listaFuncionarios.isEmpty()){
InOut.OutMessage("Nenhum Funcionario Cadastrado");
return;
}
listaFuncionarios.clear();
InOut.OutMessage("Todos os Funcionarios foram Apagados!");
}
}
|
4f9e716f86f8c61e40b9546d2319da8c964cef35
|
[
"Markdown",
"Java"
] | 3 |
Java
|
GermanoMacieira/ADS_Projeto_de_Arquitetura_de_Sistema_CRUD
|
6c2dbd1f678bdd501b0ef502a03c473a6952dacc
|
fd64e373d1447b069bf6a048c6eb6a7b184a2236
|
refs/heads/master
|
<repo_name>BenBurum/Duplicate-File-Finder<file_sep>/burum-brown/src/test/java/com/agile/findduplicates/DuplicateFinderTest.java
package com.agile.findduplicates;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import static junit.framework.Assert.*;
public class DuplicateFinderTest {
private static final String DIR_NAME = "test";
private static final String DIR1 = "dir1";
private static final String DIR2 = "dir2";
private static final String DIR3 = "dir3";
private static final String FILE1 = "file1";
private static final String FILE2 = "file2";
private static final String FILE3 = "file3";
private static final String FILE4 = "file4";
private static final String FILE_CONTENT1 = UUID.randomUUID().toString();
private static final String FILE_CONTENT2 = UUID.randomUUID().toString();
private static final String FILE_CONTENT3 = UUID.randomUUID().toString() + UUID.randomUUID().toString();
private static final String FILE_CONTENT4 = UUID.randomUUID().toString() + UUID.randomUUID().toString();
private File directory;
private File dir1File1;
private File dir1File2;
private File dir1File3;
private File dir1Sub1File4;
private File dir1Sub2File1;
private File dir2File1;
private File dir2File2;
private File dir2File4;
private File dir3File1;
private File dir3File2;
private File dir3File3;
private File dir3File4;
private boolean rm (File file) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (!rm(f)) {
return false;
}
}
}
return file.delete();
}
private Path createDirectory (String dirPath, String dirName) throws Exception {
return Files.createDirectory(Paths.get(dirPath, dirName));
}
private Path createFile (String dirPath, String fileName) throws Exception {
return Files.createFile(Paths.get(dirPath, fileName));
}
private File createFile (String dirPath, String fileName, String fileContent) throws Exception {
Path p = Paths.get(dirPath, fileName);
Files.createFile(p);
PrintWriter writer = new PrintWriter(p.toFile());
writer.println(fileContent);
writer.flush();
return p.toFile();
}
private <K,V> boolean checkMultimapEquals (Multimap<K,V> a, Multimap<K,V> b) {
boolean equals = true;
for (K key : a.keySet()) {
for (V value : b.get(key)) {
if (!a.get(key).contains(value)) {
return false;
}
}
}
for (K key : b.keySet()) {
for (V value : a.get(key)) {
if (!b.get(key).contains(value)) {
return false;
}
}
}
return true;
}
/**
* Sets up a miniature file system in our working directory for testing purposes.
*/
@Before
public void setUp() throws Exception {
Path p = Paths.get(System.getProperty("user.dir"), DIR_NAME);
directory = Files.createDirectory(p).toFile();
String directoryPath = directory.getAbsolutePath();
createDirectory(directoryPath, DIR1);
createDirectory(directoryPath, DIR2);
createDirectory(directoryPath, DIR3);
String dir1Path = Paths.get(directoryPath, DIR1).toString();
createDirectory(dir1Path, DIR1);
createDirectory(dir1Path, DIR2);
dir1File1 = createFile(dir1Path, FILE1, FILE_CONTENT1);
dir1File2 = createFile(dir1Path, FILE2, FILE_CONTENT1);
dir1File3 = createFile(dir1Path, FILE3, FILE_CONTENT3);
String dir1Subdirpath = Paths.get(dir1Path, DIR1).toString();
createDirectory(dir1Subdirpath, DIR1);
createDirectory(dir1Subdirpath, DIR2);
dir1Sub1File4 = createFile(dir1Subdirpath, FILE4, FILE_CONTENT2);
dir1Sub2File1 = createFile(Paths.get(dir1Subdirpath, DIR1).toString(), FILE1, FILE_CONTENT1);
String dir2Path = Paths.get(directoryPath, DIR2).toString();
dir2File4 = createFile(dir2Path, FILE4, FILE_CONTENT4);
dir2File1 = createFile(dir2Path, FILE1, FILE_CONTENT3);
dir2File2 = createFile(dir2Path, FILE2, FILE_CONTENT2);
String dir3Path = Paths.get(directoryPath, DIR3).toString();
dir3File1 = createFile(dir3Path, FILE1, FILE_CONTENT4);
dir3File2 = createFile(dir3Path, FILE2, FILE_CONTENT4);
dir3File3 = createFile(dir3Path, FILE3, FILE_CONTENT1);
dir3File4 = createFile(dir3Path, FILE4, FILE_CONTENT2);
}
/**
* Removes the temporary folders.
*/
@After
public void tearDown() throws Exception {
rm(directory);
directory = null;
}
/**
* Tests DuplicateFinder.findDuplicatesByChecksum for correctness. Files are considered duplicates with the same checksum, and recursion is on.
*/
@Test
public void testFindDuplicatesByChecksum() {
SortFile directorySort = new DuplicateFinder(directory);
Multimap<File,File> testMap = directorySort.findDuplicatesByChecksum(true);
Multimap<File,File> knownMap = HashMultimap.create();
knownMap.put(dir1File1, dir1File2);
knownMap.put(dir1File1, dir1Sub2File1);
knownMap.put(dir1File1, dir3File3);
knownMap.put(dir1File2, dir1File1);
knownMap.put(dir1File2, dir1Sub2File1);
knownMap.put(dir1File2, dir3File3);
knownMap.put(dir1File3, dir2File1);
knownMap.put(dir1Sub1File4, dir2File2);
knownMap.put(dir1Sub1File4, dir3File4);
knownMap.put(dir1Sub2File1, dir1File1);
knownMap.put(dir1Sub2File1, dir1File2);
knownMap.put(dir1Sub2File1, dir3File3);
knownMap.put(dir2File1, dir1File3);
knownMap.put(dir2File2, dir1Sub1File4);
knownMap.put(dir2File2, dir3File4);
knownMap.put(dir2File4, dir3File1);
knownMap.put(dir2File4, dir3File2);
knownMap.put(dir3File1, dir2File4);
knownMap.put(dir3File1, dir3File2);
knownMap.put(dir3File2, dir2File4);
knownMap.put(dir3File2, dir3File1);
knownMap.put(dir3File3, dir1File1);
knownMap.put(dir3File3, dir1File2);
knownMap.put(dir3File3, dir1Sub2File1);
knownMap.put(dir3File4, dir1Sub1File4);
knownMap.put(dir3File4, dir2File2);
assertTrue(checkMultimapEquals(testMap, knownMap));
}
/**
* Tests DuplicateFinder.findDuplicatesByFilename for correctness. Files are considered duplicates with the same filename, and recursion is on.
*/
@Test
public void testFindDuplicatesByFilename () {
SortFile directorySort = new DuplicateFinder(directory);
Multimap<File,File> testMap = directorySort.findDuplicatesByFilename(true);
Multimap<File,File> knownMap = HashMultimap.create();
knownMap.put(dir1File1, dir1Sub2File1);
knownMap.put(dir1File1, dir2File1);
knownMap.put(dir1File1, dir3File1);
knownMap.put(dir1File2, dir2File2);
knownMap.put(dir1File2, dir3File2);
knownMap.put(dir1File3, dir3File3);
knownMap.put(dir1Sub1File4, dir2File4);
knownMap.put(dir1Sub1File4, dir3File4);
knownMap.put(dir1Sub2File1, dir1File1);
knownMap.put(dir1Sub2File1, dir2File1);
knownMap.put(dir1Sub2File1, dir3File1);
knownMap.put(dir2File1, dir1File1);
knownMap.put(dir2File1, dir1Sub2File1);
knownMap.put(dir2File1, dir3File1);
knownMap.put(dir2File2, dir1File2);
knownMap.put(dir2File2, dir3File2);
knownMap.put(dir2File4, dir1Sub1File4);
knownMap.put(dir2File4, dir3File4);
knownMap.put(dir3File1, dir1File1);
knownMap.put(dir3File1, dir1Sub2File1);
knownMap.put(dir3File1, dir2File1);
knownMap.put(dir3File2, dir1File2);
knownMap.put(dir3File2, dir2File2);
knownMap.put(dir3File3, dir1File3);
knownMap.put(dir3File4, dir1Sub1File4);
knownMap.put(dir3File4, dir2File4);
assertTrue(checkMultimapEquals(testMap, knownMap));
}
/**
* Tests DuplicateFinder.findDuplicatesBySize for correctness. Files are considered duplicates with the same size, and recursion is on.
*/
@Test
public void testFindDuplicatesBySize () {
SortFile directorySort = new DuplicateFinder(directory);
Multimap<File,File> testMap = directorySort.findDuplicatesBySize(true);
Multimap<File,File> knownMap = HashMultimap.create();
knownMap.put(dir1File1, dir1File2);
knownMap.put(dir1File1, dir1Sub1File4);
knownMap.put(dir1File1, dir1Sub2File1);
knownMap.put(dir1File1, dir2File2);
knownMap.put(dir1File1, dir3File3);
knownMap.put(dir1File1, dir3File4);
knownMap.put(dir1File2, dir1File1);
knownMap.put(dir1File2, dir1Sub2File1);
knownMap.put(dir1File2, dir1Sub1File4);
knownMap.put(dir1File2, dir2File2);
knownMap.put(dir1File2, dir3File3);
knownMap.put(dir1File2, dir3File4);
knownMap.put(dir1File3, dir2File4);
knownMap.put(dir1File3, dir2File1);
knownMap.put(dir1File3, dir3File1);
knownMap.put(dir1File3, dir3File2);
knownMap.put(dir1Sub1File4, dir1File1);
knownMap.put(dir1Sub1File4, dir1File2);
knownMap.put(dir1Sub1File4, dir1Sub2File1);
knownMap.put(dir1Sub1File4, dir2File2);
knownMap.put(dir1Sub1File4, dir3File3);
knownMap.put(dir1Sub1File4, dir3File4);
knownMap.put(dir2File1, dir2File4);
knownMap.put(dir2File1, dir1File3);
knownMap.put(dir2File1, dir3File1);
knownMap.put(dir2File1, dir3File2);
knownMap.put(dir2File2, dir1File1);
knownMap.put(dir2File2, dir1File2);
knownMap.put(dir2File2, dir1Sub1File4);
knownMap.put(dir2File2, dir1Sub2File1);
knownMap.put(dir2File2, dir3File3);
knownMap.put(dir2File2, dir3File4);
knownMap.put(dir2File4, dir2File1);
knownMap.put(dir2File4, dir1File3);
knownMap.put(dir2File4, dir3File1);
knownMap.put(dir2File4, dir3File2);
knownMap.put(dir3File1, dir1File3);
knownMap.put(dir3File1, dir2File4);
knownMap.put(dir3File1, dir2File1);
knownMap.put(dir3File1, dir3File2);
knownMap.put(dir3File2, dir1File3);
knownMap.put(dir3File2, dir2File1);
knownMap.put(dir3File2, dir2File4);
knownMap.put(dir3File2, dir3File1);
knownMap.put(dir3File3, dir1File1);
knownMap.put(dir3File3, dir1File2);
knownMap.put(dir3File3, dir1Sub1File4);
knownMap.put(dir3File3, dir1Sub2File1);
knownMap.put(dir3File3, dir2File2);
knownMap.put(dir3File3, dir3File4);
knownMap.put(dir3File4, dir1File1);
knownMap.put(dir3File4, dir1File2);
knownMap.put(dir3File4, dir1Sub1File4);
knownMap.put(dir3File4, dir1Sub2File1);
knownMap.put(dir3File4, dir2File2);
knownMap.put(dir3File4, dir3File3);
assertTrue(checkMultimapEquals(testMap, knownMap));
}
/**
* Tests DuplicateFinder.findDuplicates for correctness. The specified directory contains no files, and recursion is off. This is a test to make sure findDuplicates works properly with no files.
*/
@Test
public void testFindDuplicatesNull () {
SortFile directorySort = new DuplicateFinder(directory);
Multimap<File,File> testMap = directorySort.findDuplicatesBySize(true);
Multimap<File,File> knownMap = HashMultimap.create();
assertTrue(checkMultimapEquals(testMap, knownMap));
}
/**
* Tests DuplicateFinder.findDuplicates for correctness. Files are considered duplicates with the same size, and recursion is off.
*/
@Test
public void testFindDuplicatesNoRecursion () {
File dir = Paths.get(directory.getAbsolutePath(), DIR3).toFile();
SortFile directorySort = new DuplicateFinder(dir);
Multimap<File,File> testMap = directorySort.findDuplicatesBySize(false);
Multimap<File,File> knownMap = HashMultimap.create();
knownMap.put(dir3File1, dir3File2);
knownMap.put(dir3File2, dir3File1);
knownMap.put(dir3File3, dir3File4);
knownMap.put(dir3File4, dir3File3);
assertTrue(checkMultimapEquals(testMap, knownMap));
}
}<file_sep>/burum-brown/src/test/java/com/agile/findduplicates/FileTest.java
package com.agile.findduplicates;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static junit.framework.Assert.*;
/**
* Unit test for Navigational File Manager.
*/
public class FileTest {
private static final String DIR_NAME = "NavigationalFileManager";
private static final String DIR1 = "dir1";
private static final String DIR2 = "dir2";
private static final String DIR3 = "dir3";
private static final String FILE1 = "test.txt";
private static final String FILE2 = "duplicate.txt";
private File directory;
public boolean rm (File file) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (!rm(f)) {
return false;
}
}
}
return file.delete();
}
@Before
public void setup () {
try {
Path p = Paths.get(System.getProperty("user.dir"), DIR_NAME);
directory = Files.createDirectory(p).toFile();
String directoryPath = directory.getAbsolutePath();
Files.createDirectory(Paths.get(directoryPath, DIR1));
String dir1Path = Paths.get(directoryPath, DIR1).toString();
Files.createFile(Paths.get(dir1Path, FILE1));
Files.createFile(Paths.get(dir1Path, FILE2));
Files.createDirectory(Paths.get(directoryPath, DIR2));
Files.createFile(Paths.get(directoryPath, FILE1));
Files.createDirectory(Paths.get(directoryPath, DIR3));
} catch (IOException e) {
System.out.println("Exception");
System.exit(1);
}
}
@After
public void tearDown () {
rm(directory);
directory = null;
}
@Test
public void testLs () {
String[] files = {
DIR1, DIR2, DIR3, FILE1
};
FileManager fm = new NavigationalFileManager(directory.getAbsolutePath());
String[] list = fm.ls();
for (int i = 0; i < list.length; i++) {
assertEquals(list[i],files[i]);
}
}
@Test
public void testCd () {
FileManager fm = new NavigationalFileManager(directory.getAbsolutePath());
fm.cd(DIR1);
assertEquals(DIR1, fm.currentDir());
fm.cd();
assertEquals(directory.getName().toString(), fm.currentDir());
}
@Test
public void testDuplicates () {
FileManager fm = new NavigationalFileManager(directory.getAbsolutePath());
String[] duplicates = fm.findDuplicates();
String[] files = {
FILE1, FILE2
};
for (int i = 0; i < duplicates.length; i++) {
assertEquals(duplicates[i],files[i]);
}
}
@Test
public void testRm () {
FileManager fm = new NavigationalFileManager(directory.getAbsolutePath());
assertTrue(fm.rm(FILE1));
boolean remains = false;
for (String s : fm.ls()) {
if (s.equals(FILE1)) {
remains = true;
}
}
assertFalse(remains);
}
@Test
public void testPwd () {
FileManager fm = new NavigationalFileManager(directory.getAbsolutePath());
assertEquals(directory.getAbsolutePath(), fm.pwd());
}
@Test
public void testCurrentDir () {
FileManager fm = new NavigationalFileManager(directory.getAbsolutePath());
assertEquals(directory.getName(), fm.currentDir());
}
@Test
public void testRmdir () {
String name = directory.getName();
FileManager fm = new NavigationalFileManager(directory.getParentFile().getAbsolutePath());
assertTrue(fm.rmdir(name));
}
}
<file_sep>/README.md
Duplicate-File-Finder
=====================
|
aee5b6a11d248db90fc10fb4db96dbceb79c3cd1
|
[
"Markdown",
"Java"
] | 3 |
Java
|
BenBurum/Duplicate-File-Finder
|
f14b3fbd3f7be69f9cd874cc5ce1829244e6ac79
|
1da879083d3d4aa10e3cf439f644a5d34167dabf
|
refs/heads/master
|
<file_sep>using System;
using System.Collections;
using UnityEngine;
using Assets.Scripts.Player;
using UnityEngine.UI;
using UnityEngine.InputSystem;
using System.Linq;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
#region PlayerMovement Properties
// public player values set in editor
[SerializeField] private Transform _transform = default;
[SerializeField] private BoxCollider2D _boxCollider = default;
[SerializeField] private Rigidbody2D _rigidBody = default;
[SerializeField] private PlayerAnimationController _animation = default;
[SerializeField] private SoundManager _soundManager = default;
[SerializeField] private PhysicsDatabase _physicsDatabase = default;
[SerializeField] private GameState _gameState = default;
[SerializeField] private LayerMask _terrainLayer = default;
[SerializeField] private LayerMask _harmLayer = default;
[SerializeField] private ParticleSystem _dashParticles = default;
[SerializeField] private ParticleSystem _walkParticles = default;
[SerializeField] private Text _gameMessageText = default;
[SerializeField] private GameObject _loadingScreen = default;
[SerializeField] private Text _loadingText = default;
[SerializeField] private Timer _timer = default;
[SerializeField] private int _maxJumps = default;
[SerializeField] private int _yPositionLimit = default;
[SerializeField] private float _stretchConstant = default;
public Transform Transform => _transform;
public InputMaster _controls;
private PlayerState _playerState = default;
private Action<bool, bool, bool, bool> UpdateAnimationState = default;
private Action DeathAnimation = default;
private int _speed = default;
private int _jumpForce = default;
private int _downForce = default;
private int _verticalComponentDashForce = default;
private float _gravityScale = default;
private int _orbForceMultiplier = default;
private Vector3 _activeOrbPosition = new Vector3(0, 0, 0);
private Vector3 _respawnPosition = default;
private float _horizontalAxis = 0;
private float _verticalAxis = 0;
private bool _play;
#endregion
private void Awake() {
_rigidBody.gravityScale = _gravityScale;
_rigidBody.angularDrag = _physicsDatabase.PlayerAngularDrag;
_rigidBody.drag = _physicsDatabase.PlayerLinearDrag;
_rigidBody.mass = _physicsDatabase.PlayerMass;
_speed = _physicsDatabase.PlayerSpeed;
_jumpForce = _physicsDatabase.PlayerJumpForce;
_downForce = _physicsDatabase.PlayerDownForce;
_verticalComponentDashForce = _physicsDatabase.PlayerVerticalComponentDashForce;
_gravityScale = _physicsDatabase.GravityScale;
_orbForceMultiplier = _physicsDatabase.OrbForceMultiplier;
_respawnPosition = _gameState.Checkpoint;
UpdateAnimationState += _animation.SetAnimationState;
DeathAnimation += _animation.SetDeathState;
_gameState.OnUpdateGameState += UpdateRespawnPosition;
_controls = new InputMaster();
_controls.Player.Orb.canceled += context =>
{
_playerState.slingShotReleased = true;
};
}
private void Start()
{
_playerState.currentDirectionFacing = DirectionFacing.Right;
_playerState.currentMovementState = MovementState.Default;
_transform.position = _respawnPosition;
_play = false;
StartCoroutine(PressAnyToPlay());
}
/**
* Capture inputs and determine current movement state
*/
private void Update()
{
if (!_play) return;
// stretches the player sprite based on its vertical velocity
_transform.localScale = new Vector3(4 + _rigidBody.velocity.x/ _stretchConstant, 4 - _rigidBody.velocity.y / _stretchConstant, 1);
if (_transform.position.y < _yPositionLimit && !_playerState.isDead) { Died(); }
// Check if on ground or wall
CheckTouchingTerrain();
// dash resets and wall climb when player touches ground
if (_playerState.onGround)
{
_playerState.canDash = true;
_playerState.canWallClimb = true;
if (_walkParticles.isPaused || _walkParticles.isStopped) _walkParticles.Play();
} else
{
_walkParticles.Stop();
}
// turn gravity back on when done sling shot
if (!_playerState.slingShotActive)
{
_rigidBody.gravityScale = _gravityScale;
}
else
{
_soundManager.PlaySoundEffect(SoundEffects.Orb);
}
_horizontalAxis = _controls.Player.Movement.ReadValue<Vector2>().x;
_verticalAxis = _controls.Player.Movement.ReadValue<Vector2>().y;
bool jumpKeyPressed = _controls.Player.Jump.triggered;
bool dashKeyPressed = _controls.Player.Dash.triggered;
bool pauseButtonPressed = _controls.Player.Pause.triggered;
bool slingShotPressed = _controls.Player.Orb.ReadValue<float>() > 0.1f ? true : false;
if (slingShotPressed)
{
_playerState.orbPulled = true;
}
else if (_playerState.slingShotReleased)
{
_playerState.orbPulled = false;
}
if (pauseButtonPressed && !GameManager.isGamePaused)
{
GameManager.Instance.PauseGame();
}
else if (pauseButtonPressed && GameManager.isGamePaused)
{
GameManager.Instance.ResumeGame();
}
else if (slingShotPressed && _playerState.isOrbActive)
{
_playerState.currentMovementState = MovementState.SlingShotActive;
}
else if (_playerState.slingShotReleased)
{
_playerState.slingShotActive = false;
_playerState.currentMovementState = MovementState.Default;
}
else if (jumpKeyPressed)
{
_playerState.slingShotActive = false;
_playerState.currentMovementState = MovementState.JumpActive;
}
else if (dashKeyPressed && _playerState.canDash)
{
_playerState.slingShotActive = false;
_playerState.currentMovementState = MovementState.DashActive;
_playerState.canDash = false;
}
if (_playerState.isOrbActive)
{
Debug.DrawLine(_activeOrbPosition, _transform.position, Color.red);
}
if (!_playerState.isDead) UpdateAnimationState(_playerState.onGround, _playerState.onWall, _playerState.orbPulled, _playerState.isOrbActive);
_playerState.slingShotReleased = false;
}
/**
* Determine which physics movement operations to execture based on current movement states
*/
private void FixedUpdate() {
switch (_playerState.currentMovementState) {
case MovementState.DashActive: Horizontal_Dash(); break;
case MovementState.JumpActive: Vertical_Jump(); break;
case MovementState.SlingShotActive: SlingShot(); break;
case MovementState.Default:
{
Horizontal_Move();
Vertical_Move();
break;
}
}
}
#region Movement Methods
/**
* Moves the player object left or right
*/
private void Horizontal_Move() {
UpdateDirectionFacing();
var forceVector = _horizontalAxis * _speed;
_rigidBody.AddForce(new Vector2(forceVector, 0));
}
/**
* Gives the player quick burst of horizontal movement in the direction the player is facing over a fixed time interval
*/
private void Horizontal_Dash() {
_rigidBody.velocity = new Vector2(0, 0);
_rigidBody.AddForce(new Vector2(((float)_playerState.currentDirectionFacing) * _jumpForce, _verticalComponentDashForce));
_dashParticles.Play();
_soundManager.PlaySoundEffect(SoundEffects.Dash);
GameManager.Instance.CameraMovementController.ShakeScreen();
_playerState.currentMovementState = MovementState.Default;
}
/**
* Accelerate the player vertically up
*/
private void Vertical_Jump() {
if (_playerState.onWall) {
Vertical_WallJump();
return;
}
// reset jumps when on the ground
if (_playerState.onGround) {
_playerState.jumpCounter = 0;
}
if (_playerState.jumpCounter < _maxJumps) {
_rigidBody.velocity = new Vector2(_rigidBody.velocity.x, 0);
_rigidBody.AddForce(new Vector2(0, _jumpForce));
_playerState.jumpCounter++;
_soundManager.PlaySoundEffect(SoundEffects.Jump);
}
_playerState.currentMovementState = MovementState.Default;
}
/**
* Accelerate the player away from the wall in an upward direction
*/
private void Vertical_WallJump() {
_rigidBody.velocity = new Vector2(0, 0);
_rigidBody.AddForce(new Vector2(((float) _playerState.currentDirectionFacing) * _jumpForce, _jumpForce));
_playerState.jumpCounter = 1;
_soundManager.PlaySoundEffect(SoundEffects.WallJump);
_playerState.currentMovementState = MovementState.Default;
}
/**
* Determine which vertical movement should be executed
*/
private void Vertical_Move() {
if (_verticalAxis > 0 && _playerState.onWall) {
Vertical_WallClimb();
} else if (_verticalAxis < 0 && !_playerState.onWall && !_playerState.onGround) {
Vertical_AccelerateDown();
}
}
/**
* Makes player fall faster
*/
private void Vertical_AccelerateDown() {
_rigidBody.AddForce(new Vector2(0, -_downForce));
}
/**
* Move player upward along a wall
*/
private void Vertical_WallClimb() {
if (_playerState.canWallClimb) {
_rigidBody.velocity = Vector2.zero;
_rigidBody.AddForce(new Vector2(0, _jumpForce));
_playerState.canWallClimb = false;
}
}
private void SlingShot() {
if (_playerState.isOrbActive) {
if (!_playerState.slingShotActive) {
_playerState.jumpCounter = 1;
_playerState.slingShotActive = true;
_rigidBody.gravityScale = 0;
}
Vector2 direction = (_activeOrbPosition - transform.position).normalized;
_rigidBody.AddForce(direction * _orbForceMultiplier);
}
}
#endregion
/**
* Checks to see if player is touching the ground or walls
*/
private void CheckTouchingTerrain()
{
// max distance from the collider in which to register a collision
float touchingGroundBuffer = 0.1f;
// creates small area just underneath the Player Collider and checks if any object on the terrain layer is inside this area
_playerState.onGround = Physics2D.BoxCast(_boxCollider.bounds.center, _boxCollider.bounds.size, 0f, Vector2.down, touchingGroundBuffer, _terrainLayer.value);
// onGround take priority over onWall;
if (_playerState.onGround) {
_playerState.onLeftWall = false;
_playerState.onRightWall = false;
return;
}
// creates small area just to the left and right of the Player Collider and checks if any object on the terrain layer is inside this area
_playerState.onLeftWall = Physics2D.BoxCast(_boxCollider.bounds.center, _boxCollider.bounds.size, 0f, Vector2.left, touchingGroundBuffer, _terrainLayer.value);
_playerState.onRightWall = Physics2D.BoxCast(_boxCollider.bounds.center, _boxCollider.bounds.size, 0f, Vector2.right, touchingGroundBuffer, _terrainLayer.value);
UpdateDirectionFacing();
}
/**
* correctly rotates player object depending on which way it is moving
*/
private void UpdateDirectionFacing() {
if (_playerState.onWall) {
// if on wall face away from the wall
if (_playerState.onLeftWall) {
transform.rotation = new Quaternion(0, 0, 0, 0);
_playerState.currentDirectionFacing = DirectionFacing.Right;
} else {
transform.rotation = new Quaternion(0, 180, 0, 0);
_playerState.currentDirectionFacing = DirectionFacing.Left;
}
} else if (_horizontalAxis < 0 && _playerState.currentDirectionFacing == DirectionFacing.Right) {
transform.rotation = new Quaternion(0, 180, 0, 0);
_playerState.currentDirectionFacing = DirectionFacing.Left;
} else if (_horizontalAxis > 0 && _playerState.currentDirectionFacing == DirectionFacing.Left) {
transform.rotation = new Quaternion(0, 0, 0, 0);
_playerState.currentDirectionFacing = DirectionFacing.Right;
}
}
public void SetActiveOrb(bool isActive, Vector3 activeOrbPos) {
var distanceToCurrentOrb = Vector2.Distance(_activeOrbPosition, _transform.position);
var distanceToNewOrb = Vector2.Distance(activeOrbPos, _transform.position);
if (_activeOrbPosition.Equals(Vector3.zero) || distanceToNewOrb.CompareTo(distanceToCurrentOrb) <= 0)
{
_activeOrbPosition = activeOrbPos;
}
_playerState.isOrbActive = isActive;
}
private void Died()
{
// probably wait until death animation is finished before setting _transform.position
_playerState.currentMovementState = MovementState.Default;
_playerState.isDead = true;
_rigidBody.constraints |= RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY;
DeathAnimation();
StartCoroutine(DeathTimer());
}
IEnumerator DeathTimer()
{
yield return new WaitForSeconds(1);
_transform.position = _respawnPosition;
_rigidBody.constraints ^= RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY;
_playerState.isDead = false;
}
IEnumerator PressAnyToPlay()
{
yield return new WaitUntil(() =>
SceneManager.GetSceneByName("Tutorial").isLoaded
|| SceneManager.GetSceneByName("Part_1").isLoaded
|| SceneManager.GetSceneByName("Part_2").isLoaded
);
_loadingText.text = "Press Any Key to Start";
var waitForAnyPress = new InputAction(binding: "/*/<button>");
waitForAnyPress.Enable();
yield return new WaitUntil(() => waitForAnyPress.triggered);
_loadingScreen.SetActive(false);
_timer.StartTimer();
_play = true;
}
private void UpdateRespawnPosition()
{
_respawnPosition = _gameState.Checkpoint;
}
#region GameObject Events
void OnCollisionEnter2D(Collision2D col)
{
if ((1 << col.gameObject.layer) == _harmLayer.value && !_playerState.isDead)
{
Died();
}
}
void OnTriggerEnter2D(Collider2D col)
{
var sign = col.gameObject.GetComponent<MessageSignController>();
if (sign != null)
{
_gameMessageText.text = sign.getMessage();
}
}
void OnTriggerExit2D(Collider2D col)
{
_gameMessageText.text = String.Empty;
}
void OnEnable()
{
_controls.Enable();
}
void OnDsiable()
{
_controls.Disable();
}
private void OnDestroy()
{
UpdateAnimationState -= _animation.SetAnimationState;
DeathAnimation -= _animation.SetDeathState;
_gameState.OnUpdateGameState -= UpdateRespawnPosition;
}
#endregion
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Goal : MonoBehaviour
{
[SerializeField] private Text _messageText = default;
[SerializeField] private GameState _gameState = default;
private void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
GameManager.Instance.Timer.StopTimer();
TimeSpan bestTime = TimeSpan.FromSeconds(_gameState.BestTime);
TimeSpan currentTime = TimeSpan.FromSeconds(_gameState.CurrentTime);
_messageText.text = string.Format(
"Best Time {0}\nCurrent Time {1}",
bestTime.ToString("mm':'ss'.'ff"),
currentTime.ToString("mm':'ss'.'ff")
);
}
}
private void OnTriggerExit2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
_messageText.text = string.Empty;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovementController : MonoBehaviour
{
[SerializeField] private Transform _playerTransform = default;
[SerializeField] private Camera _cameraComponent = default;
[SerializeField] private float _screenShakeAmount = default;
[SerializeField] private float _screenShakeLength = default;
private short _screenBufferY = 2;
private short _screenBufferX = 5;
private short _orthographicSize = 10;
private short _zPosition = -10;
void Awake()
{
_cameraComponent.orthographicSize = _orthographicSize;
}
void Update()
{
// Keeps player sprite within screen, but does not directly follow
float x = transform.position.x;
float y = transform.position.y;
float diffX = _playerTransform.position.x - x;
float diffY = _playerTransform.position.y - y;
if (diffX > _screenBufferX)
{
x = _playerTransform.position.x - _screenBufferX;
}
else if (diffX < -_screenBufferX)
{
x = _playerTransform.position.x + _screenBufferX;
}
if (diffY > _screenBufferY)
{
y = _playerTransform.position.y - _screenBufferY;
}
else if (diffY < -_screenBufferY)
{
y = _playerTransform.position.y + _screenBufferY;
}
transform.position = new Vector3(x, y, _zPosition);
}
// screen shake code obtained from https://www.youtube.com/watch?v=Y8nOgEpnnXo
public void ShakeScreen()
{
InvokeRepeating("BeginShake", 0f, 0.1f);
Invoke("StopShake", _screenShakeLength);
}
private void BeginShake()
{
if (_screenShakeAmount > 0)
{
Vector3 cameraPosition = _cameraComponent.transform.position;
float offsetX = Random.value * _screenShakeAmount * 2 - _screenShakeAmount;
float offsetY = Random.value * _screenShakeAmount * 2 - _screenShakeAmount;
cameraPosition.x += offsetX;
cameraPosition.y += offsetY;
_cameraComponent.transform.position = cameraPosition;
}
}
private void StopShake()
{
CancelInvoke("BeginShake");
_cameraComponent.transform.localPosition = Vector3.zero;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAnimationController : MonoBehaviour
{
private enum SurfaceMapping : int
{
Death = 0,
Orb = 1,
Ground = 2,
Wall = 3,
Air = 4
}
[SerializeField] private BoxCollider2D _boxCollider = default;
[SerializeField] private Rigidbody2D _rigidBody = default;
[SerializeField] private Animator _animator = default;
public void SetAnimationState(bool onGround, bool onWall, bool fPressed, bool isOrbActive)
{
bool orbPulling = fPressed && isOrbActive;
SurfaceMapping mapping = default;
if (orbPulling)
{
mapping = SurfaceMapping.Orb;
}
else if (!orbPulling && onGround)
{
mapping = SurfaceMapping.Ground;
}
else if (!orbPulling && !onGround && onWall)
{
mapping = SurfaceMapping.Wall;
}
else if (!orbPulling && !onGround && !onWall)
{
mapping = SurfaceMapping.Air;
}
var velocity = Mathf.Abs(_rigidBody.velocity.magnitude);
var angle = Vector3.SignedAngle(Vector3.right, _rigidBody.velocity, Vector3.forward);
_animator.SetInteger("Surface", (int) mapping);
_animator.SetFloat("Speed", velocity);
_animator.SetFloat("VelocityAngle", angle);
UpdateBoxCollider(mapping, velocity, angle);
}
public void SetDeathState()
{
_animator.SetInteger("Surface", (int) SurfaceMapping.Death);
}
private void UpdateBoxCollider(SurfaceMapping mapping, double velocity, double angle)
{
// AirDash bounds
// TODO: refactor out these "magic numbers" into consts
if (mapping == SurfaceMapping.Air && velocity > 10 && (angle < 0 && angle > -45 || angle < -135 && angle > -180))
{
_boxCollider.size = new Vector2(0.19f, 0.15f);
_boxCollider.offset = new Vector2(0, 0.075f);
}
else if (mapping == SurfaceMapping.Orb && velocity > 0.01)
{
_boxCollider.size = new Vector2(0.19f, 0.19f);
_boxCollider.offset = new Vector2(0, 0);
}
else if (mapping == SurfaceMapping.Wall && velocity > 0.01 && angle > 80 && angle < 100)
{
_boxCollider.size = new Vector2(0.19f, 0.35f);
_boxCollider.offset = new Vector2(0, 0.17f);
}
else
{
_boxCollider.size = new Vector2(0.19f, 0.3f);
_boxCollider.offset = new Vector2(0, 0.145f);
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class OptionsMenuController : MonoBehaviour
{
[SerializeField] private GameSettings _gameSettings = default;
[SerializeField] private Slider _soundEffects = default;
[SerializeField] private Slider _wind = default;
void Start()
{
_soundEffects.value = _gameSettings.SoundEffectsVolume;
_wind.value = _gameSettings.WindVolume;
}
void Update()
{
if (_gameSettings.SoundEffectsVolume != _soundEffects.value)
{
_gameSettings.SoundEffectsVolume = _soundEffects.value;
}
if (_gameSettings.SoundEffectsVolume != _wind.value)
{
_gameSettings.WindVolume = _wind.value;
}
}
}
<file_sep>using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenuController : MonoBehaviour
{
public GameObject _eventSystem = default;
[SerializeField] private GameState _gameState = default;
[SerializeField] private GameObject _playFromCheckpointButton = default;
[SerializeField] private Text _bestTimeText = default;
private bool isBestTimeTextShowing = false;
void Start()
{
if (_gameState.Checkpoint == new Vector3(-6, -4.45f, -1))
{
_playFromCheckpointButton.SetActive(false);
} else
{
_playFromCheckpointButton.SetActive(true);
}
}
public void PlayFromCheckpoint()
{
LoadGame();
}
public void PlayGame()
{
_gameState.Checkpoint = new Vector3(-6, -4.45f, -1);
_gameState.CurrentTime = 0f;
LoadGame();
}
public void Quit()
{
Application.Quit();
}
public void ToggleBestTimeText()
{
if (isBestTimeTextShowing)
{
_bestTimeText.text = string.Empty;
isBestTimeTextShowing = false;
}
else
{
TimeSpan bestTime = TimeSpan.FromSeconds(_gameState.BestTime);
_bestTimeText.text = string.Format(
"Best Time : {0}",
bestTime.ToString("mm':'ss'.'ff")
);
isBestTimeTextShowing = true;
}
}
private void LoadGame()
{
_eventSystem.SetActive(false);
StartCoroutine(GameManager.Instance.SceneController.LoadGame());
}
}
<file_sep>namespace Assets.Scripts.Player
{
enum DirectionFacing : int
{
Right = 1,
Left = -1
}
}<file_sep># Sky-Runner
A 2D platforming game made by <NAME> and <NAME>.
Link: https://sandychip06.itch.io/sky-runner
Gameplay: https://youtu.be/87SDMKVCzjw
<file_sep>using UnityEngine;
public class Checkpoint : MonoBehaviour
{
[SerializeField] private ParticleSystem _paticles = default;
[SerializeField] private GameState _gameState = default;
private void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
if (gameObject.activeSelf)
{
_gameState.Checkpoint = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y - 1, -1);
_paticles.Play();
}
}
}
}<file_sep>// Source/References: https://github.com/amel-unity/Multi-Scene-workflow/blob/master/Assets/Creator%20Kit%20-%20FPS/Scripts/System/ScenePartLoader.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public enum CheckMethod
{
Distance,
Trigger
}
public class SceneLoader : MonoBehaviour
{
public CheckMethod _checkMethod;
[SerializeField] private Transform _player = default;
[SerializeField] private float _loadRange = default;
// Scene state
private bool _isLoaded;
private bool _shouldLoad;
void Start()
{
// verify if the scene is already open to avoid opening a scene twice
if (SceneManager.sceneCount > 0)
{
for (int i = 0; i < SceneManager.sceneCount; ++i)
{
Scene scene = SceneManager.GetSceneAt(i);
if (scene.name == gameObject.name)
{
_isLoaded = true;
}
}
}
}
void Update()
{
// Checking which method to use
if (_checkMethod == CheckMethod.Distance)
{
DistanceCheck();
}
else if (_checkMethod == CheckMethod.Trigger)
{
TriggerCheck();
}
}
void DistanceCheck()
{
// Checking if the player is within the range
if (Vector3.Distance(_player.position, transform.position) < _loadRange)
{
LoadScene();
}
else
{
UnLoadScene();
}
}
void LoadScene()
{
if (!_isLoaded)
{
// Loading the scene, using the gameobject name as it's the same as the name of the scene to load
SceneManager.LoadSceneAsync(gameObject.name, LoadSceneMode.Additive);
// We set it to true to avoid loading the scene twice
_isLoaded = true;
}
}
void UnLoadScene()
{
if (_isLoaded)
{
SceneManager.UnloadSceneAsync(gameObject.name);
_isLoaded = false;
}
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
_shouldLoad = true;
}
}
private void OnTriggerExit2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
_shouldLoad = false;
}
}
void TriggerCheck()
{
// _shouldLoad is set from the Trigger methods
if (_shouldLoad)
{
LoadScene();
}
else
{
UnLoadScene();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuHelpers
{
public static void Transition(GameObject from, GameObject to)
{
from.SetActive(false);
to.SetActive(true);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CreateAssetMenu(fileName = "PhysicsDatabase", menuName = "Databases/PhysicsDatabase")]
public class PhysicsDatabase : ScriptableObject
{
// NOTE: should eventually refactor most of these values into a set of global constants
[SerializeField] private float _gravityScale = default;
[SerializeField] private float _playerMass = default;
[SerializeField] private float _playerAngularDrag = default;
[SerializeField] private float _playerLinearDrag = default;
[SerializeField] private int _playerSpeed = default;
[SerializeField] private int _playerJumpForce = default;
[SerializeField] private int _playerDownForce = default;
[SerializeField] private int _playerVerticalComponentDashForce = default;
[SerializeField] private int _orbForceMultiplier = default;
[SerializeField] private short _orbRange = default;
public float GravityScale => _gravityScale;
public float PlayerMass => _playerMass;
public float PlayerAngularDrag => _playerAngularDrag;
public float PlayerLinearDrag => _playerLinearDrag;
public int PlayerSpeed => _playerSpeed;
public int PlayerJumpForce => _playerJumpForce;
public int PlayerDownForce => _playerDownForce;
public int PlayerVerticalComponentDashForce => _playerVerticalComponentDashForce;
public int OrbForceMultiplier => _orbForceMultiplier;
public short OrbRange => _orbRange;
}<file_sep>namespace Assets.Scripts.Player
{
enum MovementState : short
{
Default = 0,
JumpActive = 1,
DashActive = 2,
SlingShotActive = 3
}
}<file_sep>namespace Assets.Scripts.Player
{
struct PlayerState
{
public bool canDash;
public bool canWallClimb;
public bool slingShotActive;
public bool onGround;
public bool onLeftWall;
public bool onRightWall;
public bool orbPulled;
public bool isDead;
public bool slingShotReleased;
public bool isOrbActive;
public int jumpCounter;
public bool onWall
{
get
{
return onLeftWall || onRightWall;
}
}
public DirectionFacing currentDirectionFacing;
public MovementState currentMovementState;
};
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneController : MonoBehaviour
{
void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
public IEnumerator LoadGame()
{
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("Gameplay", LoadSceneMode.Additive);
yield return new WaitUntil(() => asyncOperation.isDone);
if (SceneManager.GetSceneByName("MainMenu").isLoaded)
{
asyncOperation = SceneManager.UnloadSceneAsync("MainMenu");
yield return new WaitUntil(() => asyncOperation.isDone);
}
}
public IEnumerator LoadMainMenu()
{
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync("MainMenu", LoadSceneMode.Additive);
yield return new WaitWhile(() => !asyncOperation.isDone);
if (SceneManager.GetSceneByName("Tutorial").isLoaded)
{
asyncOperation = SceneManager.UnloadSceneAsync("Tutorial");
yield return new WaitUntil(() => asyncOperation.isDone);
}
if (SceneManager.GetSceneByName("Part_1").isLoaded)
{
asyncOperation = SceneManager.UnloadSceneAsync("Part_1");
yield return new WaitUntil(() => asyncOperation.isDone);
}
if (SceneManager.GetSceneByName("Part_2").isLoaded)
{
asyncOperation = SceneManager.UnloadSceneAsync("Part_2");
yield return new WaitUntil(() => asyncOperation.isDone);
}
if (SceneManager.GetSceneByName("Gameplay").isLoaded)
{
asyncOperation = SceneManager.UnloadSceneAsync("Gameplay");
yield return new WaitUntil(() => asyncOperation.isDone);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SlingShotOrbBehavior : MonoBehaviour
{
[SerializeField] private PhysicsDatabase _physicsDatabase = default;
[SerializeField] private Transform _orbRangeIndicator = default;
[SerializeField] private short _orbRangeOverride = 0;
private PlayerController _playerController = default;
private Transform _playerTransform;
private short _orbRange = default;
private bool _isActive = false;
void Awake()
{
if (_orbRangeOverride != 0)
{
_orbRange = _orbRangeOverride;
}
else
{
_orbRange = _physicsDatabase.OrbRange;
}
_orbRangeIndicator.localScale = new Vector3(4 * _orbRange, 4 * _orbRange, 1);
_playerController = GameManager.Instance.PlayerController;
_playerTransform = _playerController.Transform;
}
void Update()
{
if (Vector2.Distance(transform.position, _playerTransform.position) < _orbRange)
{
_isActive = true;
_playerController.SetActiveOrb(true, transform.position);
}
else if (_isActive)
{
_isActive = false;
_playerController.SetActiveOrb(false, Vector3.zero);
}
if (_isActive)
{
// makes the orb range indicator change colors
Color lightBlue = new Color(0.1f, 0.67f, 1f, 0.4f);
Color darkBlue = new Color(0.4f, 0.4f, 1f, 0.4f);
_orbRangeIndicator.GetComponent<SpriteRenderer>().color = Color.Lerp(lightBlue, darkBlue, Mathf.PingPong(Time.time, 1));
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenuController : MonoBehaviour
{
[SerializeField] private GameState _gameState = default;
[SerializeField] private GameObject _eventSystem = default;
[SerializeField] private Timer _timer = default;
[SerializeField] private GameObject PauseMenu = default;
[SerializeField] private GameObject OptionsMenu = default;
void Start()
{
GameManager.Instance.PauseMenu = gameObject.GetComponent<PauseMenuController>();
hidePauseMenu();
}
public void Resume()
{
GameManager.Instance.ResumeGame();
}
public void ExitToMenu()
{
_gameState.CurrentTime = _timer.ElapsedTime;
_eventSystem.SetActive(false);
Time.timeScale = 1f;
StartCoroutine(GameManager.Instance.SceneController.LoadMainMenu());
}
public void showPauseMenu()
{
PauseMenu.SetActive(true);
OptionsMenu.SetActive(false);
}
public void hidePauseMenu()
{
PauseMenu.SetActive(false);
OptionsMenu.SetActive(false);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "GameSettings", menuName = "Databases/GameSettings")]
public class GameSettings : ScriptableObject
{
public event Action OnUpdateGameSettings;
[SerializeField] private float _soundEffectsVolume = default;
[SerializeField] private float _windVolume = default;
public float SoundEffectsVolume
{
get
{
return _soundEffectsVolume;
}
set
{
if (value >= 1)
{
_soundEffectsVolume = 1;
}
else
{
_soundEffectsVolume = value;
}
OnUpdateGameSettings?.Invoke();
}
}
public float WindVolume
{
get
{
return _windVolume;
}
set
{
if (value >= 1)
{
_windVolume = 1;
}
else
{
_windVolume = value;
}
OnUpdateGameSettings?.Invoke();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MessageSignController : MonoBehaviour
{
[SerializeField] [TextArea(3, 10)] private string _message = default;
public string getMessage()
{
return _message;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum SoundEffects {
Jump,
Dash,
WallJump,
OnWall,
Orb,
MovingFast
}
public class SoundManager : MonoBehaviour
{
[SerializeField] private GameSettings _gameSettings = default;
[SerializeField] private AudioSource _soundEffects = default;
[SerializeField] private AudioSource _windSound = default;
[SerializeField] private SoundsDatabase _soundsDatabase = default;
void Start()
{
_gameSettings.OnUpdateGameSettings += updateVolume;
updateVolume();
}
public void PlaySoundEffect(SoundEffects soundEffect)
{
switch (soundEffect) {
case SoundEffects.Jump:
_soundEffects.PlayOneShot(_soundsDatabase.Jump);
break;
case SoundEffects.Dash:
_soundEffects.PlayOneShot(_soundsDatabase.Dash);
break;
case SoundEffects.WallJump:
_soundEffects.PlayOneShot(_soundsDatabase.WallJump); break;
case SoundEffects.OnWall:
_soundEffects.PlayOneShot(_soundsDatabase.OnWall);
break;
case SoundEffects.Orb:
_soundEffects.loop = true;
if (!_soundEffects.isPlaying) _soundEffects.PlayOneShot(_soundsDatabase.Orb);
break;
case SoundEffects.MovingFast:
_soundEffects.PlayOneShot(_soundsDatabase.MovingFast);
break;
}
}
private void updateVolume()
{
_soundEffects.volume = _gameSettings.SoundEffectsVolume;
_windSound.volume = _gameSettings.WindVolume;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager
{
private static GameManager _instance;
private PlayerController _playerController;
private CameraMovementController _cameraMovementController;
private SceneController _sceneController;
private PauseMenuController _pauseMenu;
private Timer _timer;
public PlayerController PlayerController {
get
{
if (_playerController == null)
{
_playerController = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
}
return _playerController;
}
}
public CameraMovementController CameraMovementController
{
get
{
if (_cameraMovementController == null)
{
_cameraMovementController = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraMovementController>();
}
return _cameraMovementController;
}
}
public SceneController SceneController
{
get
{
if (_sceneController == null)
{
_sceneController = GameObject.FindGameObjectWithTag("SceneController").GetComponent<SceneController>();
}
return _sceneController;
}
}
public PauseMenuController PauseMenu
{
get
{
if (_pauseMenu == null)
{
_pauseMenu = GameObject.FindGameObjectWithTag("PauseMenu").GetComponent<PauseMenuController>();
if (_pauseMenu == null) Debug.Log("empty");
}
return _pauseMenu;
}
set
{
_pauseMenu = value;
}
}
public Timer Timer
{
get
{
if (_timer == null)
{
_timer = GameObject.FindGameObjectWithTag("Timer").GetComponent<Timer>();
}
return _timer;
}
set
{
_timer = value;
}
}
public static bool isGamePaused = false;
public static GameManager Instance {
get
{
if (_instance == null)
{
_instance = new GameManager();
}
return _instance;
}
}
public GameManager() { }
public void PauseGame()
{
Time.timeScale = 0f;
isGamePaused = true;
PauseMenu.showPauseMenu();
}
public void ResumeGame()
{
PauseMenu.hidePauseMenu();
Time.timeScale = 1f;
isGamePaused = false;
}
}
<file_sep>// Reference/Source: https://www.youtube.com/watch?v=zit45k6CUMk&t=411s
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallax : MonoBehaviour
{
[SerializeField] private float _parallaxEffect = default;
private GameObject _camera = default;
private float _startPosition = default;
void Start()
{
_startPosition = transform.position.x;
_camera = GameObject.FindGameObjectWithTag("MainCamera");
}
// Update is called once per frame
void Update()
{
if (_camera == null)
{
// if we dont have the camera try again
_camera = GameObject.FindGameObjectWithTag("MainCamera");
}
// if it is still null dont do the calculations
if (_camera == null) return;
float distance = (_camera.transform.position.x * _parallaxEffect);
transform.position = new Vector3(_startPosition + distance, transform.position.y, transform.position.z);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "SoundsDatabase", menuName = "Databases/SoundsDatabase")]
public class SoundsDatabase : ScriptableObject
{
[SerializeField] private AudioClip _jump = default;
[SerializeField] private AudioClip _dash = default;
[SerializeField] private AudioClip _wallJump = default;
[SerializeField] private AudioClip _onWall = default;
[SerializeField] private AudioClip _orb = default;
[SerializeField] private AudioClip _movingFast = default;
public AudioClip Jump => _jump;
public AudioClip Dash => _dash;
public AudioClip WallJump => _wallJump;
public AudioClip OnWall => _onWall;
public AudioClip Orb => _orb;
public AudioClip MovingFast => _movingFast;
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
[SerializeField] private Text _timerText = default;
[SerializeField] private GameState _gameState = default;
private bool _running = default;
public float ElapsedTime { get; private set; } = default;
void Start()
{
ElapsedTime = _gameState.CurrentTime;
_running = false;
}
// Update is called once per frame
void Update()
{
if (_running)
{
ElapsedTime += Time.deltaTime;
TimeSpan time = TimeSpan.FromSeconds(ElapsedTime);
_timerText.text = time.ToString("mm':'ss'.'ff");
}
}
public void StartTimer()
{
_running = true;
}
// called when goal is reached
public void StopTimer()
{
_gameState.CurrentTime = ElapsedTime;
if (ElapsedTime < _gameState.BestTime || _gameState.BestTime == 0)
{
_gameState.BestTime = ElapsedTime;
}
_running = false;
}
}
<file_sep>using System;
using UnityEngine;
// the model for the game
[CreateAssetMenu(fileName = "GameState", menuName = "Databases/GameState")]
public class GameState : ScriptableObject
{
public event Action OnUpdateGameState;
[SerializeField] private Vector3 _checkpoint = new Vector3(-6, -4.45f, -1);
[SerializeField] private float _currentTime = 0;
[SerializeField] private float _bestTime = 0;
public Vector3 Checkpoint
{
get
{
return _checkpoint;
}
set
{
_checkpoint = value;
OnUpdateGameState?.Invoke();
}
}
public float BestTime
{
get
{
return _bestTime;
}
set
{
_bestTime = value;
}
}
public float CurrentTime
{
get
{
return _currentTime;
}
set
{
_currentTime = value;
}
}
}
|
b16225a2215bd71b19408dcf5d56259ff4116ab9
|
[
"Markdown",
"C#"
] | 25 |
C#
|
nickhachmer/Sky-Runner
|
1f26d21b732226bc83f8358754da6230b872d073
|
3d62bf1d2af8ba7c6a03a0f5973c1c233e02ab66
|
refs/heads/master
|
<repo_name>invinciible/golang-restapi<file_sep>/books-list/controllers/book.go
package controllers
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/inviincible/rest_api/books-list/models"
)
type Controller struct{}
type Book = models.Book
var books []Book
func logFatal(err error) {
if err != nil {
log.Println(err)
}
}
func (c Controller) GetBooks(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var book Book
books = []Book{}
rows, err := db.Query("select * from books")
logFatal(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&book.ID, &book.Title, &book.Author, &book.Year)
logFatal(err)
books = append(books, book)
}
json.NewEncoder(w).Encode(books)
}
}
func (c *Controller) GetBook(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var book Book
params := mux.Vars(r)
bookID, _ := strconv.Atoi(params["id"])
row := db.QueryRow("select * from books where id = $1", bookID)
err := row.Scan(&book.ID, &book.Title, &book.Author, &book.Year)
logFatal(err)
json.NewEncoder(w).Encode(&book)
}
}
func (c *Controller) AddBook(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var book Book
//var bookID int
err := json.NewDecoder(r.Body).Decode(&book)
logFatal(err)
err = db.QueryRow("insert into books (title, author, year) values($1, $2, $3) RETURNING id;", book.Title, book.Author, book.Year).Scan(&book.ID)
logFatal(err)
json.NewEncoder(w).Encode(&book)
}
}
func (c *Controller) UpdateBook(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var book Book
err := json.NewDecoder(r.Body).Decode(&book)
logFatal(err)
result, err := db.Exec("update books set title=$1, author=$2, year=$3 where id=$4 RETURNING id;", book.Title, book.Author, book.Year, book.ID)
logFatal(err)
rowsUpdated, err := result.RowsAffected()
logFatal(err)
json.NewEncoder(w).Encode(rowsUpdated)
}
}
func (c *Controller) RemoveBook(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
result, err := db.Exec("delete from books where id=$1", params["id"])
logFatal(err)
rowsDeleted, err := result.RowsAffected()
logFatal(err)
json.NewEncoder(w).Encode(rowsDeleted)
}
}
<file_sep>/README.md
# Golang-restapi
RESTful APIs example with Golang (basic CRUD operations) using Postgresql
|
a634fcbec756abf118116be7536850711a7416bb
|
[
"Markdown",
"Go"
] | 2 |
Go
|
invinciible/golang-restapi
|
4327c9147b5ed7c8c42c9633464812c368adeb87
|
566e18eb8d489144dcf7624716d5c71217c440fd
|
refs/heads/master
|
<repo_name>amiratak88/js-basics-functions-lab-dumbo-web-071618<file_sep>/index.js
function distanceFromHqInBlocks(st) {
return Math.abs(st - 42)
}
function distanceFromHqInFeet(st) {
return 264 * distanceFromHqInBlocks(st)
}
function distanceTravelledInFeet(st1, st2) {
return Math.abs((st2 - st1) * 264)
}
function calculatesFarePrice(start, dest) {
distance = distanceTravelledInFeet(start, dest)
if (distance > 2500) {
return 'cannot travel that far'
} else if (distance > 2000) {
return 25
} else if (distance > 400) {
return (distance - 400) * 2 / 100
} else {
return 0
}
}
|
fce704604649fd5b60cf3b952e10ade15e92c15e
|
[
"JavaScript"
] | 1 |
JavaScript
|
amiratak88/js-basics-functions-lab-dumbo-web-071618
|
2d174819e5d8f514150af6a0a6a29a7ade1f7058
|
04df786eb408f3d039896eff356dc07f85b0dfaf
|
refs/heads/master
|
<repo_name>sivaish/chatapp-socketIO<file_sep>/server/server.js
const path = require('path')
const express = require('express')
const socketIO = require('socket.io')
const http = require('http')
var publicPath = path.join(__dirname, '../public')
const port = process.env.PORT || 3000
var app = express()
var server = http.createServer(app)
var io = socketIO(server)
// this is used to configure the express app middleware
app.use(express.static(publicPath))
// Register an client event - Where the Client and Server Events are accessed here
io.on('connection', (socket) => {
console.log('New user client connected')
// connection listener
socket.on('disconnect', () => {
console.log('User client disconnected')
})
// custom event emit
socket.emit('welcomeMsgToClient', {
frm: 'Server',
msg: 'Welcome to Chat app - Share your thoughts here'
})
// custom event listener
socket.on('msgFrmClient', (msgFrmClient) => {
console.log('Msg:', msgFrmClient)
io.emit('newMsg', {
frm: msgFrmClient.frm,
msg: msgFrmClient.msg,
createdAt: new Date().getTime()
})
})
})
server.listen(port, () => {
console.log(`Server is up and running in the PORT ${port}`)
})
<file_sep>/public/js/index.js
var socket = io();
// Below are the two different declaration of the ES6 (arrow function) and normal function declaration
// socket.on('connect', () => {
// console.log('connected to server')
// })
socket.on('connect', function () {
console.log('connected to server')
// custom Event emitter
socket.emit('msgFrmClient', {
frm: 'Client',
msg: 'Thanks for connecting me!'
})
})
socket.on('disconnect', function() {
console.log('Disconnected from server')
})
// custom Listener Event
socket.on('welcomeMsgToClient', function (messageToClient) {
console.log('msgFrmServer', messageToClient)
})
// custom Listener Event
socket.on('newMsg', function (messageToClients) {
console.log('New Message', messageToClients)
})
|
eb5a6c33c6a36098c8d855d3e570a3815121caa6
|
[
"JavaScript"
] | 2 |
JavaScript
|
sivaish/chatapp-socketIO
|
e10937f26c2699b4a5fadde95b47c840e3eeb8ba
|
7436aee2617771f88dc7b95daf5c32a6e924ce28
|
refs/heads/main
|
<repo_name>James404-cyber/Pro<file_sep>/Main/James/James.py
user :James
pass:
<file_sep>/Main/James/Salam/Passuser/pass.py
User:James
pass:404
|
efa971c6315b0766d0c172182e7fbe56fbce659e
|
[
"Python"
] | 2 |
Python
|
James404-cyber/Pro
|
a7ab1d9d38338e930e23414c9bd3ea1273c5e8ed
|
198c630d0d260a413acbb3cc9fab7d94605f8625
|
refs/heads/master
|
<file_sep>package com.berstek.myveripy.view.home;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.berstek.myveripy.R;
import com.berstek.myveripy.callback.RecviewItemClickCallback;
import com.berstek.myveripy.data_access.UserDA;
import com.berstek.myveripy.model.PayTransaction;
import com.berstek.myveripy.model.User;
import com.berstek.myveripy.utils.Utils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import java.util.List;
public class HomeTransactionsAdapter extends RecyclerView.Adapter<HomeTransactionsAdapter.ListHolder> {
private List<PayTransaction> data;
private LayoutInflater inflater;
private Context context;
private UserDA userDA;
private Utils utils;
private RecviewItemClickCallback itemClickCallback;
public HomeTransactionsAdapter(List<PayTransaction> data, Context context) {
this.data = data;
this.context = context;
inflater = LayoutInflater.from(context);
userDA = new UserDA();
utils = new Utils(context);
}
@Override
public ListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ListHolder(inflater.inflate(R.layout.viewholder_transaction_list, parent, false));
}
@Override
public void onBindViewHolder(final ListHolder holder, int position) {
final PayTransaction transaction = data.get(position);
holder.titleTxt.setText(transaction.getTitle());
switch (transaction.getStatus()) {
case 0:
holder.statusTxt.setText("Pending");
break;
case 1:
holder.statusTxt.setText("Waiting Shipment");
break;
case 2:
holder.statusTxt.setText("Rejected");
case 3:
holder.statusTxt.setText("Completed");
break;
default:
break;
}
String uid;
if (Utils.getUid().equals(transaction.getSender_uid())) {
uid = transaction.getRecipient_uid();
holder.typeTxt.setText("Sent Payment for ");
holder.flowTxt.setText("To ");
//set color to red
holder.priceTxt.setTextColor(context.getResources().getColor(R.color.redText));
} else {
uid = transaction.getSender_uid();
holder.typeTxt.setText("Received Payment for ");
holder.flowTxt.setText("From ");
holder.priceTxt.setTextColor(context.getResources().getColor(R.color.greenText));
}
userDA.queryUserByUidOnce(uid).
addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
User u = task.getResult().toObject(User.class);
utils.loadImage(u.getPhoto_url(), holder.dp, 100);
holder.nameTxt.setText(String.format("%s %s", u.getFirst_name(), u.getLast_name()));
}
});
holder.priceTxt.setText(String.format("%s %s", Utils.getPesoSign(),
Utils.formatDf(transaction.getPrice())));
}
@Override
public int getItemCount() {
return data.size();
}
class ListHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView priceTxt, nameTxt, dateTxt, statusTxt, titleTxt, typeTxt, flowTxt;
private ImageView dp;
public ListHolder(View itemView) {
super(itemView);
typeTxt = itemView.findViewById(R.id.typeTxt);
flowTxt = itemView.findViewById(R.id.flowTxt);
priceTxt = itemView.findViewById(R.id.priceTxt);
nameTxt = itemView.findViewById(R.id.nameTxt);
dateTxt = itemView.findViewById(R.id.dateTxt);
statusTxt = itemView.findViewById(R.id.statusTxt);
titleTxt = itemView.findViewById(R.id.titleTxt);
dp = itemView.findViewById(R.id.dp);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
itemClickCallback.onRecviewItemClick(view, getAdapterPosition());
}
}
public void setItemClickCallback(RecviewItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
}
<file_sep>package com.berstek.myveripy.utils;
public class PartnersImg {
public static final String LBC = "https://firebasestorage.googleapis.com/v0/b/myveripay.appspot.com/o/img_partners%2Fimg_lbc.png?alt=media&token=<PASSWORD>";
}
<file_sep>package com.berstek.myveripy.utils;
public class PermissionCodes {
public static int ACCESS_FINE_LOCATION = 89;
}
<file_sep>package com.berstek.myveripy.view.pay.send_money;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.berstek.myveripy.R;
import com.berstek.myveripy.model.Payment;
import com.berstek.myveripy.model.User;
import com.berstek.myveripy.view.confirmation.ConfirmationFragment;
import com.berstek.myveripy.presentor.payment.PaymentPresentor;
import com.berstek.myveripy.utils.Utils;
import com.berstek.myveripy.view.home.MainActivity;
import com.berstek.myveripy.view.pay.pay_shipment.PayShipmentActivity;
import com.berstek.myveripy.view.pay.pay_shipment.PaymentRecipientFragment;
public class SendMoneyActivity extends AppCompatActivity
implements PaymentRecipientFragment.PaymentRecipientFragmentCallback,
PaymentPresentor.PaymentPresentorCallback, View.OnClickListener {
private PaymentRecipientFragment paymentRecipientFragment;
private PaymentPresentor paymentPresentor;
private EditText priceEdit;
private String recipient;
private TextView actionTxt, moduleTitleTxt;
private double cash = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_money);
getSupportActionBar().hide();
priceEdit = findViewById(R.id.priceEdit);
actionTxt = findViewById(R.id.actionTxt);
actionTxt.setOnClickListener(this);
moduleTitleTxt = findViewById(R.id.moduleTitleTxt);
moduleTitleTxt.setText("Send Money");
paymentPresentor = new PaymentPresentor(this);
paymentPresentor.setPaymentPresentorCallback(this);
paymentPresentor.init();
paymentRecipientFragment = new PaymentRecipientFragment();
paymentRecipientFragment.setPaymentRecipientFragmentCallback(this);
getSupportFragmentManager().beginTransaction().
replace(R.id.fragment1, paymentRecipientFragment).commit();
}
@Override
public void onUserQueried(User user) {
recipient = user.getKey();
}
@Override
public void onDebit(Payment payment) {
cash -= payment.getAmount();
}
@Override
public void onCredit(Payment payment) {
cash += payment.getAmount();
}
@Override
public void onPayment(Payment payment) {
ConfirmationFragment confirmationFragment = new ConfirmationFragment();
confirmationFragment.setCancelable(false);
confirmationFragment.show(getFragmentManager(), null);
confirmationFragment.setConfirmationFragmentCallback(new ConfirmationFragment.ConfirmationFragmentCallback() {
@Override
public void onConfirmationDone() {
Intent intent = new Intent(SendMoneyActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
@Override
public void onClick(View view) {
double amount = Double.parseDouble(priceEdit.getText().toString());
if (amount > cash) {
Toast.makeText(this, "You have insufficient funds.", Toast.LENGTH_LONG).show();
} else {
if (recipient != null) {
Payment payment = new Payment();
payment.setFrom(Utils.getUid());
payment.setTo(recipient);
payment.setAmount(amount);
payment.setDate(System.currentTimeMillis());
paymentPresentor.pushPayment(payment);
} else {
Toast.makeText(this, "Please select a recipient.", Toast.LENGTH_LONG).show();
}
}
}
}
<file_sep>package com.berstek.myveripy.view.upload_image;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.berstek.myveripy.R;
import com.berstek.myveripy.utils.Utils;
import java.util.ArrayList;
public class PlainImageListAdapterHorizontal extends RecyclerView.Adapter<PlainImageListAdapterHorizontal.ListHolder> {
private ArrayList<String> data;
private LayoutInflater inflater;
private Utils utils;
public PlainImageListAdapterHorizontal(ArrayList<String> data, Context context) {
this.data = data;
inflater = LayoutInflater.from(context);
utils = new Utils(context);
}
@Override
public ListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ListHolder(inflater.inflate(R.layout.viewholder_plain_image_horizontal, parent, false));
}
@Override
public void onBindViewHolder(ListHolder holder, int position) {
String url = data.get(position);
utils.loadImage(url, holder.img);
}
@Override
public int getItemCount() {
return data.size();
}
class ListHolder extends RecyclerView.ViewHolder {
private ImageView img;
public ListHolder(View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
}
}
}
<file_sep>package com.berstek.myveripy.view.pay.pay_shipment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.berstek.myveripy.R;
import com.berstek.myveripy.model.PayTransaction;
import com.berstek.myveripy.model.Payment;
import com.berstek.myveripy.model.User;
import com.berstek.myveripy.presentor.payment.PaymentPresentor;
import com.berstek.myveripy.view.confirmation.ConfirmationFragment;
import com.berstek.myveripy.presentor.pay_shipment.PayShipmentPresentor;
import com.berstek.myveripy.presentor.pay_shipment.PayShipmentPresentor.PayShipmentPresentorCallback;
import com.berstek.myveripy.utils.Utils;
import com.berstek.myveripy.view.home.MainActivity;
import com.berstek.myveripy.view.upload_image.PlainImageListAdapter;
import com.berstek.myveripy.view.upload_image.UploadImageFragment;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
public class PayShipmentActivity extends AppCompatActivity implements
PaymentRecipientFragment.PaymentRecipientFragmentCallback, View.OnClickListener,
UploadImageFragment.ImageUploaderCallback, PayShipmentPresentorCallback,
PaymentPresentor.PaymentPresentorCallback {
private PaymentRecipientFragment paymentRecipientFragment;
private DateSelectionFragment dateSelectionFragment;
private UploadImageFragment uploadImageFragment;
private RecyclerView imagesRecview;
private PayTransaction transaction = new PayTransaction();
private String searchParam;
private TextView actionTxt;
private EditText titleEdit, detailsEdit, priceEdit;
private ArrayList<String> imgsUrlList = new ArrayList<>();
private PlainImageListAdapter plainImageListAdapter;
private PayShipmentPresentor payShipmentPresentor;
private PaymentPresentor paymentPresentor;
private double cash;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_shipment);
if (getIntent().getExtras() != null)
searchParam = getIntent().getExtras().getString("searchParam");
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
paymentPresentor = new PaymentPresentor(this);
paymentPresentor.setPaymentPresentorCallback(this);
paymentPresentor.init();
payShipmentPresentor = new PayShipmentPresentor();
payShipmentPresentor.setPayShipmentPresentorCallback(this);
actionTxt = findViewById(R.id.actionTxt);
titleEdit = findViewById(R.id.titleEdit);
detailsEdit = findViewById(R.id.detailsEdit);
priceEdit = findViewById(R.id.priceEdit);
imagesRecview = findViewById(R.id.imagesRecview);
imagesRecview.setLayoutManager(new LinearLayoutManager(this));
plainImageListAdapter = new PlainImageListAdapter(imgsUrlList, this);
imagesRecview.setAdapter(plainImageListAdapter);
actionTxt.setOnClickListener(this);
Bundle bundle = new Bundle();
bundle.putString("searchParam", searchParam);
paymentRecipientFragment = new PaymentRecipientFragment();
paymentRecipientFragment.setArguments(bundle);
paymentRecipientFragment.setPaymentRecipientFragmentCallback(this);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment1, paymentRecipientFragment).commit();
dateSelectionFragment = new DateSelectionFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment2, dateSelectionFragment).commit();
uploadImageFragment = new UploadImageFragment();
uploadImageFragment.setImageUploaderCallback(this);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment3, uploadImageFragment).commit();
}
@Override
public void onUserQueried(User user) {
transaction.setSender_uid(Utils.getUid());
transaction.setRecipient_uid(user.getKey());
}
@Override
public void onClick(View view) {
Double amount = Double.parseDouble(priceEdit.getText().toString());
if (amount < cash) {
transaction.setTitle(titleEdit.getText().toString());
transaction.setPrice(amount);
transaction.setDetails(detailsEdit.getText().toString());
transaction.setDate_created(System.currentTimeMillis());
//TODO hardcoded due date in 2 days
transaction.setDue_date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 * 2));
transaction.setTransaction_id("TRN-" + UUID.randomUUID().toString().substring(0, 7).toUpperCase());
transaction.setStatus(0);
int[] dates = Utils.getDateInt(new Date());
transaction.setYear(dates[0]);
transaction.setMonth(dates[1]);
transaction.setDay(dates[2]);
payShipmentPresentor.pushTransaction(transaction);
} else {
Toast.makeText(this, "Insufficient funds.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onImageUploaded(String url) {
imgsUrlList.add(url);
plainImageListAdapter.notifyItemInserted(imgsUrlList.size() - 1);
transaction.setImgs_url(imgsUrlList);
}
@Override
public void onUpdate() {
//TODO, notify user about upload percentage
}
@Override
public void onTransactionPushed() {
ConfirmationFragment confirmationFragment = new ConfirmationFragment();
confirmationFragment.setCancelable(false);
confirmationFragment.show(getFragmentManager(), null);
confirmationFragment.setConfirmationFragmentCallback(new ConfirmationFragment.ConfirmationFragmentCallback() {
@Override
public void onConfirmationDone() {
Intent intent = new Intent(PayShipmentActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
@Override
public void onDebit(Payment payment) {
cash -= payment.getAmount();
}
@Override
public void onCredit(Payment payment) {
cash += payment.getAmount();
}
@Override
public void onPayment(Payment payment) {
}
}
<file_sep>package com.berstek.myveripy.model;
import com.google.firebase.firestore.Exclude;
import java.io.Serializable;
public class User implements Serializable {
private String email, last_name, first_name, photo_url;
private long phone_number;
private long date_joined;
private String pay_id;
private Address address;
private String key;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getPhoto_url() {
return photo_url;
}
public void setPhoto_url(String photo_url) {
this.photo_url = photo_url;
}
public long getPhone_number() {
return phone_number;
}
public void setPhone_number(long phone_number) {
this.phone_number = phone_number;
}
public long getDate_joined() {
return date_joined;
}
public void setDate_joined(long date_joined) {
this.date_joined = date_joined;
}
public String getPay_id() {
return pay_id;
}
public void setPay_id(String pay_id) {
this.pay_id = pay_id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getFullName() {
return first_name + " " + last_name;
}
}
<file_sep>package com.berstek.myveripy.utils;
public class RequestCodes {
public static final int SIGN_IN = 69;
public static final int PICK_FILE = 70;
}
<file_sep>package com.berstek.myveripy.presentor.payment;
import android.app.Activity;
import android.support.annotation.NonNull;
import com.berstek.myveripy.data_access.PaymentDA;
import com.berstek.myveripy.model.Payment;
import com.berstek.myveripy.utils.Utils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
public class PaymentPresentor {
private PaymentDA paymentDA;
private PaymentPresentorCallback paymentPresentorCallback;
private Activity activity;
public PaymentPresentor(Activity activity) {
paymentDA = new PaymentDA();
this.activity = activity;
}
public void init() {
paymentDA.queryCredits(Utils.getUid()).addSnapshotListener(activity, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentChange dc : documentSnapshots.getDocumentChanges()) {
Payment payment = dc.getDocument().toObject(Payment.class);
paymentPresentorCallback.onCredit(payment);
}
}
});
paymentDA.queryDebits(Utils.getUid()).addSnapshotListener(activity, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentChange dc : documentSnapshots.getDocumentChanges()) {
Payment payment = dc.getDocument().toObject(Payment.class);
paymentPresentorCallback.onDebit(payment);
}
}
});
}
public void pushPayment(final Payment payment) {
paymentDA.pushPayment(payment).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
paymentPresentorCallback.onPayment(payment);
}
}
});
}
public interface PaymentPresentorCallback {
void onDebit(Payment payment);
void onCredit(Payment payment);
void onPayment(Payment payment);
}
public void setPaymentPresentorCallback(PaymentPresentorCallback paymentPresentorCallback) {
this.paymentPresentorCallback = paymentPresentorCallback;
}
}
<file_sep>package com.berstek.myveripy.view.home;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.berstek.myveripy.R;
import com.berstek.myveripy.custom_classes.CustomDialogFragment;
import com.berstek.myveripy.model.PayTransaction;
import com.berstek.myveripy.presentor.home.TransactionFullViewPresentor;
import com.berstek.myveripy.utils.Utils;
import com.berstek.myveripy.view.upload_image.PlainImageListAdapterHorizontal;
/**
* A simple {@link Fragment} subclass.
*/
public class TransactionFullViewDialogFragment extends CustomDialogFragment
implements View.OnClickListener,
TransactionFullViewPresentor.TransactionFullViewPresentorCallback {
TransactionFullViewPresentor presentor;
private PayTransaction transaction;
private TextView directionTxt, nameTxt, dateTxt, dueTxt,
priceTxt, statusTxt, titleTxt, detailsTxt, statusBelowTxt, trnoTxt;
private LinearLayout btnsLinearLayout;
private Button acceptBtn, rejectBtn;
private RecyclerView imagesRecview;
private PlainImageListAdapterHorizontal adapter;
public TransactionFullViewDialogFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_transaction_full_view_dialog, container, false);
transaction = (PayTransaction) getArguments().getSerializable("transaction");
presentor = new TransactionFullViewPresentor();
presentor.setTransactionFullViewPresentorCallback(this);
trnoTxt = view.findViewById(R.id.trnoTxt);
directionTxt = view.findViewById(R.id.directionTxt);
nameTxt = view.findViewById(R.id.nameTxt);
dateTxt = view.findViewById(R.id.dateTxt);
dueTxt = view.findViewById(R.id.dueTxt);
priceTxt = view.findViewById(R.id.priceTxt);
statusTxt = view.findViewById(R.id.statusTxt);
titleTxt = view.findViewById(R.id.titleTxt);
detailsTxt = view.findViewById(R.id.detailsTxt);
imagesRecview = view.findViewById(R.id.imagesRecview);
acceptBtn = view.findViewById(R.id.acceptBtn);
acceptBtn.setOnClickListener(this);
rejectBtn = view.findViewById(R.id.rejectBtn);
rejectBtn.setOnClickListener(this);
statusBelowTxt = view.findViewById(R.id.statusBelowTxt);
btnsLinearLayout = view.findViewById(R.id.btnsLinearLayout);
btnsLinearLayout.setVisibility(View.GONE);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
imagesRecview.setLayoutManager(linearLayoutManager);
if (transaction.getImgs_url() != null)
adapter = new PlainImageListAdapterHorizontal(transaction.getImgs_url(), getActivity());
imagesRecview.setAdapter(adapter);
titleTxt.setText(transaction.getTitle());
trnoTxt.setText(transaction.getTransaction_id());
//check if we are in the seller or buyer's perspective
String direction;
//this is the buyer's perspective
if (transaction.getSender_uid().equals(Utils.getUid())) {
direction = "Sent Pending Payment to ";
if (transaction.getStatus() == 0) {
statusBelowTxt.setText("");
} else if (transaction.getStatus() == 1) {
statusTxt.setText("Waiting for Seller to Ship Item");
statusBelowTxt.setText("This transaction has been accepted.");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.greenText));
} else if (transaction.getStatus() == 2) {
statusTxt.setText("This transaction is no longer valid");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.redText));
statusBelowTxt.setText("The seller declined this transaction.");
} else if (transaction.getStatus() == 3) {
statusTxt.setText("The seller has received payment for this item.");
statusBelowTxt.setText("This transaction is complete.");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.greenText));
}
//this is the seller's perspective
} else {
direction = "Received Pending Payment from ";
priceTxt.setTextColor(getActivity().getResources().getColor(R.color.greenText));
if (transaction.getStatus() == 0) {
statusBelowTxt.setText("");
btnsLinearLayout.setVisibility(View.VISIBLE);
} else if (transaction.getStatus() == 1) {
statusTxt.setText("Please ship the item to receive the payment.");
statusBelowTxt.setText("This transaction has been accepted.");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.greenText));
} else if (transaction.getStatus() == 2) {
statusTxt.setText("This transaction is no longer valid.");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.redText));
statusBelowTxt.setText("You declined this transaction.");
} else if (transaction.getStatus() == 3) {
statusTxt.setText("You have received payment for this item.");
statusBelowTxt.setText("This transaction is complete.");
statusTxt.setTextColor(getActivity().getResources().getColor(R.color.greenText));
}
}
directionTxt.setText(direction);
dateTxt.setText(Utils.formatDateWithTime(transaction.getDate_created()));
dueTxt.setText(String.format("Due on %s", Utils.formatDateWithTime(transaction.getDue_date())));
return super.onCreateView(inflater, container, savedInstanceState);
}
private boolean accepted;
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.acceptBtn) {
presentor.acceptTransaction(transaction.getKey());
accepted = true;
} else {
presentor.rejectTransaction(transaction.getKey());
accepted = false;
}
}
@Override
public void onTransactionUpdateCompleted() {
btnsLinearLayout.setVisibility(View.GONE);
statusTxt.setText("Waiting for Seller to Ship Item");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.primaryTextColor));
if (accepted) {
statusBelowTxt.setText("This transaction has been accepted.");
} else {
statusBelowTxt.setText("This transaction has been declined.");
statusBelowTxt.setTextColor(getActivity().getResources().getColor(R.color.redText));
}
}
@Override
public void onTransactionUpdateFailed() {
}
}
<file_sep>package com.berstek.myveripy.model;
public class Payment {
private double amount;
private long date;
private String from, to;
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
}
<file_sep>package com.berstek.myveripy.view.confirmation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.berstek.myveripy.R;
import com.berstek.myveripy.custom_classes.CustomDialogFragment;
/**
* A simple {@link Fragment} subclass.
*/
public class ConfirmationFragment extends CustomDialogFragment
implements View.OnClickListener {
private View view;
public ConfirmationFragment() {
// Required empty public constructor
}
private Button doneBtn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_confirmation, container, false);
super.onCreateView(inflater, container, savedInstanceState);
doneBtn = view.findViewById(R.id.doneBtn);
doneBtn.setOnClickListener(this);
return view;
}
@Override
public void onClick(View view) {
confirmationFragmentCallback.onConfirmationDone();
}
private ConfirmationFragmentCallback confirmationFragmentCallback;
public interface ConfirmationFragmentCallback {
void onConfirmationDone();
}
public void setConfirmationFragmentCallback(ConfirmationFragmentCallback confirmationFragmentCallback) {
this.confirmationFragmentCallback = confirmationFragmentCallback;
}
}
<file_sep>package com.berstek.myveripy.view.pay;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.berstek.myveripy.R;
import com.berstek.myveripy.custom_classes.CustomDialogFragment;
/**
* A simple {@link Fragment} subclass.
*/
public class PaymentTypeSelectionDialogFragment
extends CustomDialogFragment implements View.OnClickListener {
public PaymentTypeSelectionDialogFragment() {
// Required empty public constructor
}
private ImageView sendMoneyImg, payShipmentImg;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_payment_type_selection_dialog, container, false);
sendMoneyImg = view.findViewById(R.id.sendMoneyImg);
payShipmentImg = view.findViewById(R.id.payShipmentImg);
sendMoneyImg.setOnClickListener(this);
payShipmentImg.setOnClickListener(this);
return super.onCreateView(inflater, container, savedInstanceState);
}
private PaymentTypeCallback paymentTypeCallback;
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.sendMoneyImg) {
paymentTypeCallback.onSendMoney();
} else if (id == R.id.payShipmentImg) {
paymentTypeCallback.onPayShipment();
}
}
public interface PaymentTypeCallback {
void onSendMoney();
void onPayShipment();
}
public void setPaymentTypeCallback(PaymentTypeCallback paymentTypeCallback) {
this.paymentTypeCallback = paymentTypeCallback;
}
}
<file_sep>package com.berstek.myveripy.data_access;
public class ImageUploader {
}
<file_sep>package com.berstek.myveripy.view.search;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.berstek.myveripy.R;
import com.berstek.myveripy.model.User;
import com.berstek.myveripy.utils.CustomImageUtils;
import com.berstek.myveripy.utils.Utils;
import com.berstek.myveripy.view.pay.pay_shipment.PayShipmentActivity;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private User user;
private TextView nameTxt, phoneTxt, addressTxt;
private CircleImageView dp;
private ImageView dpBlurred;
private Button payBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
dp = findViewById(R.id.dp);
dpBlurred = findViewById(R.id.dp_blurred);
nameTxt = findViewById(R.id.nameTxt);
phoneTxt = findViewById(R.id.addressTxt);
phoneTxt = findViewById(R.id.addressTxt);
user = (User) getIntent().getSerializableExtra("user");
nameTxt.setText(user.getFirst_name() + " " + user.getLast_name());
new Utils(this).loadImage(user.getPhoto_url(), dp);
new CustomImageUtils().blurImage(this, user.getPhoto_url(), dpBlurred, true);
payBtn = findViewById(R.id.payBtn);
payBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("searchParam", user.getPay_id());
Intent intent = new Intent(this, PayShipmentActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
<file_sep>package com.berstek.myveripy.data_access;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.FirebaseFirestoreSettings;
import com.google.firebase.firestore.Transaction;
public class DA {
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
private FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(false)
.build();
public DA() {
db.setFirestoreSettings(settings);
}
public void log(Object object) {
db.collection("logs").add(object);
}
public void log2(Object o) {
rootRef.child("logs").push().setValue(o);
}
public Task<Object> updateDocument(String collection, String key, final String field, final Object value) {
final DocumentReference reference = db.collection(collection).document(key);
return db.runTransaction(new Transaction.Function<Object>() {
@Override
public Object apply(@NonNull Transaction transaction)
throws FirebaseFirestoreException {
DocumentSnapshot documentSnapshot = transaction.get(reference);
transaction.update(reference, field, value);
return value;
}
});
}
}
<file_sep>package com.berstek.myveripy.callback;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.firebase.auth.FirebaseUser;
public interface AuthCallback {
void onAuthSuccess(FirebaseUser user, GoogleSignInAccount account);
void onSignOutSuccess();
}
<file_sep>package com.berstek.myveripy.presentor.auth;
import com.berstek.myveripy.data_access.DA;
import com.berstek.myveripy.data_access.UserDA;
import com.berstek.myveripy.model.User;
import com.berstek.myveripy.utils.Utils;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseUser;
import java.util.UUID;
public class AuthPresentor {
private UserDA userDA;
private OnUserAddedCallback onUserAddedCallback;
public AuthPresentor() {
userDA = new UserDA();
}
public void addUser(FirebaseUser fbUser, GoogleSignInAccount account) {
User user = new User();
user.setLast_name(account.getFamilyName());
user.setFirst_name(account.getGivenName());
user.setPhoto_url(account.getPhotoUrl().toString());
user.setDate_joined(System.currentTimeMillis());
user.setKey(Utils.getUid());
user.setEmail(account.getEmail());
user.setPay_id(UUID.randomUUID().toString().substring(0, 8).toUpperCase());
userDA.addUserCheckIfExists(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
onUserAddedCallback.onUserAdded();
}
});
}
public interface OnUserAddedCallback {
void onUserAdded();
}
public void setOnUserAddedCallback(OnUserAddedCallback onUserAddedCallback) {
this.onUserAddedCallback = onUserAddedCallback;
}
}
<file_sep>package com.berstek.myveripy.view.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.berstek.myveripy.R;
import com.berstek.myveripy.callback.AuthCallback;
import com.berstek.myveripy.data_access.TransactionDA;
import com.berstek.myveripy.model.User;
import com.berstek.myveripy.presentor.auth.GoogleAuthPresentor;
import com.berstek.myveripy.presentor.home.MainActivityPresentor;
import com.berstek.myveripy.utils.CustomImageUtils;
import com.berstek.myveripy.utils.Utils;
import com.berstek.myveripy.view.auth.AuthActivity;
import com.berstek.myveripy.view.search.SearchUserFragment;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
View.OnClickListener, MainActivityPresentor.MainActivityPresentorCallback, AuthCallback {
private ImageView searchBtn;
private MainActivityPresentor mainActivityPresentor;
private ConstraintLayout navHeader;
private CircleImageView dp;
private TextView nameTxt, phoneTxt, addressTxt, payIdTxt;
private ImageView dpBlurred;
private CustomImageUtils customImageUtils;
private GoogleAuthPresentor authPresentor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FirebaseApp.initializeApp(this);
authPresentor = new GoogleAuthPresentor(this, FirebaseAuth.getInstance());
authPresentor.setGoogleAuthCallback(this);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
searchBtn = findViewById(R.id.searchBtn);
searchBtn.setOnClickListener(this);
getSupportFragmentManager().beginTransaction().
replace(R.id.main_container, new ViewPagerFragment()).commit();
navHeader = (ConstraintLayout) navigationView.getHeaderView(0);
nameTxt = navHeader.findViewById(R.id.nameTxt);
phoneTxt = navHeader.findViewById(R.id.phoneTxt);
addressTxt = navHeader.findViewById(R.id.addressTxt);
payIdTxt = navHeader.findViewById(R.id.payIdTxt);
dp = navHeader.findViewById(R.id.dp);
dpBlurred = navHeader.findViewById(R.id.dpBlurred);
customImageUtils = new CustomImageUtils();
mainActivityPresentor = new MainActivityPresentor(this);
mainActivityPresentor.setMainActivityPresentorCallback(this);
mainActivityPresentor.init();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_logout) {
authPresentor.signOut();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onClick(View view) {
SearchUserFragment searchUserFragment = new SearchUserFragment();
searchUserFragment.show(getFragmentManager(), null);
}
@Override
public void onUserDataLoaded(User user) {
nameTxt.setText(user.getFirst_name() + " " + user.getLast_name());
payIdTxt.setText(user.getPay_id());
new Utils(this).loadImage(user.getPhoto_url(), dp);
customImageUtils.blurImage(this, user.getPhoto_url(), dpBlurred, false);
}
@Override
public void onAuthSuccess(FirebaseUser user, GoogleSignInAccount account) {
}
@Override
public void onSignOutSuccess() {
Intent intent = new Intent(this, AuthActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
<file_sep>package com.berstek.myveripy.view.payment_history;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.berstek.myveripy.R;
import com.berstek.myveripy.model.Payment;
import com.berstek.myveripy.presentor.payment.PaymentPresentor;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class PaymentHistoryFragment extends Fragment
implements PaymentPresentor.PaymentPresentorCallback {
private View view;
private RecyclerView paymentsRecview;
private PaymentPresentor paymentPresentor;
private ArrayList<Payment> payments;
private PaymentHistoryAdapter adapter;
public PaymentHistoryFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_payment_history, container, false);
paymentsRecview = view.findViewById(R.id.paymentsRecview);
paymentsRecview.setLayoutManager(new LinearLayoutManager(getContext()));
payments = new ArrayList<>();
adapter = new PaymentHistoryAdapter(payments, getContext());
paymentsRecview.setAdapter(adapter);
paymentPresentor = new PaymentPresentor(getActivity());
paymentPresentor.setPaymentPresentorCallback(this);
paymentPresentor.init();
return view;
}
@Override
public void onDebit(Payment payment) {
payments.add(payment);
adapter.notifyItemInserted(payments.size() - 1);
}
@Override
public void onCredit(Payment payment) {
payments.add(payment);
adapter.notifyItemInserted(payments.size() - 1);
}
@Override
public void onPayment(Payment payment) {
}
}
|
d8f43f383e1de0d9c27ee0b4d3068ffb33f21df5
|
[
"Java"
] | 20 |
Java
|
quasarjohn/myveripay
|
228b74f544dcfa795d958cd594ea0319163b4ffc
|
4b632d7f523703548eb65481843c05529aeef499
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.