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 | <file_sep>import requests
import pandas as pd
import os
import sys
import logging
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_handler.setFormatter(logging.Formatter('%(asctime)s : %(processName)s : %(levelname)s : %(message)s'))
logger.addHandler(log_handler)
class EthScrapping():
def __init__(self, apikey, rate=200, logging_level="DEBUG"):
self.apikey=apikey
self.rate=rate
logger.setLevel(logging.getLevelName(logging_level))
#Limit 10.000
def get_transactions(self,address, start=0, end=99999999):
apirequest="http://api.etherscan.io/api?module=account&action=txlist&address="+address+"&startblock="+str(start)+"&endblock="+str(end)+"&sort=asc&apikey="+self.apikey
r = requests.get(url=apirequest)
return r.json()["result"]
#All transactions recorded
def get_all_transactions(self, address, start=0, end=99999999):
apirequest="http://api.etherscan.io/api?module=account&action=txlist&address="+address+"&startblock="+str(start)+"&endblock="+str(end)+"&sort=asc&apikey="+self.apikey
r = requests.get(url=apirequest)
res=r.json()["result"]
if (len(res)==10000):
res=res+self.get_all_transactions(address,res[9999]['blockNumber'],end)
return res
def get_investors(self, address):
transactions=self.get_all_transactions(address, start=0, end=99999999)
investors={}
for i in range(len(transactions)):
if transactions[i]["to"]==address:
investors[transactions[i]["from"]]=self.convert_dollar(transactions[i]["value"])
return investors
def convert_dollar(self, value, rate):
return float(value)*rate/1000000000000000000
def get_investors_dollars(self, address):
transactions=self.get_all_transactions(address, start=0, end=99999999)
investors={}
for i in range(len(transactions)):
if transactions[i]["to"]==address:
if transactions[i]["from"] not in investors:
investors[transactions[i]["from"]]=self.convert_dollar(transactions[i]["value"], self.rate)
else:
investors[transactions[i]["from"]]=investors[transactions[i]["from"]]+self.convert_dollar(transactions[i]["value"], self.rate)
return investors
def investors_to_csv(self, address, file_address):
investors=self.get_investors_dollars(address)
investments=[]
for i in investors:
investments.append([i,investments[i]])
pd.DataFrame(investments, columns=["From", "Value"]).to_csv(file_address)
def get_balance(self, address):
apirequest="https://api.etherscan.io/api?module=account&action=balance&address="+address+"&tag=latest&apikey="+self.apikey
r = requests.get(url=apirequest)
return float(r.json()["result"])
def get_balance_dollar(self, address):
apirequest="https://api.etherscan.io/api?module=account&action=balance&address="+address+"&tag=latest&apikey="+self.apikey
r = requests.get(url=apirequest)
return convert_dollar(r.json()["result"])
def get_all_useful_transactions(self, address):
transactions=self.get_all_transactions(address)
useful_transactions=[]
for trs in transactions:
useful_transactions.append([trs["from"],trs["to"], trs["value"], trs["blockNumber"]])
return useful_transactions
def transactions_to_csv(self, address, file_address):
transactions=pd.DataFrame(self.get_all_useful_transactions(address), columns=["From", "To", "Value", "Block"])
transactions.to_csv(file_address)
def get_transaction_values(self, address):
transactions=self.get_all_useful_transactions(address)
transactions_values={}
for trs in transactions:
if (trs[0],trs[1]) in transactions_values:
transactions_values[(trs[0],trs[1])]=transactions_values[(trs[0],trs[1])]+trs[2]
else:
transactions_values[(trs[0],trs[1])]=trs[2]
return transactions_values
if __name__ == '__main__':
if len(sys.argv) > 1:
apiKey=sys.argv[1]
scrapper=EthScrapping(apiKey)
if len(sys.argv)>2:
address=sys.argv[2]
else:
address="0xd24400ae8BfEBb18cA49Be86258a3C749cf46853"
print(scrapper.get_transactions(address))
else:
print("Error. No API key given.")<file_sep># ethereumTransactionsAnalysis
Useful classes to request Etherscan's API and analyze the behavior of Ethereum accounts in order to discover patterns for fraud, speculation on tokens, transactions' source identity hiding.
<file_sep>import sys
sys.path.append("..")
from ethScrapping import EthScrapping
import logging
logger = logging.getLogger(__name__)
log_handler = logging.StreamHandler()
log_handler.setFormatter(logging.Formatter('%(asctime)s : %(processName)s : %(levelname)s : %(message)s'))
logger.addHandler(log_handler)
logger.setLevel(logging.getLevelName("DEBUG"))
if len(sys.argv) > 1:
scrapper=EthScrapping(sys.argv[1])
address="0xbbc79794599b19274850492394004087cbf89710"
file_to_save="../Results/bancorInvestors.csv"
logger.debug("Loading transactions...")
scrapper.transactions_to_csv(address, file_to_save)
scrapper.investors_to_csv(address, file_to_save) | 4e666e1a0d078f2a4e1db1569c63ce8c7971448c | [
"Markdown",
"Python"
] | 3 | Python | DennisLeoUTS/ethereumTransactionsAnalysis | 3ed1b0451c549de699458912f1807e8cb037c122 | c9ad7a38aefae96cfeee4be8a454057031ed1c20 |
refs/heads/master | <file_sep>package main
import (
"github.com/draringi/go-libtrue"
"os"
"log"
)
func main() {
val := truth.GetTrue()
if !val {
log.Fatal("Wrong value")
}
os.Exit(0)
}
<file_sep>package truth
// #cgo LDFLAGS: -L/usr/local/lib -ltrue
// #include <stdbool.h>
// bool get_true();
//
// int bool_to_int(bool b) {
// return b;
// }
import "C"
// GetTrue returns the truth
// You can't handle the truth.
func GetTrue() bool {
val := C.get_true()
converted := C.bool_to_int(val)
if converted == 0 {
return false
}
return true
}
<file_sep># go-libtrue
Wrapper for [libtrue](https://github.com/zxombie/libtrue), allowing the lesser language go to gaze upon the truth
## Installation
Use `go get github.com/draringi/go-libtrue/cmd/...` to install both library and binary.
<file_sep>package truth
import "testing"
func TestGetTrue(t *testing.T) {
val := GetTrue()
expected := true
if val != expected {
t.Fatalf("Expected '%v', got '%v'", expected, val)
}
}
| 5e2982d1eeb767622fbf814838ae29624f306c91 | [
"Markdown",
"Go"
] | 4 | Go | draringi/go-libtrue | 6ab3d43a95c31ae775fc8b02c8348feb8f459cb3 | 214768737fda62864d3d3d7720ad3239e237ed5f |
refs/heads/master | <file_sep># allocation-table
[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/allocation-table)<file_sep>import { Component, OnInit } from '@angular/core';
declare var $:any;
var allocationData = [
[
[
{cropType: "type-2", size: "40 CM", "postingStatus": true,"precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100, "greenHouse": 'GH1', "family" : "Rose", "variety": "Rose Upper Class","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{cropType: "type-2", size: "60 CM", "postingStatus": true, "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH2',"family" : "Rose", "variety": "Rose Fuschiana","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true, cropType: "type-2", size: "80 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH3',"family" : "Rose", "variety": "Rose Jupiter","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true, cropType: "type-2", size: "100 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH4',"family" : "Rose", "variety": "Rose Memory","color": "Pink Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true, cropType: "type-2", size: "120 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH5',"family" : "Rose", "variety": "Rose Red Calypso","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true, cropType: "type-2", size: "120 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH6',"family" : "Rose", "variety": "Rose Red Tourch","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
],
[
{cropType: "type-2", size: "40 CM", "postingStatus": false,"precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100, "greenHouse": 'GH1', "family" : "Rose", "variety": "Rose Upper Class","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{cropType: "type-2", size: "60 CM", "postingStatus": false, "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH2',"family" : "Rose", "variety": "Rose Fuschiana","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false, cropType: "type-2", size: "80 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH3',"family" : "Rose", "variety": "Rose Jupiter","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false, cropType: "type-2", size: "100 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH4',"family" : "Rose", "variety": "Rose Memory","color": "Pink Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false, cropType: "type-2", size: "120 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH5',"family" : "Rose", "variety": "Rose Red Calypso","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false, cropType: "type-2", size: "120 CM", "precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100,"greenHouse": 'GH6',"family" : "Rose", "variety": "Rose Red Tourch","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
],
],
[
[
{"postingStatus": true,size: "40 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH1',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true,size: "60 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600, time: "11.30","ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH2',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true,size: "80 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH3',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true,size: "100 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH4',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true,size: "120 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH5',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": true,size: "120 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600, time: "11.30","ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH6',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 }
],
[
{"postingStatus": false,size: "40 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH1',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false,size: "60 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600, time: "11.30","ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH2',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false,size: "80 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH3',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false,size: "100 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH4',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false,size: "120 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600,time: "11.30", "ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH5',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{"postingStatus": false,size: "120 CM",cropType: "type-1","precoolPostHarvestRejection": 50,"ghOutput":600, time: "11.30","ghRejection": 100,"receivingAreaCollection": 500, "gradingRejection": 50,"greenHouse": 'GH6',"family" : "Chrysanthemum", "variety": "Euro Champagne Yellow","color": "Yellow", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 }
]
],
]
var customers = [
{id: 1 , custName: '<NAME>'},
{id: 2 , custName: '<NAME>'},
{id: 3 , custName: '<NAME>'},
{id: 4 , custName: '<NAME>'},
{id: 5 , custName: '<NAME>'},
// {id: 6 , custName: '<NAME>'},
// {id: 7 , custName: '<NAME>'},
// {id: 8 , custName: '<NAME>'},
// {id: 9 , custName: '<NAME>'},
// {id: 10 , custName: '<NAME>'},
]
var arr = [
[
{cropType: "type-2", size: "40 CM", "postingStatus": true,"precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100, "greenHouse": 'GH1', "family" : "Rose", "variety": "Rose Upper Class","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
{cropType: "type-2", size: "40 CM", "postingStatus": true,"precoolPostHarvestRejection": 0,"ghOutput":600, "ghRejection": 100,"receivingAreaCollection": 500,time: "11.30", "gradingRejection": 100, "greenHouse": 'GH1', "family" : "Rose", "variety": "Rose Upper Class","color": "Red", "date": "06/10", "harvest": 500, "rejection": 100, "output": 400 },
]
]
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.scss' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
tableData =[];
i = 0;
dateArr = [];
allocationData = allocationData;
customersList = customers;
constructor() {
this.tableData = this.allocationData;
const td = new Date();
const dd = td.getDate();
var mm = td.getMonth() + 1;
let arr = [];
for (let index = 0; index <= 2; index++) {
const ppDate = dd + index + '/' + mm;
arr.push(ppDate);
}
this.dateArr = arr;
}
getFlowers(item) { ;
let arr = [];
let array =[];
for(const i of item){
array = i;
for (let index = 0; index < i.length; index++) {
const element = array[index];
arr.push(item[index]);
}
}
return item[1];
}
ngOnInit() {
}
edit(data) {
// if(!data.postingStatus) {
// this.dialogRef = this.dialog.open(SumamryDetailComponent, {width: '70%'});
// this.dialogRef.componentInstance.data = data;
// const closeSub = this.dialogRef.componentInstance.dataSaved.subscribe((res: any) => {
// if(!res) {
// this.dialogRef.close();
// return;
// }
// this.dialogRef.close();
// this.dialogRef.afterClosed().subscribe(() => {
// closeSub.unsubscribe();
// this.toastr.success('Updated Sucessfully.')
// })
// });
// }
}
onSubmit(data: any){
// Swal.fire({
// title: 'Are you sure?',
// text: "Once submited, you will not be able to edit this records!",
// type: 'warning',
// showCancelButton: true,
// confirmButtonColor: '#3085d6',
// cancelButtonColor: '#d33',
// confirmButtonText: 'Ok',
// }).then((result) => {
// if (result.value) {
// Swal.fire(
// 'Updated!',
// 'Selected column submitted successfully.!',
// 'success'
// )
// }
// })
}
consoleFn(i){
// console.log(i);
}
disableSAPButton(idx) {
if(idx === 0) {
return true;
} else {
return false;
}
}
cancel() {
// this.dialogRef.close();
}
findDateRef(idx) {
if(idx < 1 ) {
return `(T)`;
}else if(idx === 1) {
return `(T + ${idx})`;
} else if(idx > 2) {
return `(T + ${idx -2 })`;
}
}
findTodayColor(idx: number){
if(idx === 0) {
//today color
return '#81c784';
} else if(idx === 1) {
//tomorrow color
return '#2ecc72';
} else if(idx === 2) {
return '#81c784'
}
}
getDate(item) {
return item.date;
}
getVariety(item) {
for(const i of item) {
return i.variety;
}
}
getFamily(item){
for(const i of item) {
for(const j of i) {
return j.family;
}
}
}
summaryCalc(item, idx) {
let harvest = 0;
let rejection = 0;
let output = 0;
for(const i of item) {
harvest += i.harvest;
rejection += i.rejection;
output += i.output;
}
return {harvest : harvest, rejection: rejection, output: output};
}
getStatus(item) {
for(const i of item) {
if(i.postingStatus){
return true;
}else {
return false;
}
}
}
getStatus2(item) {
const array = item;
for (let index = 0; index < array.length; index++) {
const element = array[index];
if(index === 0) {
if(element.postingStatus) {
return 1;
}
}else if(index === 1) {
if(element.postingStatus) {
return 2;
}
} else if(index === 2) {
if(element.postingStatus) {
return 3;
}
}
}
return 0;
}
getDescription(arr) {
let item = [];
for(let i of arr){
for(let j of i) {
item = j;
}
}
return item;
}
brClass(obj) {
if(obj.c === 4 && this.i == 1) {
this.i++;
return 'check';
}
if(obj.c === 4 && this.i ==0) {
this.i = 1;
console.log(obj)
}
return '';
}
displayDate(val) {
const pivot = Math.ceil((this.customersList.length / 2));
if(val === pivot) {
return '';
}
return 'none';
}
keyNavigation() {
// $(document).ready(function () {
// $(this).each(function () {
// $(this).find('input').on('keyup', function (e) {
// switch (e.which) {
// case 39:
// $(this).closest('div').parent().next().children().eq($(this).closest('div').index()).find('input').focus();
// break;
// case 37:
// $(this).closest('div').parent().prev().children().eq($(this).closest('div').index()).find('input').focus();
// break;
// case 40:
// e.preventDefault();
// $(this).closest('div').next().find('input').focus();
// break;
// case 38:
// $(this).closest('div').prev().find('input').focus();
// break;
// }
// });
// $(this).find('input').on('keydown', function (e) {
// if (e.which === 38 || e.which === 40) {
// e.preventDefault();
// }
// });
// });
// // Disable scroll when focused on a number input.
// $(this).on('focus', 'input[type=number]', function (e) {
// $(this).on('wheel', function (e) {
// e.preventDefault();
// });
// });
// })
}
}
| 7fa3f032a8a933ae286ce323cee50f9c452cd8ef | [
"Markdown",
"TypeScript"
] | 2 | Markdown | ksiranjeevi92/allocation-table | 4859ffb1154e596e354ae9f896ea881e245941b2 | 64040c28b4399274546e0d82ef3aea4c5b53af5e |
refs/heads/develop | <repo_name>telerik/kendo-vscode-extensions<file_sep>/templates/Web/_composition/ReactJS/Page.React.AddHome/src/App_postaction.jsx
class App extends Component {
render() {
return (
<React.Fragment>
<NavBar />
<Switch>
//{[{
<Redirect exact path = "/" to = "/Param_HomePageName" />
//}]}
</Switch>
<Footer />
</React.Fragment>
);
}
}<file_sep>/src/client/src/reducers/generationStatus/index.ts
import { combineReducers } from "redux";
import { statusMessage } from "./statusMessage";
import { genStatus } from "./genStatus";
export default combineReducers({
statusMessage,
genStatus
});
<file_sep>/src/client/src/reducers/wizardSelectionReducers/updateProjectName.ts
import { WIZARD_SELECTION_TYPEKEYS } from "../../actions/wizardSelectionActions/typeKeys";
import { IValidation } from "./updateOutputPath";
import WizardSelectionActionType from "../../actions/wizardSelectionActions/wizardSelectionActionType";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
/* State Shape
{
projectName: string,
validation: {
isValid: false,
error: string
}
}
*/
export interface IProjectName {
projectName: string;
validation: IValidation;
}
const initialState = {
projectName: "",
validation: {
isValid: false,
error: ""
}
};
const projectNameReducer = (
state: IProjectName = initialState,
action: WizardSelectionActionType | WizardInfoType
) => {
switch (action.type) {
case WIZARD_SELECTION_TYPEKEYS.UPDATE_PROJECT_NAME:
return action.payload;
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return initialState;
default:
return state;
}
};
export default projectNameReducer;
<file_sep>/src/client/src/actions/ActionType.ts
import AzureActionType from "./azureActions/azureActionType";
import ModalActionType from "./modalActions/modalActionType";
import VSCodeActionTypes from "./vscodeApiActions/VSCodeActionType";
import WizardContentActionType from "./wizardContentActions/wizardContentActionType";
import WizardSelectionActionType from "./wizardSelectionActions/wizardSelectionActionType";
import WizardInfoActionType from "./wizardInfoActions/wizardInfoActionType";
type RootAction =
| AzureActionType
| ModalActionType
| VSCodeActionTypes
| WizardContentActionType
| WizardSelectionActionType
| WizardInfoActionType;
export default RootAction;
<file_sep>/src/extension/src/scripts/generate-test.ts
import { CoreTemplateStudio } from "../coreTemplateStudio";
import { CONSTANTS } from "../constants";
let instance: CoreTemplateStudio;
let backends: string[] = [];
let frontends: string[] = [];
const projType = "FullStackWebApp";
let syncAttemptNum = 0;
let prevPromise: Promise<any> = Promise.resolve(null);
const delay = (time: number) => {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
};
let getPagesObj = (
instance: CoreTemplateStudio,
frontend: string,
backend: string
) => {
return instance
.getPages(projType, frontend, backend)
.then(pages => {
return pages.map((page: { name: string; templateId: string }) => {
return { name: page.name, identity: page.templateId };
});
})
.catch((error: Error) => {
console.log(error.toString());
});
};
let generateProj = (
instance: CoreTemplateStudio,
backend: string,
frontend: string
) => {
return getPagesObj(instance, frontend, backend).then(pagesObj => {
return instance.generate({
port: instance.getPort(),
payload: {
backendFramework: backend,
frontendFramework: frontend,
pages: pagesObj,
path: "../../../../../src/extension/src/template_test",
projectName: backend + "-" + frontend,
projectType: projType,
services: []
},
liveMessageHandler: value => {
value;
}
});
});
};
let attemptSync: any = (
instanceObj: CoreTemplateStudio,
syncAttemptNum: number
) => {
if (syncAttemptNum >= CONSTANTS.API.MAX_SYNC_REQUEST_ATTEMPTS) {
CoreTemplateStudio.DestroyInstance();
throw new Error("too many failed sync requests");
}
return instanceObj
.sync({
port: instance.getPort(),
payload: { path: CONSTANTS.API.DEVELOPMENT_PATH_TO_TEMPLATES },
liveMessageHandler: value => {
value;
}
})
.then(async () => {
return await instance.getFrameworks(projType);
})
.then(frameworks => {
frameworks.forEach((obj: { tags: { type: string }; name: string }) => {
if (obj.tags.type == "frontend") {
frontends.push(obj.name);
} else if (obj.tags.type == "backend") {
backends.push(obj.name);
}
});
frontends.forEach(frontendFrameWork => {
backends.forEach(backendFramework => {
prevPromise = prevPromise.then(() =>
generateProj(instance, backendFramework, frontendFrameWork)
);
});
});
prevPromise.then(() => {
console.log("project generation complete");
CoreTemplateStudio.DestroyInstance();
});
})
.catch(() => {
syncAttemptNum++;
return delay(3000).then(() => attemptSync(instance, syncAttemptNum));
});
};
CoreTemplateStudio.GetInstance(undefined)
.then(res => {
instance = res;
})
.then(() => {
return attemptSync(instance, syncAttemptNum);
})
.catch((error: Error) => {
throw Error(error.toString());
});
<file_sep>/src/client/src/reducers/wizardContentReducers/backendFrameworkReducer.ts
import { WIZARD_CONTENT_TYPEKEYS } from "../../actions/wizardContentActions/typeKeys";
import WizardContentActionType from "../../actions/wizardContentActions/wizardContentActionType";
import { IOption } from "../../types/option";
/* State Shape
{
backendOptions: []
}
*/
const backendFrameworkOptions = (
state: IOption[] = [],
action: WizardContentActionType
) => {
switch (action.type) {
case WIZARD_CONTENT_TYPEKEYS.GET_BACKEND_FRAMEWORKS_SUCCESS:
const newState = [...state];
for (const frameworkToAdd of action.payload) {
let found = false;
for (const framework of newState) {
if (framework.internalName === frameworkToAdd.internalName) {
found = true;
}
}
if (!found) {
newState.push(frameworkToAdd);
}
}
return newState;
default:
return state;
}
};
export default backendFrameworkOptions;
<file_sep>/src/client/src/actions/vscodeApiActions/VSCodeActionType.ts
import { IVSCodeAPIActionType } from "./getVSCodeApi";
type VSCodeActionTypes = IVSCodeAPIActionType;
export default VSCodeActionTypes;
<file_sep>/docs/install.md
# Web Template Studio Installation Instructions
## Prerequisites
Web Template Studio runs as a VSCode extension and hence you'll need to have _VScode_ version 1.33 or above installed.
Also, you'll need [_Node_](https://nodejs.org/en/download/) and _npm_/[_yarn_](https://yarnpkg.com/en/docs/install) to run the generated templates.
## Where is the offical release?
We are currently early in our development phase and only have a dev nightly on Visual Studio Marketplace.
## Installing the nightly dev branch build _preferred_
Head over to [Visual Studio Marketplace’s Web Template Studio page](https://marketplace.visualstudio.com/items?itemName=WASTeamAccount.WebTemplateStudio-dev-nightly) and click "[install](vscode:extension/WASTeamAccount.WebTemplateStudio-dev-nightly)" 😊.
## Installing the latest Microsoft Web Template Studio release manually
1. Get the latest release from Web Template Studio [Github releases](https://github.com/Microsoft/WebTemplateStudio/releases)
2. Scroll down to _Assets_ and download the `.vsix` file
3. Open VSCode
4. Open the extensions menu from VSCode sidebar
5. Click on the ellipsis in the upper right hand corner
6. Choose _Install from VSIX_
7. Select the `.vsix` you downloaded earlier. Web Template Studio is now ready to use

#### Run the Release
- Open **VSCode**
- Press `ctrl+shift+p`to open VSCode's extension launcher
- Type/Select `Web Template Studio: Launch` and press `Enter` to launch the extension
<file_sep>/src/client/src/mockData/leftSidebarData.ts
const leftSidebarData: string[] = [
"1. Name and Output",
"2. Project Type",
"3. Frameworks",
"4. Pages",
"5. Services (Optional)",
"6. Summary"
];
export default leftSidebarData;
<file_sep>/src/client/src/setupTests.ts
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { IntlProvider, FormattedRelative } from "react-intl";
/**
* This setup file configures the Enzyme Adapter and is executed before running the tests
* https://facebook.github.io/create-react-app/docs/running-tests#initializing-test-environment
*/
configure({ adapter: new Adapter() });
const intlProvider = new IntlProvider({ locale: "en" }, {});
const { intl } = intlProvider.getChildContext();
global.intl = intl;
<file_sep>/templates/_catalog/frontendframeworks/KendoVue.md
Every UI component in Native Kendo UI for Vue suite, from the data grid to the dropdowns and inputs, has been built from the ground-up specifically for Vue. <file_sep>/templates/Web/_composition/Features/Feature.Azure.FunctionsMerging/README_postaction.md
## Next Steps
//^^
//{[{
### Azure Functions
An Azure Function with a Node runtime stack and HTTP trigger has been deployed to Azure. Microsoft Web Template Studio
has also generated a folder containing the code deployed to Azure Functions. To edit and redeploy the Azure
Function it is recommended to install the [Azure Functions Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions). Additional documentation can be found here: [Azure Function Docs](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/services/azure-functions.md).
//}]}
### Deployment
The generated templates can be deployed to Azure App Service using the following steps:
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.SQL/server/sql/settings.py
import os
from os.path import join, dirname, realpath
from dotenv import load_dotenv
#create .env file path
dotenv_path = join(dirname(dirname(dirname(realpath(__file__)))), '.env')
#load file from path
load_dotenv(dotenv_path)
#access env file variables
connection_key = os.getenv('COSMOSDB_URI')
master_key = os.getenv('COSMOSDB_PRIMARY_KEY')<file_sep>/src/client/src/reducers/wizardSelectionReducers/services/index.ts
import { combineReducers } from "redux";
import azureFunctions from "./azureFunctionsReducer";
import cosmosDB from "./cosmosDbReducer";
const serviceReducer = combineReducers({
azureFunctions,
cosmosDB
});
export type ServiceState = ReturnType<typeof serviceReducer>;
export default serviceReducer;
<file_sep>/src/extension/src/utils/vscodeUI.ts
import * as vscode from "vscode";
import { WizardServant, IPayloadResponse } from "../wizardServant";
import {
ExtensionCommand,
DialogMessages,
DialogResponses
} from "../constants";
export class VSCodeUI extends WizardServant {
clientCommandMap: Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
>;
/**
*
*/
constructor() {
super();
this.clientCommandMap = this.defineCommandMap();
}
private defineCommandMap(): Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
> {
return new Map([
[ExtensionCommand.ResetPages, this.promptUsersToResetPages]
]);
}
async promptUsersToResetPages(message: any) {
if (message.payload.pagesLength > 0) {
return await vscode.window
.showInformationMessage(
DialogMessages.resetPagesPrompt,
...[DialogResponses.yes, DialogResponses.no]
)
.then((selection: vscode.MessageItem | undefined) => {
let userConfirmation = {
resetPages: false,
internalName: message.payload.internalName
};
if (selection === DialogResponses.yes) {
userConfirmation = {
resetPages: true,
internalName: message.payload.internalName
};
}
return { payload: userConfirmation };
});
} else {
return {
payload: {
resetPages: true,
internalName: message.payload.internalName
}
};
}
}
}
<file_sep>/templates/Web/Projects/KendoReactDefault/src/components/Home.jsx
import React from 'react';
import ComponentsIcon from './img/components.svg';
import StylesIcon from './img/styles.svg';
import BlogsIcon from './img/blogs.svg';
import TutorialsIcon from './img/tutorials.svg';
import Kendoka from './img/kendoka.svg';
const Home = (props) => {
return (
<div className="container mt-5">
<div className='row'>
<div className='col-12'>
<h1 className='welcome mb-0'>Welcome to KendoReact</h1>
<h2 className='sub-header mt-0'>This is a sample application built with KendoReact - a set of over 80 UI components built from the ground-up specifically for React.</h2>
</div>
</div>
<div className='row'>
<div className='col-12'>
<h1 className='get-started'>Get Started</h1>
</div>
</div>
<div className='row justify-content-center'>
<div className='col-6 text-right'>
<div className='kendoka-div'>
<img className='kendoka' src={Kendoka} alt='kendoka' />
</div>
</div>
<div className='col-6 components-list'>
<p>
<img src={ComponentsIcon} alt='components' />
<a href='https://www.telerik.com/kendo-react-ui/components/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext'>Components & Documentation</a>
</p>
<p>
<img src={StylesIcon} alt='styles' />
<a href='https://www.telerik.com/kendo-react-ui/components/styling/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext'>KendoReact Themes Overview</a>
</p>
<p>
<img src={BlogsIcon} alt='blogs' />
<a href='https://www.telerik.com/blogs/tag/react?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext'>Blog Posts</a>
</p>
<p>
<img src={TutorialsIcon} alt='tutorials' />
<a href='https://www.telerik.com/kendo-react-ui/react-hooks-guide/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext'>Tutorials</a>
</p>
</div>
</div>
</div>
)
}
export default Home;
<file_sep>/src/client/src/reducers/index.ts
import { combineReducers } from "redux";
import azureProfileData from "./azureLoginReducers";
import dependencyInfo from "./dependencyInfoReducers";
import generationStatus from "./generationStatus";
import modals from "./modalReducers";
import wizardContent from "./wizardContentReducers";
import wizardRoutes from "./wizardRoutes";
import vscodeApi from "./vscodeApiReducer";
import selection from "./wizardSelectionReducers";
import versions from "./versionsReducer";
const rootReducer = combineReducers({
vscode: vscodeApi,
wizardContent,
selection,
azureProfileData,
modals,
wizardRoutes,
generationStatus,
versions,
dependencyInfo
});
export type AppState = ReturnType<typeof rootReducer>;
export default rootReducer;
<file_sep>/src/client/src/actions/wizardSelectionActions/selectBackEndFramework.ts
import { ISelected } from "../../types/selected";
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
export interface ISelectBackendAction {
type: WIZARD_SELECTION_TYPEKEYS.SELECT_BACKEND_FRAMEWORK;
payload: ISelected;
}
const selectBackendFrameworkAction = (
backendFramework: ISelected
): ISelectBackendAction => ({
type: WIZARD_SELECTION_TYPEKEYS.SELECT_BACKEND_FRAMEWORK,
payload: backendFramework
});
export { selectBackendFrameworkAction };
<file_sep>/templates/Web/Pages/React.MasterDetail/src/components/ReactMasterDetail/MasterDetailPage.jsx
import React from "react";
import classnames from "classnames";
import styles from "./masterdetail.module.css";
export default function MasterDetailPage(props) {
const {
longDescription,
title,
status,
shipTo,
orderTotal,
orderDate
} = props.textSampleData;
return (
<div className="col">
<div className={classnames("row", styles.heading)}>
<div className="col">
<h3 className="ml-3 mb-4">{title}</h3>
</div>
</div>
<div className="row">
<div className="col-12 mt-3">
<nav aria-label="breadcrumb">
<ol className="breadcrumb bg-white mb-0">
<li className="breadcrumb-item">
<a className={styles.breadCrumbLink} href="/ReactMasterDetail">
ReactMasterDetail
</a>
</li>
<li className="breadcrumb-item active" aria-current="page">
{title}
</li>
</ol>
</nav>
</div>
<div className="col-md-8 col-12 ml-3 mb-5">
<p className={styles.title}>Status</p>
<p>{status}</p>
<p className={styles.title}>Order Date</p>
<p>{orderDate}</p>
<p className={styles.title}>Ship To</p>
<p>{shipTo}</p>
<p className={styles.title}>Order Total</p>
<p>{orderTotal}</p>
<p className={styles.title}>Description</p>
<p>{longDescription}</p>
</div>
</div>
</div>
);
}
<file_sep>/templates/_catalog/frontendframeworks/KendoReact.md
Every UI component in the KendoReact suite, from the data grid and charts to date pickers and dropdowns, has been built from the ground-up specifically for React.<file_sep>/src/client/src/actions/azureActions/saveCosmosDbSettings.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
export interface ISaveCosmosDbSettings {
type: AZURE_TYPEKEYS.SAVE_COSMOS_DB_RESOURCE_SETTINGS;
payload: any;
}
export interface IRemoveCosmosDbSettings {
type: AZURE_TYPEKEYS.REMOVE_COSMOS_RESOURCE;
payload: number;
}
const saveCosmosDbSettingsAction = (
cosmosDbSettings: any
): ISaveCosmosDbSettings => ({
type: AZURE_TYPEKEYS.SAVE_COSMOS_DB_RESOURCE_SETTINGS,
payload: cosmosDbSettings
});
const removeCosmosSelectionAction = (
selectionIndex: number
): IRemoveCosmosDbSettings => ({
type: AZURE_TYPEKEYS.REMOVE_COSMOS_RESOURCE,
payload: selectionIndex
});
export { saveCosmosDbSettingsAction, removeCosmosSelectionAction };
<file_sep>/templates/_catalog/frontendframeworks/KendoAngular.md
Engineered specifically for Angular, this suite enables you to take full advantage of the framework’s native performance capabilities such as AOT Compilation, Angular Universal Rendering and Tree Shaking.<file_sep>/templates/Web/Pages/React.MasterDetail/src/components/ReactMasterDetail/index.jsx
import React, { Component } from "react";
import classnames from "classnames";
import WarningMessage from "../WarningMessage";
import MasterDetailPage from "./MasterDetailPage";
import MasterDetailSideBarTab from "./MasterDetailSideBarTab";
import GreyAvatar from "../../images/GreyAvatar.svg";
import styles from "./masterdetail.module.css";
import CONSTANTS from "../../constants";
export default class ReactMasterDetail extends Component {
constructor(props) {
super(props);
this.state = {
currentDisplayTabIndex: 0,
masterDetailText: [
{
shortDescription: "",
longDescription: "",
title: "",
status: "",
shipTo: "",
orderTotal: 0.0,
orderDate: "",
id: 0
}
]
};
this.handleDisplayTabClick = this.handleDisplayTabClick.bind(this);
this.handleWarningClose = this.handleWarningClose.bind(this);
}
// Get the sample data from the back end
componentDidMount() {
fetch(CONSTANTS.ENDPOINT.MASTERDETAIL)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(result => {
this.setState({ masterDetailText: result });
})
.catch(error =>
this.setState({
WarningMessageOpen: true,
WarningMessageText: `${
CONSTANTS.ERROR_MESSAGE.MASTERDETAIL_GET
} ${error}`
})
);
}
handleWarningClose() {
this.setState({
WarningMessageOpen: false,
WarningMessageText: ""
});
}
handleDisplayTabClick(id) {
this.setState({ currentDisplayTabIndex: id });
}
render() {
const {
masterDetailText,
currentDisplayTabIndex,
WarningMessageOpen,
WarningMessageText
} = this.state;
return (
<main id="mainContent">
<div className="container-fluid">
<div className="row">
<div
className={classnames(
"col-2",
"p-0",
"border-right",
styles.sidebar
)}
>
<div className="list-group list-group-flush border-bottom">
{masterDetailText.map((textAssets, index) => (
<MasterDetailSideBarTab
onDisplayTabClick={this.handleDisplayTabClick}
tabText={textAssets.title}
image={GreyAvatar}
index={index}
key={textAssets.id}
/>
))}
</div>
</div>
<MasterDetailPage
textSampleData={masterDetailText[currentDisplayTabIndex]}
/>
</div>
</div>
<WarningMessage
open={WarningMessageOpen}
text={WarningMessageText}
onWarningClose={this.handleWarningClose}
/>
</main>
);
}
}
<file_sep>/src/client/src/actions/wizardInfoActions/updateGenStatusActions.ts
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
import { IServiceStatus } from "../../reducers/generationStatus/genStatus";
export interface IUpdateGenStatusMessage {
type: WIZARD_INFO_TYPEKEYS.UPDATE_TEMPLATE_GENERATION_STATUS_MESSAGE;
payload: string;
}
export interface IUpdateGenStatus {
type: WIZARD_INFO_TYPEKEYS.UPDATE_TEMPLATE_GENERATION_STATUS;
payload: IServiceStatus;
}
const updateTemplateGenerationStatusMessageAction = (status: string): IUpdateGenStatusMessage => ({
type: WIZARD_INFO_TYPEKEYS.UPDATE_TEMPLATE_GENERATION_STATUS_MESSAGE,
payload: status
});
const updateTemplateGenerationStatusAction = (
isGenerated: IServiceStatus
): IUpdateGenStatus => ({
type: WIZARD_INFO_TYPEKEYS.UPDATE_TEMPLATE_GENERATION_STATUS,
payload: isGenerated
});
export {
updateTemplateGenerationStatusMessageAction,
updateTemplateGenerationStatusAction
};
<file_sep>/src/client/src/reducers/wizardSelectionReducers/updateOutputPath.ts
import { FormattedMessage } from "react-intl";
import { WIZARD_SELECTION_TYPEKEYS } from "../../actions/wizardSelectionActions/typeKeys";
import WizardSelectionActionType from "../../actions/wizardSelectionActions/wizardSelectionActionType";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
/* State Shape
{
outputPath: string,
validation: {
isValid: false,
error: string
}
}
*/
export interface IValidation {
isValid: boolean;
error: string | FormattedMessage.MessageDescriptor;
}
export interface IOutputPath {
outputPath: string;
validation?: IValidation;
}
const initialState = {
outputPath: "",
validation: undefined
};
const outputPathReducer = (
state: IOutputPath = initialState,
action: WizardSelectionActionType | WizardInfoType
) => {
switch (action.type) {
case WIZARD_SELECTION_TYPEKEYS.UPDATE_OUTPUT_PATH:
return {
...state,
outputPath: action.payload
};
case WIZARD_SELECTION_TYPEKEYS.SET_PROJECT_PATH_VALIDATION:
return {
...state,
validation: {
...action.payload
}
};
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return initialState;
default:
return state;
}
};
export default outputPathReducer;
<file_sep>/src/client/src/actions/wizardContentActions/getProjectTypes.ts
import EngineAPIService from "../../services/EngineAPIService";
import { IMetadata } from "../../types/metadata";
import { IOption } from "../../types/option";
import { getProjectTypesSuccess } from "./getProjectTypesSuccess";
import getSvgUrl from "../../utils/getSvgUrl";
import WizardContentActionType from "./wizardContentActionType";
import { Dispatch } from "react";
// thunk
export const getProjectTypesAction = (serverPort: number) => {
return async (dispatch: Dispatch<WizardContentActionType>) => {
const api = new EngineAPIService(serverPort, undefined);
try {
const projectTypesJson = await api.getProjectTypes();
if (projectTypesJson.detail == null) {
dispatch(
getProjectTypesSuccess(
getOptionalFromMetadata(getMetadataFromJson(projectTypesJson))
)
);
} else {
console.log("FAILED");
}
} catch (error) {
console.log(error);
}
};
};
function getMetadataFromJson(items: any[]): IMetadata[] {
return items.map<IMetadata>(val => ({
name: val.name,
displayName: val.displayName,
summary: val.summary,
longDescription: val.description,
position: val.order,
licenses: val.licenses,
svgUrl: val.icon,
tags: val.tags,
selected: false,
author: val.author
}));
}
function getOptionalFromMetadata(items: IMetadata[]): IOption[] {
return items.map<IOption>(val => ({
title: val.displayName,
internalName: val.name,
body: val.summary,
longDescription: val.longDescription,
position: val.position,
svgUrl: getSvgUrl(val.name),
selected: val.selected,
licenses: val.licenses
}));
}
<file_sep>/src/client/src/actions/wizardSelectionActions/selectWebApp.ts
import { ISelected } from "../../types/selected";
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
export interface ISelectProjectTypeAction {
type: WIZARD_SELECTION_TYPEKEYS.SELECT_WEB_APP;
payload: ISelected;
}
const selectWebAppAction = (
selectedApp: ISelected
): ISelectProjectTypeAction => ({
type: WIZARD_SELECTION_TYPEKEYS.SELECT_WEB_APP,
payload: selectedApp
});
export { selectWebAppAction };
<file_sep>/src/client/src/mockData/webAppOptions.ts
import blankpage from "../assets/blankpage.svg";
import { IOption } from "../types/option";
const options: IOption[] = [
{
svgUrl: process.env.REACT_APP_RELATIVE_PATH + blankpage,
title: "Full Stack App",
internalName: "FullstackApp",
body: "A single page application with a local back-end server.",
selected: false
},
{
svgUrl: undefined,
title: "RESTful API",
internalName: "RestulfApi",
body: "A RESTful API with no front-end user interface.",
selected: false
}
];
const getWebAppOptions = (): Promise<IOption[]> => {
return Promise.resolve(options);
};
export default getWebAppOptions;
<file_sep>/src/client/src/reducers/wizardContentReducers/pagesOptionsReducer.ts
import { WIZARD_CONTENT_TYPEKEYS } from "../../actions/wizardContentActions/typeKeys";
import WizardContentActionType from "../../actions/wizardContentActions/wizardContentActionType";
import { IOption } from "../../types/option";
import { WIZARD_SELECTION_TYPEKEYS } from "../../actions/wizardSelectionActions/typeKeys";
import { IResetPagesAction } from "../../actions/wizardSelectionActions/selectPages";
/* State Shape
{
pageOptions: IOption[]
}
*/
const pageOptions = (
state: IOption[] = [],
action: WizardContentActionType | IResetPagesAction
) => {
switch (action.type) {
case WIZARD_CONTENT_TYPEKEYS.GET_PAGES_OPTIONS_SUCCESS:
return action.payload;
case WIZARD_SELECTION_TYPEKEYS.RESET_PAGES:
return [];
default:
return state;
}
};
export default pageOptions;
<file_sep>/templates/Web/Pages/KendoAngular.Form/src/app/components/Param_SourceName_Kebab/Param_SourceName_Kebab.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-Param_SourceName_Kebab',
templateUrl: './Param_SourceName_Kebab.component.html'
})
export class Param_SourceName_PascalComponent {
}
<file_sep>/templates/Web/_composition/KendoAngular/Page.Kendo.Angular.AddImports/src/app/app.module_postaction.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MenuModule } from '@progress/kendo-angular-menu';
import { GridModule } from '@progress/kendo-angular-grid';
import { ChartsModule } from '@progress/kendo-angular-charts';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { PopupModule } from '@progress/kendo-angular-popup';
import { InputsModule } from '@progress/kendo-angular-inputs';
import 'hammerjs';
import { HeaderComponent } from './components/header/header.component';
import { HomeComponent } from './components/home/home.component';
import { FooterComponent } from './components/footer/footer.component';
//{[{
import { Param_SourceName_PascalComponent } from "./components/Param_SourceName_Kebab/Param_SourceName_Kebab.component";
//}]}
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
//{[{
{ path: 'Param_SourceName_Kebab', component: Param_SourceName_PascalComponent },
//}]}
{ path: '**', redirectTo: 'home' }
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
HomeComponent,
//{[{
Param_SourceName_PascalComponent,
//}]}
FooterComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
FormsModule,
MenuModule,
BrowserAnimationsModule,
GridModule,
ChartsModule,
RouterModule.forRoot(routes),
DropDownsModule, PopupModule, InputsModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/extension/src/extension.ts
import * as vscode from "vscode";
import { Controller } from "./controller";
import { activateCallHomeTracking } from "./workspace/fileEvents"
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand(
"kendoTemplateExtension.wizardLaunch",
async () => {
Controller.getInstance(context, Date.now());
}
)
);
activateCallHomeTracking(context);
}
export function deactivate() {
Controller.dispose();
}
<file_sep>/src/client/src/selectors/azureFunctionsServiceSelector.ts
import _ from "lodash";
import { createSelector } from "reselect";
import { ISelectedAzureFunctionsService } from "../reducers/wizardSelectionReducers/services/azureFunctionsReducer";
import { AppState } from "../reducers";
import { ServiceState } from "../reducers/wizardSelectionReducers/services/index";
interface ISelectedDropdowns {
[key: string]: IDropDownOptionType | undefined;
subscription?: IDropDownOptionType;
resourceGroup?: IDropDownOptionType;
appName?: IDropDownOptionType;
runtimeStack?: IDropDownOptionType;
location?: IDropDownOptionType;
numFunctions?: IDropDownOptionType;
}
interface ISelectionInformation {
dropdownSelection: ISelectedDropdowns;
previousFormData: ISelectedAzureFunctionsService;
}
const getState = (state: AppState): AppState => state;
const getServicesSelector = (state: AppState): ServiceState =>
state.selection.services;
const getAzureFunctionsNamesSelector = (state: AppState) => {
if (state.selection.services.azureFunctions.selection[0]) {
return state.selection.services.azureFunctions.selection[0].functionNames;
}
};
const isAzureFunctionsSelected = (state: AppState): boolean => {
return !_.isEmpty(state.selection.services.azureFunctions.selection);
};
const isAzureFunctionsSelectedSelector = createSelector(
getState,
isAzureFunctionsSelected
);
const getAzureFunctionsOptions = (
state: AppState,
isAzureFunctionsSelected: boolean
): any => {
if (isAzureFunctionsSelected) {
let selections = state.selection.services.azureFunctions.selection[0];
let updatedSelections;
if (selections.functionNames) {
updatedSelections = {
functionNames: selections.functionNames.map(functionNameObject => {
return functionNameObject.title;
}),
appName: selections.appName.value,
internalName: selections.internalName.value,
location: selections.location.value,
numFunctions: selections.numFunctions.value,
resourceGroup: selections.resourceGroup.value,
runtimeStack: selections.runtimeStack.value,
subscription: selections.subscription.value
};
} else {
updatedSelections = selections;
}
return updatedSelections;
}
};
const getAzureFunctionsOptionsSelector = createSelector(
getState,
isAzureFunctionsSelected,
getAzureFunctionsOptions
);
/**
* Returns the Azure Functions selection made by a developer.
* Returns undefined if a selection was not made.
* Currently, only one Azure Functions App can be added, hence
* the hardcoded value of 0 index.
*
* @param services
* @param isAzureFunctionsSelected
*/
const getAzureFunctionsSelectionInDropdownForm = (
services: ServiceState
): any => {
const { selection } = services.azureFunctions;
if (!_.isEmpty(selection)) {
const selectionInformation: ISelectionInformation = {
dropdownSelection: {},
previousFormData: selection[0]
};
for (const selectionKey in selectionInformation.previousFormData) {
let selectionInfo = selectionInformation.previousFormData[
selectionKey
] as IDropDownOptionType;
if (selectionKey) {
selectionInformation.dropdownSelection[selectionKey] = {
value: selectionInfo.value,
label: selectionInfo.label
} as IDropDownOptionType;
}
}
return selectionInformation;
}
};
const getFunctionsSelection = createSelector(
getServicesSelector,
getAzureFunctionsSelectionInDropdownForm
);
export {
getFunctionsSelection,
getAzureFunctionsOptionsSelector,
isAzureFunctionsSelectedSelector,
getAzureFunctionsNamesSelector
};
<file_sep>/templates/Web/_composition/NodeJS/Page.Node.List.AddRoutes.NoCosmos/server/sampleData$wts.Page.React.List_gpostaction.js
//{[{
const shortLoremIpsum = `Lorem id sint aliqua tempor tempor sit. Ad dolor dolor ut nulla mollit dolore non eiusmod Lorem tempor nisi cillum.`;
//}]}
const sampleData = {};
// This class holds sample data used by some generated pages to show how they can be used.
// TODO Web Template Studio: Delete this file once your app is using real data.
//{[{
// TODO Web Template Studio: If you use a database replace this ID with the ID created by the database
sampleData.listID = 3;
sampleData.listTextAssets = [
{
text: shortLoremIpsum,
_id: 1
},
{
text: shortLoremIpsum,
_id: 2
}
];
//}]}
module.exports = sampleData;
<file_sep>/src/client/src/actions/wizardInfoActions/updateDependencyInfo.spec.ts
import { updateDependencyInfoAction } from "./updateDependencyInfo";
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
describe("updateDependencyInfo actions", () => {
it("should create an action", () => {
const dependencyInfo = { dependency: "node" };
expect(updateDependencyInfoAction(dependencyInfo)).toEqual({
type: WIZARD_INFO_TYPEKEYS.UPDATE_DEPENDENCY_INFO,
payload: dependencyInfo
});
});
});
<file_sep>/templates/Web/_composition/Flask/Page.Flask.Cosmos.Mongo.AddMerging/README_postaction.md
## Next Steps
//^^
//{[{
### Cosmos Database
**Do Not share the keys stored in the .env file publicly.**
The Cosmos database will take approximately 5 minutes to deploy. Upon completion of deployment,
a notification will appear in VS Code and your connection string will be automatically added in
the .env file. The schema and operations for the Cosmos database are defined in `/server` folder.
Additional documentation can be found here: [Cosmos Docs](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/services/azure-cosmos.md).
//}]}
## File Structure
The back-end is based on [Flask](https://github.com/pallets/flask).
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
├── server/ - Flask server that provides API routes and serves front-end
//{[{
│ ├── mongo/ - Handles all interactions with the cosmos database
//}]}
│ ├── constants.py - Defines the constants for the endpoints and port
│ └── server.py - Configures Port and HTTP Server and provides API routes
└── README.md
```
## Additional Documentation
- Bootstrap CSS - https://getbootstrap.com/
//^^
//{[{
- Cosmos DB - https://docs.microsoft.com/en-us/azure/cosmos-db/mongodb-mongoose
//}]}
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/src/client/src/actions/azureActions/logOutAzure.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
import logout from "../../mockData/logout";
import { Dispatch } from "react";
export interface ILogout {
type: AZURE_TYPEKEYS.LOG_OUT_OF_AZURE;
}
const logOutAzureAction = (): ILogout => ({
type: AZURE_TYPEKEYS.LOG_OUT_OF_AZURE
});
const startLogOutAzure = () => {
return async (dispatch: Dispatch<ILogout>) => {
// Can dispatch a spinner here until login completes
try {
const loginData = await logout();
if (loginData.body === "success") {
dispatch(logOutAzureAction());
} else {
console.log("Error signing out of Azure");
}
} catch (err) {
console.log(err);
}
};
};
export { startLogOutAzure };
<file_sep>/templates/Web/Projects/AddPackageJsonDefault/README.md
## Getting Started
In the root directory of the project...
1. Install node modules `yarn install` or `npm install`.
2. Start development server `yarn start` or `npm start`.
## Next Steps
### Deployment
The generated templates can be deployed to Azure App Service using the following steps:
1. In the root directory of the project `yarn build` or `npm build` to create a build folder.
2. Move the build folder inside the server folder.
3. Deploy the server folder to Azure App Service using the [Azure App Service Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice).
4. If a database is used, add the environment variables defined in .env to your Application Settings.
5. Consider adding authentication and securing back-end API's by following [Azure App Service Security](https://docs.microsoft.com/en-us/azure/app-service/overview-security).
Full documentation for deployment to Azure App Service can be found here: [Deployment Docs](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/deployment.md).
## File Structure
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
└── README.md
```
## Additional Documentation
- Bootstrap CSS - https://getbootstrap.com/
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/src/client/src/mockData/azureServiceOptions.ts
import { IOption } from "../types/option";
import { defineMessages } from "react-intl";
import getSvgUrl from "../utils/getSvgUrl";
import { WIZARD_CONTENT_INTERNAL_NAMES } from "../utils/constants";
export const messages = defineMessages({
azureTitle: {
id: "azureLogin.azureTitle",
defaultMessage: "Microsoft Azure"
},
azureCardBody: {
id: "azureLogin.azureCardBody",
defaultMessage:
"Microsoft Azure is an ever-expanding set of cloud services to help your organization meet your business challenges. Sign in or create an account to get access to CosmosDB and Azure Functions from this extension"
},
azureLongDescription: {
id: "azureLogin.longDescription",
defaultMessage:
"Azure is a cloud computing service created by Microsoft for building, testing, deploying, and managing applications and services through Microsoft-managed data centers spread throughout the world. It offers more than a hundred services including scalable databases, container deployments, infrastructure management, serverless compute etc. These services combined with Microsoft's developer tools like Visual Studio and Visual Studio Code offer you great end-to-end tools to make you success. More information about Microsoft Azure can be found at [azure.microsoft.com](azure.microsoft.com)."
},
azureLoginTitle: {
id: "azureLogin.azureLoginTitle",
defaultMessage: "Attach services to your web application (Optional)"
},
azureFunctionsTitle: {
id: "azureFunctions.Title",
defaultMessage: "Azure Functions"
},
azureFunctionsLongDescription: {
id: "azureFunctions.longDescription",
defaultMessage:
"Azure Functions is a serverless compute service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. Think of it as deploying functions that executes on pre-defined triggers instead of having to write and manage a full-fledged server yourself. One of the most commonly used triggers is an HTTPTrigger which is a function that runs whenever it receives an HTTP request. This is essentially the same as an API endpoint. Web Template Studio allows you to deploy a function app with multiple 'hello world' HTTPTrigger functions (maximum of 10) so you can get to writing your business logic as soon as possible."
},
azureFunctionsCardBody: {
id: "azureFunctions.cardBody",
defaultMessage:
"Azure Functions is a serverless compute service that enables you to run code on-demand without having to explicitly provision or manage infrastructure."
},
cosmosTitle: {
id: "cosmosDb.title",
defaultMessage: "Cosmos DB"
},
cosmosLongDescription: {
id: "cosmosDb.longDescription",
defaultMessage:
"Azure Cosmos DB is Microsoft’s proprietary globally-distributed, multi-model database service for managing data on a global scale. It offers a variety of APIs for your database including Azure Table, Core (SQL), MongoDB and Gremlin (GraphQL). Web Template Studio offers you the functionality to deploy a Cosmos DB instance from the wizard itself and select an initial location to deploy your database with the ability to scale it to multiple locations at a future time. As an added feature, deploying with the MongoDB API enables you to quickly connect the project Web Template Studio generates to your database instance."
},
cosmosCardBody: {
id: "cosmosDb.cardBody",
defaultMessage:
"Cosmos DB allows you to build and scale your application with a globally distributed, multi-model database service."
}
});
const azureServiceOptions: IOption[] = [
{
author: "Microsoft",
svgUrl: getSvgUrl(WIZARD_CONTENT_INTERNAL_NAMES.AZURE_FUNCTIONS),
title: messages.azureFunctionsTitle,
internalName: WIZARD_CONTENT_INTERNAL_NAMES.AZURE_FUNCTIONS,
longDescription: messages.azureFunctionsLongDescription,
body: messages.azureFunctionsCardBody
},
{
author: "Microsoft",
svgUrl: getSvgUrl(WIZARD_CONTENT_INTERNAL_NAMES.COSMOS_DB),
title: messages.cosmosTitle,
internalName: WIZARD_CONTENT_INTERNAL_NAMES.COSMOS_DB,
longDescription: messages.cosmosLongDescription,
body: messages.cosmosCardBody
}
];
export const microsoftAzureDetails: IOption = {
author: "Microsoft",
svgUrl: getSvgUrl(WIZARD_CONTENT_INTERNAL_NAMES.AZURE),
title: messages.azureTitle,
internalName: WIZARD_CONTENT_INTERNAL_NAMES.AZURE,
longDescription: messages.azureLongDescription,
body: messages.azureCardBody
};
export default azureServiceOptions;
<file_sep>/src/client/src/actions/azureActions/azureFunctionActions.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
import { IFunctionName } from "../../containers/AzureFunctionsSelection";
export interface IFunctionApp {
appIndex: number;
functionNames: IFunctionName[];
}
export interface IUpdateFunctionNamesAction {
type: AZURE_TYPEKEYS.UPDATE_AZURE_FUNCTION_NAMES;
payload: IFunctionApp;
}
export interface ISaveAzureFunctionsSettings {
type: AZURE_TYPEKEYS.SAVE_AZURE_FUNCTIONS_SETTINGS;
payload: any;
}
export interface IRemoveAzureFunction {
type: AZURE_TYPEKEYS.REMOVE_AZURE_FUNCTION;
payload: number;
}
export interface IRemoveAzureFunctionApp {
type: AZURE_TYPEKEYS.REMOVE_AZURE_FUNCTIONS_APP;
payload: number;
}
const updateAzureFunctionNamesAction = (functionApp: {
appIndex: number;
functionNames: IFunctionName[];
}): IUpdateFunctionNamesAction => ({
type: AZURE_TYPEKEYS.UPDATE_AZURE_FUNCTION_NAMES,
payload: functionApp
});
const saveAzureFunctionsSettingsAction = (
azureFunctionsSettings: any
): ISaveAzureFunctionsSettings => ({
type: AZURE_TYPEKEYS.SAVE_AZURE_FUNCTIONS_SETTINGS,
payload: azureFunctionsSettings
});
const removeAzureFunctionAction = (
functionIndex: number
): IRemoveAzureFunction => ({
type: AZURE_TYPEKEYS.REMOVE_AZURE_FUNCTION,
payload: functionIndex
});
const removeAzureFunctionAppAction = (
appIndex: number
): IRemoveAzureFunctionApp => ({
type: AZURE_TYPEKEYS.REMOVE_AZURE_FUNCTIONS_APP,
payload: appIndex
});
export {
updateAzureFunctionNamesAction,
removeAzureFunctionAction,
removeAzureFunctionAppAction,
saveAzureFunctionsSettingsAction
};
<file_sep>/src/client/src/selectors/licenseSelector.ts
import { createSelector } from "reselect";
import { ILicenseObject, License } from "../types/license";
const getSelection = (state: any) => state.selection;
const getFrameworkLicenses = (selection: any): string[] => {
const licenses: any[] = [];
licenses.push(selection.frontendFramework.licenses);
licenses.push(selection.backendFramework.licenses);
return licenses;
};
const getPageLicenses = (selection: any): ILicenseObject[] => {
const licenses: ILicenseObject[] = [];
const licenseSet = new Set();
for (const page of selection.pages) {
for (const license of page.licenses) {
if (!licenseSet.has(license.text)) {
licenses.push(license);
licenseSet.add(license.text);
}
}
}
return licenses;
};
const getFrameworkLicensesSelector = createSelector(
getSelection,
getFrameworkLicenses
);
const getPageLicencesSelector = createSelector(
getSelection,
getPageLicenses
);
export { getFrameworkLicensesSelector, getPageLicencesSelector };
<file_sep>/src/extension/README.md
# Kendo UI Template Wizard for Visual Studio Code
## Instruction To Use
- Open **VSCode**
- Press `ctrl+shift+p` in Windows/Linux or `⇧⌘P` in Mac to open VSCode's extension launcher
- Type/Select `Kendo UI Template Wizard: Launch` and press `Enter` to launch the extension
## Features
Kendo UI VS Code Template Wizard approaches web app creation using the following three attribute sets:
- **Frameworks**: We currently support two frameworks for frontend: _[React.js](https://reactjs.org/)_ with [KendoReact](https://www.telerik.com/kendo-react-ui/), _[Angular](https://angular.io/)_ with [Kendo UI for Angular](https://www.telerik.com/kendo-angular-ui) and [Vue.js](https://vuejs.org/) with [Kendo UI for Vue](https://www.telerik.com/kendo-vue-ui/).
Once you make the selections you want and click generate, you can quickly extend the generated code.
## Request a Feature / Submit Feedback
You can request a feature or submit feedback using the Kendo UI [support system](https://www.telerik.com/account/support-tickets)
## License
This code is distributed under the terms and conditions of the Progress Software Corporation End User License Agreement for [Visual Studio Code Extensions](https://github.com/telerik/kendo-vscode-extensions/tree/master/kendo-ui-template-wizard/src/extension/LICENSE.md).
<file_sep>/src/client/src/actions/wizardInfoActions/setVisitedWizardPage.ts
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
export interface ISetVisitedPage {
type: WIZARD_INFO_TYPEKEYS.SET_VISITED_WIZARD_PAGE;
payload: string;
}
export interface ISetPageAction {
type: WIZARD_INFO_TYPEKEYS.SET_PAGE_WIZARD_PAGE;
payload: string;
}
export interface IResetVisitedPageAction {
type: WIZARD_INFO_TYPEKEYS.RESET_VISITED_WIZARD_PAGE;
}
export const setVisitedWizardPageAction = (route: string): ISetVisitedPage => ({
type: WIZARD_INFO_TYPEKEYS.SET_VISITED_WIZARD_PAGE,
payload: route
});
export const setPageWizardPageAction = (route: string): ISetPageAction => ({
type: WIZARD_INFO_TYPEKEYS.SET_PAGE_WIZARD_PAGE,
payload: route
});
export interface IResetWizardAction {
type: WIZARD_INFO_TYPEKEYS.RESET_WIZARD;
}<file_sep>/src/client/src/reducers/generationStatus/genStatus.ts
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import RootAction from "../../actions/ActionType";
export interface IStatus {
success: boolean;
failure: boolean;
}
export interface IServiceStatus {
[key: string]: IStatus;
}
const initialState = {
templates: {
success: false,
failure: false
},
cosmos: {
success: false,
failure: false
},
azureFunctions: {
success: false,
failure: false
}
};
const genStatus = (
state: IServiceStatus = initialState,
action: RootAction
) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.UPDATE_TEMPLATE_GENERATION_STATUS:
return {
...action.payload
};
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return initialState;
default:
return state;
}
};
export { genStatus };
<file_sep>/src/client/src/selectors/wizardSelectionSelector.ts
import _ from "lodash";
import { createSelector } from "reselect";
import { RowType } from "../types/rowType";
import { ISelected } from "../types/selected";
import getSvgUrl from "../utils/getSvgUrl";
import { IPageCount } from "../reducers/wizardSelectionReducers/pageCountReducer";
import { defineMessages } from "react-intl";
import { IValidation } from "../reducers/wizardSelectionReducers/updateOutputPath";
import { AppState } from "../reducers";
import { SelectionState } from "../reducers/wizardSelectionReducers";
export const messages = defineMessages({
azureFunctionsOriginalTitle: {
id: "azureFunctions.originalTitle",
defaultMessage: "Azure Functions"
},
cosmosOriginalTitle: {
id: "cosmosDb.originalTitle",
defaultMessage: "CosmosDB"
}
});
const getWizardSelectionsSelector = (state: AppState): SelectionState =>
state.selection;
const getProjectName = (state: AppState): string =>
state.selection.projectNameObject.projectName;
const getProjectNameValidation = (state: AppState): IValidation =>
state.selection.projectNameObject.validation;
const getOutputPath = (state: AppState): string =>
state.selection.outputPathObject.outputPath;
const getOutputPathValidation = (state: AppState): IValidation =>
state.selection.outputPathObject.validation;
const getPageCount = (state: AppState): IPageCount => state.selection.pageCount;
const getTheme = (state: AppState): string => state.selection.theme.name;
const isValidNameAndProjectPath = (
projectNameValidationObject: IValidation,
outputPathValidationObject: IValidation,
outputPath: string,
projectName: string
): boolean => {
if (!projectNameValidationObject || !outputPathValidationObject) {
return false;
}
if (outputPath === "" || projectName === "") {
return false;
}
if (
!projectNameValidationObject.isValid ||
!outputPathValidationObject.isValid
) {
return false;
}
return true;
};
const isValidNameAndProjectPathSelector = createSelector(
getProjectNameValidation,
getOutputPathValidation,
getOutputPath,
getProjectName,
isValidNameAndProjectPath
);
const getProjectTypeRowItems = (selection: SelectionState): RowType[] => {
const projectType = selection.appType as ISelected;
return [
{
title: projectType.title,
internalName: projectType.internalName,
version: selection.appType.version!,
author: projectType.author
}
];
};
/* BOOM */
const frameworksRowItems = (selection: SelectionState): RowType[] => {
const { frontendFramework, backendFramework } = selection;
return [
{
title: frontendFramework.title,
internalName: frontendFramework.internalName,
version: frontendFramework.version!,
author: frontendFramework.author
},
{
title: backendFramework.title,
internalName: backendFramework.internalName,
version: backendFramework.version!,
author: backendFramework.author
}
];
};
/**
* Iterates through every service, and for every services, identifies each
* resource that was created and adds it to a list that will be displayed on the
* summary page. Currently supports Azure Functions and CosmosDB only. Information
* provided is in line with props required by SummaryTile component.
*
* @param selection selection object created by the developer
*/
const getServices = (selection: SelectionState): RowType[] => {
const { services } = selection;
const { azureFunctions, cosmosDB } = services;
const servicesRows: RowType[] = [];
if (!_.isEmpty(azureFunctions.selection)) {
servicesRows.push({
title: azureFunctions.selection[0].appName.value,
originalTitle: "Azure Functions",
company: "Microsoft",
svgUrl: getSvgUrl(azureFunctions.selection[0].internalName.value),
functionNames: azureFunctions.selection[0].functionNames,
internalName: azureFunctions.selection[0].internalName.value,
version: "1.0"
});
}
if (!_.isEmpty(cosmosDB.selection)) {
servicesRows.push({
title: cosmosDB.selection[0].accountName,
originalTitle: "CosmosDB",
company: "Microsoft",
svgUrl: getSvgUrl(cosmosDB.selection[0].internalName),
internalName: cosmosDB.selection[0].internalName,
version: "1.0"
});
}
return servicesRows;
};
const getProjectTypeRowItemSelector = createSelector(
getWizardSelectionsSelector,
getProjectTypeRowItems
);
const getFrameworksRowItemSelector = createSelector(
getWizardSelectionsSelector,
frameworksRowItems
);
const getServicesSelector = createSelector(
getWizardSelectionsSelector,
getServices
);
export {
getProjectTypeRowItemSelector,
getWizardSelectionsSelector,
getFrameworksRowItemSelector,
getServicesSelector,
getOutputPath,
getOutputPathValidation,
getProjectName,
getPageCount,
getTheme,
getProjectNameValidation,
isValidNameAndProjectPathSelector
};
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.Mongo/server/mongo/mongo_service.py
from flask import jsonify, make_response, request
from .mongo_client import *
from bson import json_util, ObjectId
import json
from .settings import *
from .utils import serialize
def get():
items = list_items.find()
serialized_list_items = [serialize(item) for item in items]
return jsonify(serialized_list_items)
def create():
data = request.get_json()
list_item = {'text': data['text']}
created_item = list_items.insert_one(list_item)
return make_response(
jsonify(
{'_id': str(created_item.inserted_id), 'text': list_item['text']}
), 201
)
def destroy(id):
query_str = {'_id': ObjectId(id)}
count = 0
result = list_items.find(query_str)
for item in iter(result):
count += 1
if count == 0:
return make_response(
jsonify(
{'error': 'Could not find an item with given id'}
),
404
)
list_items.delete_one(query_str)
return jsonify(
{'_id': id, 'text': 'This comment was deleted'}
)
<file_sep>/src/client/src/actions/wizardInfoActions/updateDependencyInfo.ts
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
// payload received from extension should look like this
export interface IDependencyInfo {
dependency: "python" | "node";
installed: boolean;
}
export interface IUpdateDependencyInfo {
type: WIZARD_INFO_TYPEKEYS.UPDATE_DEPENDENCY_INFO;
payload: IDependencyInfo;
}
export const updateDependencyInfoAction = (
dependencyInfo: IDependencyInfo
): IUpdateDependencyInfo => ({
type: WIZARD_INFO_TYPEKEYS.UPDATE_DEPENDENCY_INFO,
payload: dependencyInfo
});
<file_sep>/templates/Web/Pages/Angular.List/src/app/app-shell/Param_SourceName_Kebab/list.component.ts
import { Component, OnInit } from '@angular/core';
import { ListService, IListItem } from './list.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
listItems: IListItem[] = [];
WarningMessageText = 'Request to get list items failed:';
WarningMessageOpen = false;
constructor(private listService: ListService) { }
ngOnInit() {
this.listService.getListItems().subscribe(
response => {
this.listItems = response;
},
error => {
this.WarningMessageOpen = true;
this.WarningMessageText = `Request to get list items failed: ${error}`;
}
);
}
handleAddListItem(inputText: string) {
this.listService.addListItem(inputText).subscribe(
(response) => {
this.listItems.splice(0, 0, response);
},
error => {
this.WarningMessageOpen = true;
this.WarningMessageText = `Request to add list item failed: ${error}`;
}
);
}
handleDeleteListItem(id: number) {
this.listService.deleteListItem(id).subscribe(
response => {
this.listItems = this.listItems.filter(item => item._id !== response._id);
},
error => {
this.WarningMessageOpen = true;
this.WarningMessageText = `Request to delete list item failed: ${error}`;
}
);
}
handleWarningClose(open: boolean) {
this.WarningMessageOpen = open;
this.WarningMessageText = '';
}
}
<file_sep>/docs/getting-started-developers.md
# Getting started with the Codebase
## Prerequisites
[Git](https://git-scm.com/downloads), [Yarn](https://yarnpkg.com/en/docs/install), [Node.js](https://nodejs.org/en/download/), [Gulp](https://gulpjs.com/) and [VSCode](https://code.visualstudio.com/) must be installed prior to running the installation or build scripts.
Run the command
```
npm config set scripts-prepend-node-path true
```
to tell VSCode which Node version to run during the extension compilation (otherwise you'll get an error during the build process).
_Note: If using Windows, use Git Bash_.
## Quick Start
To get started, the first step is to clone this repository. To install dependencies, compile the client, and compile the
extension, run:
```
./build
```
Open `src/extension` using `VSCode` and press `F5` to run the extension. Use `Ctrl+Shift+P` to open VSCode's extension
launcher. Select `Kendo UI Template Wizard: Launch` and press `Enter` to launch the extension
## Developing the Client
The client lives in the `src/client` directory. To run the client for development, navigate to `src/client` and use the command
```
yarn start
```
to begin development. The client was bootstrapped using [Create-React-App with TypeScript](https://facebook.github.io/create-react-app/docs/adding-typescript).
## Creating VSIX Package
_**Note: You cannot sideload the VSIX and build/run the extension through Extension Development Host (using `F5` on VSCode) at the same time or there will be naming conflicts. The VSIX should be uninstalled first.**_
The installation script `createVsix` will build the extension package (_.vsix_) for you.
```
./createVsix
```
The script will package the extension into the root directory `/dist` folder. The vsix package can be distributed and
installed by anyone who has VSCode using the command in the extension directory:
```
code --install-extension [extensionName].vsix
```
`kendovscode.vsix` is the default extensionName.
Alternatively, copy the extension into your extensions directory. For _Windows_, it is
`%USERPROFILE%\.vscode\extensions`. For _Mac/Linux_, it is `~/.vscode/extensions` (By Default).
After installation, use `ctrl+shift+p (Windows)` or `cmd+shift+p (Mac)` to open the Extension Launcher and select `Kendo UI Template Wizard: Launch` to run the extension.
## Running the client in the VSCode Extension
To see any changes made on the client within VSCode, run the instructions shown in the `Quick Start` section to rebuild the client and the extension. The resulting changes should appear in VSCode when the extension runs.
Rebuilding the client is required because the client is injected into a [VSCode Webview](https://code.visualstudio.com/api/extension-guides/webview) using the production build of the client.
### Under the Hood
The following notes are inspired by the [vscode-webview-react](https://github.com/rebornix/vscode-webview-react)
repository by [rebornix](https://github.com/rebornix):
- We inline `index.html` content in `src/extension/src/extension.ts` when creating the webview
- For all resources going to the webview, their scheme is `vscode-resource`
- We add a baseUrl `<base href="${vscode.Uri.file(path.join(this._extensionPath, 'build')).with({ scheme: 'vscode-resource' })}/">` and then all relative paths work.
<file_sep>/templates/Web/Projects/FlaskDefault/server/requirements.txt
flask==1.0.3<file_sep>/templates/Web/_composition/Flask/Page.Flask.List.AddRoutes.WithCosmos.Mongo/server/server_postaction.py
from flask import Flask, send_from_directory
from flask import jsonify
from flask import make_response
//{[{
from mongo.mongo_service import *
//}]}
from constants import CONSTANTS
import os
from os.path import exists, join
app = Flask(__name__, static_folder = 'build')
//{[{
# List Endpoints
@app.route(CONSTANTS['ENDPOINT']['LIST'])
def get_list():
return get()
@app.route(CONSTANTS['ENDPOINT']['LIST'], methods=['POST'])
def add_list_item():
return create()
@app.route(CONSTANTS['ENDPOINT']['LIST'] + '/<id>', methods=['DELETE'])
def delete_list_item(id):
return destroy(id)
//}]}
<file_sep>/src/client/src/actions/wizardContentActions/typeKeys.ts
export enum WIZARD_CONTENT_TYPEKEYS {
GET_VSCODE_API = "WTS/vscode/GET_VSCODE_API",
GET_PAGES_OPTIONS = "WTS/wizardContent/GET_PAGES_OPTIONS",
GET_PAGES_OPTIONS_SUCCESS = "WTS/wizardContent/GET_PAGES_OPTIONS_SUCCESS",
GET_PROJECT_TYPES = "WTS/wizardContent/GET_PROJECT_TYPES",
GET_PROJECT_TYPES_SUCCESS = "WTS/wizardContent/GET_PROJECT_TYPES_SUCCESS",
GET_WEB_APP_OPTIONS = "WTS/wizardContent/GET_WEB_APP_OPTIONS",
GET_WEB_APP_OPTIONS_SUCCESS = "WTS/wizardContent/GET_WEB_APP_OPTIONS_SUCCESS",
GET_FRONTEND_FRAMEWORKS = "WTS/wizardContent/GET_FRONTEND_FRAMEWORKS",
GET_FRONTEND_FRAMEWORKS_SUCCESS = "WTS/wizardContent/GET_FRONTEND_FRAMEWORKS_SUCCESS",
GET_BACKEND_FRAMEWORKS = "WTS/wizardContent/GET_BACKEND_FRAMEWORKS",
SET_PREVIEW_STATUS = "WTS/wizardContent/SET_PREVIEW_STATUS",
SET_PORT = "WTS/wizardContent/SET_PORT",
GET_BACKEND_FRAMEWORKS_SUCCESS = "WTS/wizardContent/GET_BACKEND_FRAMEWORKS_SUCCESS",
LOAD_WIZARD_CONTENT = "WTS/wizardContent/LOAD_WIZARD_CONTENT"
}
<file_sep>/src/client/src/reducers/wizardRoutes/index.ts
import { combineReducers } from "redux";
import { isVisited, selected } from "./navigationReducer";
export default combineReducers({
isVisited, selected
});
<file_sep>/templates/Web/_composition/Flask/Page.Flask.MasterDetail.AddRoutes/server/server_postaction.py
from flask import Flask, send_from_directory
from flask import jsonify
from flask import make_response
from constants import CONSTANTS
import os
from os.path import exists, join
//{[{
from sample_data import *
//}]}
app = Flask(__name__, static_folder = 'build')
//{[{
# MasterDetail Page Endpoint
@app.route(CONSTANTS['ENDPOINT']['MASTER_DETAIL'])
def get_master_detail():
return jsonify(
sample_data['text_assets']
)
//}]}
<file_sep>/templates/Web/Pages/Angular.Grid/src/app/app-shell/Param_SourceName_Kebab/grid.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class GridService {
private listUrl = environment.endpoint.grid;
constructor(private http: HttpClient) { }
getGridItems(): Observable<IGridTextItem[]> {
return this.http.get<IGridTextItem[]>(this.listUrl);
}
}
export interface IGridTextItem {
description: string;
header: string;
id: number;
}
<file_sep>/src/extension/src/utils/dependencyChecker.ts
import { WizardServant, IPayloadResponse } from "../wizardServant";
import { ExtensionCommand, CONSTANTS } from "../constants";
const os = require("os");
const util = require("util");
const exec = util.promisify(require("child_process").exec);
const PYTHON3_REGEX = RegExp("^Python 3\\.[5-9]\\.[0-9]"); // minimum Python version required is 3.5.x
const NODE_REGEX = RegExp("v10\\.(1[5-9]|[2-9][0-9])\\.[0-9]"); // minimum Node version required is 10.15.x
export class DependencyChecker extends WizardServant {
clientCommandMap: Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
>;
constructor() {
super();
this.clientCommandMap = this.defineCommandMap();
}
private defineCommandMap(): Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
> {
return new Map([[ExtensionCommand.CheckDependency, this.checkDependency]]);
}
private async runPythonVersionCommand(command: string) {
let installed: boolean;
try {
const { stdout } = await exec(command + " --version");
installed = PYTHON3_REGEX.test(stdout);
} catch (err) {
installed = false;
}
return installed;
}
async checkDependency(message: any): Promise<IPayloadResponse> {
let name: string = message.payload.dependency;
let state: boolean = false;
if (name === CONSTANTS.DEPENDENCY_CHECKER.NODE) {
try {
const { stdout } = await exec(
CONSTANTS.DEPENDENCY_CHECKER.NODE + " --version"
);
state = NODE_REGEX.test(stdout);
} catch (err) {
state = false;
}
} else if (name === CONSTANTS.DEPENDENCY_CHECKER.PYTHON) {
let userOS: string = os.platform();
let userOnWin: boolean = userOS.indexOf("win") === 0;
if (
await this.runPythonVersionCommand(CONSTANTS.DEPENDENCY_CHECKER.PYTHON3)
) {
state = true;
} else if (
await this.runPythonVersionCommand(CONSTANTS.DEPENDENCY_CHECKER.PYTHON)
) {
state = true;
} else if (
userOnWin &&
(await this.runPythonVersionCommand(
CONSTANTS.DEPENDENCY_CHECKER.PYTHON_LAUNCHER
))
) {
state = true;
} else {
state = false;
}
}
return {
payload: {
dependency: name,
installed: state
}
};
}
}
<file_sep>/src/client/src/actions/azureActions/logIntoAzure.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
import login from "../../mockData/login";
import { Dispatch } from "react";
export interface IsLoggedIntoAzure {
type: AZURE_TYPEKEYS.IS_LOGGED_IN_TO_AZURE;
}
export interface ILoginToAzure {
type: AZURE_TYPEKEYS.LOG_IN_TO_AZURE;
payload: any;
}
const isLoggedIntoAzureAction = (): IsLoggedIntoAzure => ({
type: AZURE_TYPEKEYS.IS_LOGGED_IN_TO_AZURE
});
const logIntoAzureAction = (loginData: any): ILoginToAzure => ({
type: AZURE_TYPEKEYS.LOG_IN_TO_AZURE,
payload: loginData
});
const startLoginToAzure = () => {
return async (dispatch: Dispatch<ILoginToAzure>) => {
// Can dispatch a spinner here until login completes
try {
const loginData = await login();
dispatch(logIntoAzureAction(loginData));
} catch (err) {
console.log(err);
}
};
};
export { isLoggedIntoAzureAction, logIntoAzureAction, startLoginToAzure };
<file_sep>/README.md
> NOTE: This repo is archived, all the code past the "monorepo-snapshot" tag, and further development has moved to:
> [https://github.com/telerik/vscode-extensions](https://github.com/telerik/vscode-extensions)
# Starter projects locations
Starter projects are sourced from https://github.com/telerik/kendo-vsx-templates
# Build
Build is availble at the VSX Jenkins
`http://10.10.7.82:8080/view/Kendo/job/VisualStudioCode_Extension_Kendo/` (VPN required)
Output is available at this location:
`smb://telerik.com/distributions/DailyBuilds/Guidance/VSCodeExtensions/master`
# Wiki & Handling Updates
Wiki and release instructions are available here:
https://github.com/telerik/kendo-vscode-extensions/wiki/Handling-updates
# Contributing and branching strategy
The main branch is develop and it is where all features go first. We use master for releases.
Always work on new things in a separate, new, branches and when ready initiate a pull request against develop. Add @vvatkov and @agpetrov as reviewers.
When ready rebase you work from develop to master (git checkout master, git rebase develop) and follow the steps in HandlingUpdates, update package.json following the semver rules.
<file_sep>/templates/Web/Projects/ReactDefault/README_postaction.md
## Getting Started
In the root directory of the project...
1. Install node modules `yarn install` or `npm install`.
2. Start development server `yarn start` or `npm start`.
## Next Steps
//{[{
### Adding a New Page
1. Create a folder in `/src/components` with your react components.
2. Add a route for your page to `/src/App.js`.
3. Add a button to the navigation bar in `/src/components/NavBar/index.js`.
//}]}
### Deployment
The generated templates can be deployed to Azure App Service using the following steps:
1. In the root directory of the project `yarn build` or `npm build` to create a build folder.
2. Move the build folder inside the server folder.
3. Deploy the server folder to Azure App Service using the [Azure App Service Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice).
4. If a database is used, add the environment variables defined in .env to your Application Settings.
5. Consider adding authentication and securing back-end API's by following [Azure App Service Security](https://docs.microsoft.com/en-us/azure/app-service/overview-security).
Full documentation for deployment to Azure App Service can be found here: [Deployment Docs](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/deployment.md).
## File Structure
//{[{
The front-end is based on [create-react-app](https://github.com/facebook/create-react-app).
//}]}
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
//^^
/{[{
├── src - React front-end
│ ├── components - React components for each page
│ ├── App.jsx - React routing
│ └── index.jsx - React root component
//}]}
└── README.md
```
## Additional Documentation
//{[{
- React - https://reactjs.org/
- React Router - https://reacttraining.com/react-router/
//}]}
- Bootstrap CSS - https://getbootstrap.com/
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/templates/Web/_composition/Flask/Page.Flask.List.AddRoutes/server/server_postaction.py
from flask import Flask, send_from_directory
from flask import jsonify
from flask import make_response
//{[{
from flask import request
//}]}
from constants import CONSTANTS
import os
from os.path import exists, join
//{[{
from sample_data import *
//}]}
app = Flask(__name__, static_folder = 'build')
//{[{
# List Endpoints
@app.route(CONSTANTS['ENDPOINT']['LIST'])
def get_list():
return jsonify(
sample_data['list_text_assets']['list_items']
)
@app.route(CONSTANTS['ENDPOINT']['LIST'], methods = ['POST'])
def add_list_item():
data = request.get_json()
list_item = {'_id': sample_data['list_text_assets']['list_id'], 'text': data['text']}
sample_data['list_text_assets']['list_items'].insert(0, list_item)
sample_data['list_text_assets']['list_id'] += 1
return make_response(
jsonify(
list_item
), 201
)
@app.route(CONSTANTS['ENDPOINT']['LIST'] + '/<int:id>', methods=['DELETE'])
def delete_list_item(id):
list_items_to_remove = [list_item for list_item in sample_data['list_text_assets']['list_items'] if list_item['_id'] == id]
if (len(list_items_to_remove) == 0):
return make_response(jsonify({'error': 'Could not find an item with the given id'}), 404)
if (len(list_items_to_remove) > 1):
return make_response(jsonify({'error': 'There is a problem with the server'}), 500)
sample_data['list_text_assets']['list_items'] = [list_item for list_item in sample_data['list_text_assets']['list_items'] if list_item['_id'] != id]
return jsonify(
{'_id': id, 'text': 'This comment was deleted'}
)
//}]}
<file_sep>/templates/Web/Pages/Angular.MasterDetail/src/app/app-shell/Param_SourceName_Kebab/master-detail-sidebar-tab/master-detail-sidebar-tab.component.ts
import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
@Component({
selector: 'app-master-detail-sidebar-tab',
templateUrl: './master-detail-sidebar-tab.component.html',
styleUrls: ['./master-detail-sidebar-tab.component.css']
})
export class MasterDetailSidebarTabComponent implements OnInit {
@Input() tabText: string;
@Input() image: string;
@Input() index: number;
@Input() key: number;
@Output() displayTabClick = new EventEmitter<number>();
constructor() { }
ngOnInit() {
}
onDisplayTabClick() {
this.displayTabClick.emit(this.index);
}
}
<file_sep>/src/client/src/containers/RightSidebar/strings.ts
import { defineMessages } from "react-intl";
const messages = defineMessages({
yourProjectDetails: {
id: "rightSidebar.yourProjectDetails",
defaultMessage: "Your Project Details"
},
projectType: {
id: "rightSidebar.projectType",
defaultMessage: "Project Type"
},
frontendFramework: {
id: "rightSidebar.frontendFramework",
defaultMessage: "Front-end Framework"
},
backendFramework: {
id: "rightSidebar.backendFramework",
defaultMessage: "Back-end Framework"
},
services: {
id: "rightSidebar.services",
defaultMessage: "Services"
}
});
export default messages;
<file_sep>/src/client/src/actions/wizardContentActions/getFrontendFrameworks.ts
import { Dispatch } from "react";
import { getFrameworks } from "./getFrameworks";
import { WIZARD_CONTENT_TYPEKEYS } from "./typeKeys";
import WizardContentActionType from "./wizardContentActionType";
import { IOption } from "../../types/option";
export interface IFrontendFrameworksActionType {
type: WIZARD_CONTENT_TYPEKEYS.GET_FRONTEND_FRAMEWORKS_SUCCESS;
payload: IOption[];
}
export const getFrontendFrameworksSuccess = (
frameworks: IOption[]
): IFrontendFrameworksActionType => ({
type: WIZARD_CONTENT_TYPEKEYS.GET_FRONTEND_FRAMEWORKS_SUCCESS,
payload: frameworks
});
// thunk
export const getFrontendFrameworksAction = (
projectType: string,
isPreview: boolean,
serverPort: number
) => {
return async (dispatch: Dispatch<WizardContentActionType>) => {
return dispatch(
getFrontendFrameworksSuccess(
await getFrameworks(projectType, "frontend", isPreview, serverPort)
)
);
};
};
<file_sep>/docs/application-architecture.md
Web Template Studio is a [Visual Studio Code Extension](https://code.visualstudio.com/api) built in [Typescript](https://www.typescriptlang.org/)/[React.js](https://reactjs.org/). It leverages the templating engine ([Core Template Studio](https://github.com/Microsoft/CoreTemplateStudio)) used by [Windows Template Studio](https://github.com/Microsoft/WindowsTemplateStudio). For more info on the terminology, please refer to the [terminology document](./terminology.md).
[Core Template Studio](https://github.com/Microsoft/CoreTemplateStudio) serves both Web and Windows Template Studios in merging the templates selected by the user. For more information on Core Template Studio, refer to its [documentation](https://github.com/Microsoft/CoreTemplateStudio/blob/dev/docs/getting-started-developers.md).
[Web Template Studio](https://github.com/Microsoft/WebTemplateStudio) has two major components. The extension's backend (referred to as the [extension](https://github.com/Microsoft/WebTemplateStudio/tree/dev/src/extension)), which is written in [Typescript](https://www.typescriptlang.org/) and the front-end wizard (referred to as the [client](https://github.com/Microsoft/WebTemplateStudio/tree/dev/src/client)), written in [React.tsx](https://www.typescriptlang.org/docs/handbook/jsx.html).
Here is a diagram that illustrates the high level functionality of each of the components:

Before the extension is ready to run, the build script compiles the wizard's React code into JavaScript that gets injected into html, which then gets served using [VSCode's Webview API](https://code.visualstudio.com/api/extension-guides/webview). Visit [this page](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/install.md) to know more about how to run the extension. As the extension is launching, it starts up the Engine (which will by default run on PORT 9502) and updates the cache with the updated templates (if any were added). The Engine will keep listening to the extension's requests such as generation, etc.
The two components will be discussed separately later. There are a few important concepts that will help you get started on development quickly:
## **Communication**
The wizard runs in an isolated environment, and mimics how applications run on a browser. For example, the wizard does not have access to the local storage of the user, or any of the OS's resources/actions. For this reason, most of the logic is done in the extension. The wizard communicates with the extension using the WebView API, with a command defined for each function (look at the extension's constants file and the wizard's constants file to see the currently defined commands).
For example, if we want to send the email of a user from the extension to the wizard, you can use the VSCode object to do so:
```js
vscode.postMessage({
command: "sendEmailCommand",
payload: {
email: "<EMAIL>"
}
});
```
This sends the email using the WebView API and
```js
panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case "sendEmailCommand":
// message.payload.email = <EMAIL>
return;
// other commands
}
},
undefined,
undefined
);
```
receives the email.
We receive all the commands from the extension in [App.tsx](https://github.com/Microsoft/WebTemplateStudio/blob/dev/src/client/src/App.tsx) and receive all the commands from the wizard in the [controller.ts](https://github.com/Microsoft/WebTemplateStudio/blob/dev/src/extension/src/controller.ts). You will find the documentation very helpful if you need more info on the Webview API.
## **Separating the UI from the Logic**:
One of our main concerns is increasing the speed of the wizard and making it as light as possible. Therefore, the wizard does not perform any expensive computations, and does not make any API requests. Most of these actions are done in the extension. So as the user navigates through the wizard, the selections are validated in the wizard and stored. When the user clicks generate, these selections will then be sent to the extension, which will deal with them synchronously. The extension starts with the templates (if any were selected), which will get sent to the Engine (Core Template Studio). After their successful generation, the extension uses Azure SDK to deploy the resources if the user selects any.
We will briefly discuss the architecture of the extension and the wizard:
## **Client**:
As previously mentioned, the client is written in React.js. It keeps track of the state using Redux. If you are not familiar with Redux, we suggest familiarizing yourself with it before you start development on the wizard.
## **Extension**:
TODO: Explain the architecture of the extension and the key concepts to contribute.
The extension back-end is responsible for running all services pertaining to the core experience. This includes launching the VS Code WebView React Panel, hosting the core template generation engine and enabling functionality with the Azure Cloud Computing Platform.
To communicate with the user-facing React Wizard, VS Code extension API exposes the `PostMessage()` function to communicate with the extension and vice versa. The behavior of a received message from the wizard is defined in a function delegate that gets passed to the ReactPanel from the controller.
The controller acts as a router to and for behavior. The flow of command from client starts when the `postMessage()` gets called in the client and the reactpanel object in the extension receives it. With the argument payload `message: any` from the client, there is a property specified within message called `module`. This tells the controller which service module the message payload should be routed to.
For more details about how to make specific contributions to the project (adding templates, services, etc.) please refer to the [FAQ](./faq.md) section.
<file_sep>/src/client/src/actions/wizardInfoActions/resetWizardAction.ts
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
export interface IResetWizard {
type: WIZARD_INFO_TYPEKEYS.RESET_WIZARD;
}
const resetWizardAction = (): IResetWizard => ({
type: WIZARD_INFO_TYPEKEYS.RESET_WIZARD
});
export { resetWizardAction };
<file_sep>/src/client/src/actions/wizardInfoActions/wizardInfoActionType.ts
import { IVersionData } from "./getVersionData";
import { ISetDetails } from "./setDetailsPage";
import { ISetVisitedPage, ISetPageAction, IResetVisitedPageAction } from "./setVisitedWizardPage";
import {
IUpdateGenStatusMessage,
IUpdateGenStatus
} from "./updateGenStatusActions";
import { IResetWizard } from "./resetWizardAction";
import { IUpdateDependencyInfo } from "./updateDependencyInfo";
type WizardInfoType =
| IVersionData
| ISetDetails
| ISetVisitedPage
| IUpdateGenStatus
| ISetPageAction
| IResetWizard
| IUpdateGenStatusMessage
| IResetVisitedPageAction
| IUpdateDependencyInfo;
export default WizardInfoType;
<file_sep>/src/client/src/containers/CosmosResourceModal/messages.ts
import { defineMessages } from "react-intl";
export const messages = defineMessages({
subscriptionLabel: {
id: "cosmosResourceModule.subscriptionLabel",
defaultMessage: "Subscription"
},
ariaSubscriptionLabel: {
id: "cosmosResourceModule.ariaSubscriptionLabel",
defaultMessage: "Subscription Drop Down"
},
resourceGroupLabel: {
id: "cosmosResourceModule.resourceGroupLabel",
defaultMessage: "Resource Group"
},
ariaResourceGroupLabel: {
id: "cosmosResourceModule.ariaResourceGroupLabel",
defaultMessage: "Resource Group Drop Down"
},
locationLabel: {
id: "cosmosResourceModule.locationLabel",
defaultMessage: "Location"
},
ariaLocationLabel: {
id: "cosmosResourceModule.ariaLocationLabel",
defaultMessage: "Location Drop Down"
},
apiLabel: {
id: "cosmosResourceModule.apiLabel",
defaultMessage: "API"
},
ariaApiLabel: {
id: "cosmosResourceModule.ariaApiLabel",
defaultMessage: "API Drop Down"
},
accountNameLabel: {
id: "cosmosResourceModule.accountNameLabel",
defaultMessage: "Account Name"
},
ariaAccountNameLabel: {
id: "cosmosResourceModule.ariaAccountNameLabel",
defaultMessage: "Account Name Input"
},
accountName: {
id: "cosmosResourceModule.accountName",
defaultMessage: "Account Name"
},
createNew: {
id: "cosmosResourceModule.createNew",
defaultMessage: "Create New"
},
addResource: {
id: "cosmosResourceModule.addResource",
defaultMessage: "Add Resource"
},
saveChanges: {
id: "cosmosResourceModule.saveChanges",
defaultMessage: "Save Changes"
},
createCosmosRes: {
id: "cosmosResourceModule.createCosmosRes",
defaultMessage: "Create Cosmos DB Account"
},
internalName: {
id: "cosmosResourceModule.internalName",
defaultMessage: "Internal Name"
}
});
<file_sep>/src/client/src/selectors/wizardNavigationSelector.ts
import { ROUTES } from "../utils/constants";
import { createSelector } from "reselect";
import { AppState } from "../reducers";
import { IRoutes } from "../reducers/wizardRoutes/navigationReducer";
export interface IVisitedPages {
showFrameworks: boolean;
showPages: boolean;
}
const getIsVisitedRoutes = (state: AppState) => state.wizardRoutes.isVisited;
const transformIsVisited = (isVisitedRoutes: IRoutes): IVisitedPages => ({
showFrameworks: isVisitedRoutes[ROUTES.SELECT_FRAMEWORKS],
showPages: false
});
const getIsVisitedRoutesSelector = createSelector(
getIsVisitedRoutes,
transformIsVisited
);
export { getIsVisitedRoutesSelector };
<file_sep>/src/extension/src/services/progress.ts
import * as vscode from "vscode";
import ProgressType from "./progressType";
export default class Progress implements vscode.Progress<ProgressType> {
report(value: ProgressType): void {
}
}<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.SQL/server/sql/sql_client.py
import azure.cosmos.cosmos_client as cosmos_client
from constants import CONSTANTS
from .settings import *
class SQLObj():
def __init__(self):
self.client = cosmos_client.CosmosClient(
url_connection = connection_key,
auth = {'masterKey': master_key}
)
self.db = self.client.CreateDatabase(
{'id': CONSTANTS['COSMOS']['DATABASE']}
)
self.container = self.client.CreateContainer(
self.db['_self'],
{
'id': CONSTANTS['COSMOS']['CONTAINER']
},
{
'offerThroughput': 400
}
)
def get_client(self):
return self.client
def get_db(self):
return self.db
def get_container(self):
return self.container<file_sep>/src/client/src/actions/azureActions/subscriptionData.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
export interface IGetSubscription {
type: AZURE_TYPEKEYS.GET_SUBSCRIPTION_DATA;
payload: any;
}
export const getSubscriptionData = (subscriptionData: any): IGetSubscription => ({
type: AZURE_TYPEKEYS.GET_SUBSCRIPTION_DATA,
payload: subscriptionData
});
<file_sep>/src/client/src/mockData/cosmosDbModalData.ts
export const azureModalInitialState: any = {
subscription: [
{
value: "",
label: ""
}
],
resourceGroup: [
{
value: "",
label: ""
}
],
accountName: [
{
value: "",
label: ""
}
],
api: [
{
value: "",
label: ""
}
],
location: [
{
value: "",
label: ""
}
]
};
export const azureFunctionModalInitialState: any = {
subscription: [
{
value: "",
label: ""
}
],
resourceGroup: [
{
value: "",
label: ""
}
],
appName: [
{
value: "",
label: ""
}
],
location: [
{
value: "",
label: ""
}
],
runtimeStack: [
{
value: "",
label: ""
}
],
numFunctions: [
{
value: 0,
label: 0
}
]
};
<file_sep>/docs/faq.md
## The purpose of this document is to provide guidance on how to make large contributions that involve more than one component.
## **FAQs**:
1. **How can I add functionality for another Azure Cloud Service like SQL Server?**
Before you start working on a service, make sure it does not conflict with any of our contribution [guidelines](https://github.com/Microsoft/WebTemplateStudio/blob/dev/CONTRIBUTING.md). To implement the functionality of a new service in the extension, make sure you familiarize yourself with how Cosmos DB is deployed in the [AzureServices](https://github.com/Microsoft/WebTemplateStudio/blob/dev/src/extension/src/azure/azureServices.ts) class. Typically, every service will have a directory with its name (for example azure-sql) in the [azure](https://github.com/Microsoft/WebTemplateStudio/tree/dev/src/extension/src/azure) directory (assuming it is an Azure Service). The class should define functions that handle the service's deployment details. You should then define a function in AzureServices class that deals with the deployment (for example deploySQLServer). Since this function will be called on a command, it needs to implement the interface for command functions.
```
public static async deploySQLServer(message: any): Promise<IPayloadResponse>
```
where [message] is the message which contains the command that will call this function. Therefore, you can access the message attributes to access the received info (example: message.subscription).
This function can utilize methods you defined in the service's directory.
You should then define a command, on which your deploy function will get called. To add a command, go to constants.ts and add a command in ExtensionCommands. After adding a command in constants, add an entry in the AzureServices map where each entry's key is the command and each entry's value is the function. Assuming you receive the right info, your function will run everytime the extension receives the command you specified in the map.
2. **How can I add a card for another service in the wizard?**
If you are not familiar with React-Redux. We suggest familarizing yourself with it before contributing to the wizard.
To add a card for a service, you need to define that option in azureServiceOptions. We suggest you use the wizard a few times in the dev environment to understand the workflow of adding a service in the wizard.
At a high level is the objects in azureServiceOptions get mapped to the Card component. The mapping takes place in AzureSubscriptions container. We recommend you add a details page to every service since our target audience includes beginner developers.
<file_sep>/templates/Web/Pages/React.Grid/src/components/ReactGrid/GridComponent.jsx
import React from "react";
export default function GridComponent(props) {
const { image, header, description } = props;
return (
<div className="col-md-4 col-sm-12 p-5">
<img src={image} alt="Default Grey Box" className="mb-3" />
<h3>{header}</h3>
<p>{description}</p>
</div>
);
}
<file_sep>/src/extension/src/generationExperience.ts
import * as vscode from "vscode";
import { WizardServant, IPayloadResponse } from "./wizardServant";
import { ExtensionCommand, TelemetryEventName, CONSTANTS } from "./constants";
import { TelemetryAI } from "./telemetry/telemetryAI";
import { IActionContext } from "./telemetry/callWithTelemetryAndErrorHandling";
import { ReactPanel } from "./reactPanel";
import { AzureServices } from "./azure/azureServices";
import { CoreTemplateStudio } from "./coreTemplateStudio";
import { Controller } from "./controller";
export class GenerationExperience extends WizardServant {
private static reactPanelContext: ReactPanel;
private static Telemetry: TelemetryAI;
clientCommandMap: Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
> = new Map([
[ExtensionCommand.Generate, this.handleGeneratePayloadFromClient],
[
ExtensionCommand.OpenProjectVSCode,
GenerationExperience.openProjectVSCode
],
[ExtensionCommand.CloseWizard, this.handleCloseWizard]
]);
/**
*
*/
constructor(private Telemetry: TelemetryAI) {
super();
GenerationExperience.Telemetry = this.Telemetry;
}
public static setReactPanel(reactPanelContext: ReactPanel) {
GenerationExperience.reactPanelContext = reactPanelContext;
}
public async handleCloseWizard() {
Controller.reactPanelContext.dispose();
return { payload: true };
}
////TODO: MAKE GEN CALL CLIENTCOMMANDMAP FUNCTIONS VIA TO WRAP TELEMETRY AUTOMATICALLY
// tslint:disable-next-line: max-func-body-length
public async handleGeneratePayloadFromClient(
message: any
): Promise<IPayloadResponse> {
GenerationExperience.Telemetry.trackWizardTotalSessionTimeToGenerate();
var payload = message.payload;
var enginePayload: any = payload.engine;
const apiGenResult = await this.sendTemplateGenInfoToApiAndSendStatusToClient(
enginePayload
).catch(error => {
console.log(error);
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatus,
payload: {
templates: GenerationExperience.getProgressObject(false),
cosmos: GenerationExperience.getProgressObject(false),
azureFunctions: GenerationExperience.getProgressObject(false)
}
});
return;
});
let progressObject = {
templates: GenerationExperience.getProgressObject(
apiGenResult !== undefined
),
cosmos: {},
azureFunctions: {}
};
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatus,
payload: progressObject
});
var serviceQueue: Promise<any>[] = [];
if (apiGenResult) {
enginePayload.path = apiGenResult.generationOutputPath;
} else {
return { payload: undefined };
}
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.GetOutputPath,
payload: { outputPath: enginePayload.path }
});
if (payload.selectedFunctions) {
serviceQueue.push(
GenerationExperience.Telemetry.callWithTelemetryAndCatchHandleErrors(
TelemetryEventName.FunctionsDeploy,
// tslint:disable-next-line: no-function-expression
async function(this: IActionContext): Promise<void> {
try {
await AzureServices.deployFunctionApp(
payload.functions,
enginePayload.path
);
progressObject = {
...progressObject,
azureFunctions: GenerationExperience.getProgressObject(true)
};
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatus,
payload: progressObject
});
} catch (error) {
progressObject = {
...progressObject,
azureFunctions: GenerationExperience.getProgressObject(false)
};
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatus,
payload: progressObject
});
}
}
)
);
}
if (payload.selectedCosmos) {
serviceQueue.push(
GenerationExperience.Telemetry.callWithTelemetryAndCatchHandleErrors(
TelemetryEventName.CosmosDBDeploy,
// tslint:disable-next-line: no-function-expression
async function(this: IActionContext): Promise<void> {
var cosmosPayload: any = payload.cosmos;
try {
var dbObject = await AzureServices.deployCosmosResource(
cosmosPayload,
enginePayload.path
);
progressObject = {
...progressObject,
cosmos: GenerationExperience.getProgressObject(true)
};
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatus,
payload: progressObject
});
AzureServices.promptUserForCosmosReplacement(
enginePayload.path,
dbObject
).then(
//log in telemetry how long it took replacement
cosmosReplaceResponse => {
if (cosmosReplaceResponse.userReplacedEnv) {
// Temporary Disable
GenerationExperience.Telemetry.trackCustomEventTime(
TelemetryEventName.ConnectionStringReplace,
cosmosReplaceResponse.startTime,
Date.now()
);
}
}
);
} catch (error) {
progressObject = {
...progressObject,
cosmos: GenerationExperience.getProgressObject(false)
};
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatus,
payload: progressObject
});
}
}
)
);
}
// kick off both services asynchronously
Promise.all(serviceQueue);
return { payload: undefined };
}
public async sendTemplateGenInfoToApiAndSendStatusToClient(
enginePayload: any
) {
let apiInstance = CoreTemplateStudio.GetExistingInstance();
return await apiInstance.generate({
port: apiInstance.getPort(),
payload: enginePayload,
liveMessageHandler: this.handleGenLiveMessage
});
}
private handleGenLiveMessage(message: string) {
GenerationExperience.reactPanelContext.postMessageWebview({
command: ExtensionCommand.UpdateGenStatusMessage,
payload: {
status: message
}
});
}
private static async openProjectVSCode(
message: any
): Promise<IPayloadResponse> {
vscode.commands.executeCommand(
CONSTANTS.VSCODE_COMMAND.OPEN_FOLDER,
vscode.Uri.file(message.payload.outputPath),
true
);
return { payload: true };
}
private static getProgressObject(didSucceed: boolean) {
return {
success: didSucceed,
failure: !didSucceed
};
}
}
<file_sep>/src/client/src/selectors/postGenerationSelector.ts
import { createSelector } from "reselect";
import { FormattedMessage } from "react-intl";
import { IServiceStatus } from "../reducers/generationStatus/genStatus";
import { isCosmosResourceCreatedSelector } from "./cosmosServiceSelector";
import { isAzureFunctionsSelectedSelector } from "./azureFunctionsServiceSelector";
import { AppState } from "../reducers";
import { messages } from "../mockData/azureServiceOptions";
const getGenerationStatusSelector = (state: AppState) =>
state.generationStatus.genStatus;
const getSyncStatusSelector = (state: AppState): string =>
state.generationStatus.statusMessage;
const isTemplateGenerated = (progressObject: IServiceStatus): boolean =>
progressObject.templates.success;
const isTemplatesFailed = (progressObject: IServiceStatus): boolean =>
progressObject.templates.failure;
const isCosmosDeployedSuccess = (progressObject: IServiceStatus): boolean =>
progressObject.cosmos.success;
const isCosmosDeployedFailure = (progressObject: IServiceStatus): boolean =>
progressObject.cosmos.failure;
const isAzureFunctionsDeployedSuccess = (
progressObject: IServiceStatus
): boolean => progressObject.azureFunctions.success;
const isAzureFunctionsDeployedFailure = (
progressObject: IServiceStatus
): boolean => progressObject.azureFunctions.failure;
const isCosmosDeployedSuccessSelector = createSelector(
getGenerationStatusSelector,
isCosmosDeployedSuccess
);
const isCosmosDeployedFailureSelector = createSelector(
getGenerationStatusSelector,
isCosmosDeployedFailure
);
const isAzureFunctionsDeployedSuccessSelector = createSelector(
getGenerationStatusSelector,
isAzureFunctionsDeployedSuccess
);
const isAzureFunctionsDeployedFailureSelector = createSelector(
getGenerationStatusSelector,
isAzureFunctionsDeployedFailure
);
const isTemplateGeneratedSelector = createSelector(
getGenerationStatusSelector,
isTemplateGenerated
);
const isTemplatesFailedSelector = createSelector(
getGenerationStatusSelector,
isTemplatesFailed
);
export interface IDeployStatus {
title: FormattedMessage.MessageDescriptor;
isSelected: boolean;
isDeployed: boolean;
isFailed: boolean;
}
export interface IAzureServiceStatus {
[key: string]: IDeployStatus;
cosmosdb: IDeployStatus;
azureFunctions: IDeployStatus;
}
const servicesToDeploy = (
isCosmosSelected: boolean,
isCosmosSuccess: boolean,
isCosmosFailure: boolean,
isFunctionsSelected: boolean,
isAzureFunctionsSuccess: boolean,
isAzureFunctionsFailure: boolean
): IAzureServiceStatus => {
return {
cosmosdb: {
title: messages.cosmosTitle,
isSelected: isCosmosSelected,
isDeployed: isCosmosSuccess,
isFailed: isCosmosFailure
},
azureFunctions: {
title: messages.azureFunctionsTitle,
isSelected: isFunctionsSelected,
isDeployed: isAzureFunctionsSuccess,
isFailed: isAzureFunctionsFailure
}
};
};
const isServicesFailure = (
isCosmosFailure: boolean,
isFunctionsFailure: boolean
): boolean => isCosmosFailure && isFunctionsFailure;
const servicesToDeploySelector = createSelector(
isCosmosResourceCreatedSelector,
isCosmosDeployedSuccessSelector,
isCosmosDeployedFailureSelector,
isAzureFunctionsSelectedSelector,
isAzureFunctionsDeployedSuccessSelector,
isAzureFunctionsDeployedFailureSelector,
servicesToDeploy
);
const isServicesFailureSelector = createSelector(
isCosmosDeployedFailureSelector,
isAzureFunctionsDeployedFailureSelector,
isServicesFailure
);
const isServicesSelected = (
isCosmosCreated: boolean,
isFunctionsSelected: boolean
): boolean => isCosmosCreated || isFunctionsSelected;
const isServicesSelectedSelector = createSelector(
isCosmosResourceCreatedSelector,
isAzureFunctionsSelectedSelector,
isServicesSelected
);
const isServicesDeployedOrFinished = (services: IAzureServiceStatus): boolean => {
const { cosmosdb, azureFunctions } = services;
let isFinished = true;
if (cosmosdb.isSelected) {
isFinished = isFinished && (cosmosdb.isDeployed || cosmosdb.isFailed);
}
if (azureFunctions.isSelected) {
isFinished = isFinished && (azureFunctions.isDeployed || azureFunctions.isFailed);
}
return isFinished;
};
const isServicesDeployedOrFinishedSelector = createSelector(
servicesToDeploySelector,
isServicesDeployedOrFinished
);
export {
getSyncStatusSelector,
isTemplateGeneratedSelector,
isServicesDeployedOrFinishedSelector,
isServicesFailureSelector,
isTemplatesFailedSelector,
isServicesSelectedSelector,
servicesToDeploySelector
};
<file_sep>/templates/Web/Pages/Angular.Blank/src/app/app-shell/Param_SourceName_Kebab/Param_SourceName_Kebab.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlankComponent } from './blank.component';
import { Param_SourceName_PascalRoutingModule } from './Param_SourceName_Kebab-routing.module';
@NgModule({
declarations: [
BlankComponent,
],
imports: [
CommonModule,
Param_SourceName_PascalRoutingModule
]
})
export class Param_SourceName_PascalModule { }
<file_sep>/src/client/src/mockData/mockVsCodeApi.ts
import {
EXTENSION_COMMANDS,
DEVELOPMENT,
EXTENSION_MODULES
} from "../utils/constants";
const WEST_US: string = "WEST US";
const RESOURCE_GROUP_MOCK: string = "resourceGroupMock";
const DEV_NO_ERROR_MSG: string = "in development, no error message";
const DEV_NO_ERROR_TYPE: string = "in development, no error type";
/**
* Models the functionality of acquireVsCodeApi() from vscode for use
* in development environment.
*
* Mimics VSCode API by using native postMessage API to mimic postMessage from
* VSCode.
*/
const mockVsCodeApi = () => ({
postMessage: (message: any) => {
if (process.env.NODE_ENV === DEVELOPMENT) {
switch (message.command) {
case "alert":
console.log("Command: ", message.alert);
break;
case EXTENSION_COMMANDS.GET_DEPENDENCY_INFO:
window.postMessage(
{
command: EXTENSION_COMMANDS.GET_DEPENDENCY_INFO,
payload: {
dependency: "node",
installed: false
}
},
"*"
);
window.postMessage(
{
command: EXTENSION_COMMANDS.GET_DEPENDENCY_INFO,
payload: {
dependency: "python",
installed: true
}
},
"*"
);
break;
case EXTENSION_COMMANDS.NAME_FUNCTIONS:
window.postMessage(
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.NAME_FUNCTIONS,
payload: {
isAvailable: message.appName.length > 0
},
message: DEV_NO_ERROR_MSG,
errorType: DEV_NO_ERROR_TYPE
},
"*"
);
break;
case EXTENSION_COMMANDS.NAME_COSMOS:
window.postMessage(
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.NAME_COSMOS,
payload: {
isAvailable: message.appName.length > 0
},
message: DEV_NO_ERROR_MSG,
errorType: DEV_NO_ERROR_TYPE
},
"*"
);
break;
case EXTENSION_COMMANDS.SUBSCRIPTION_DATA_COSMOS:
// produces locations and resource groups in development
window.postMessage(
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.SUBSCRIPTION_DATA_COSMOS,
payload: {
locations: [{ label: WEST_US, value: WEST_US }],
resourceGroups: [
{ label: RESOURCE_GROUP_MOCK, value: RESOURCE_GROUP_MOCK },
{ label: "ResourceGroupMock2", value: "ResourceGroupMock2" }
]
}
},
"*"
);
break;
case EXTENSION_COMMANDS.SUBSCRIPTION_DATA_FUNCTIONS:
// produces locations and resource groups in development
window.postMessage(
{
module: EXTENSION_MODULES.AZURE,
command: EXTENSION_COMMANDS.SUBSCRIPTION_DATA_FUNCTIONS,
payload: {
locations: [{ label: WEST_US, value: WEST_US }],
resourceGroups: [
{ label: RESOURCE_GROUP_MOCK, value: RESOURCE_GROUP_MOCK }
]
}
},
"*"
);
break;
case EXTENSION_COMMANDS.GENERATE:
// @ts-ignore mocks a generation status message
window.postMessage(
{
command: EXTENSION_COMMANDS.GEN_STATUS_MESSAGE,
payload: {
status: "updated status message..."
}
},
"*"
);
// @ts-ignore mocks a generation status object
window.postMessage(
{
command: EXTENSION_COMMANDS.GEN_STATUS,
payload: {
templates: {
success: false,
failure: true
},
cosmos: {
success: true,
failure: false
},
azureFunctions: {
success: true,
failure: false
}
}
},
"*"
);
break;
case EXTENSION_COMMANDS.GET_OUTPUT_PATH:
// produces a mock login response from VSCode in development
window.postMessage(
{
command: EXTENSION_COMMANDS.GET_OUTPUT_PATH,
payload: {
outputPath: "/generic_output_path"
}
},
"*"
);
window.postMessage(
{
command: EXTENSION_COMMANDS.GET_PREVIEW_STATUS,
payload: {
preview: true
}
},
"*"
);
break;
case EXTENSION_COMMANDS.GET_VERSIONS:
// produces a mock login response from VSCode in development
window.postMessage(
{
command: EXTENSION_COMMANDS.GET_VERSIONS,
payload: {
wizardVersion: "1.x",
templatesVersion: "1.x"
}
},
"*"
);
break;
case EXTENSION_COMMANDS.GEN_STATUS:
break;
case EXTENSION_COMMANDS.AZURE_LOGIN:
// produces a mock login response from VSCode in development
window.postMessage(
{
command: "login",
payload: {
email: "<EMAIL>",
subscriptions: [
{ value: "GIV.Hackathon", label: "GIV.Hackathon" }
]
}
},
"*"
);
break;
case EXTENSION_COMMANDS.PROJECT_PATH_VALIDATION:
// produces a mock validation response from VSCode in development
window.postMessage(
{
command: EXTENSION_COMMANDS.PROJECT_PATH_VALIDATION,
payload: {
projectPathValidation: {
isValid: true,
error: ""
}
}
},
"*"
);
break;
case EXTENSION_COMMANDS.RESET_PAGES:
window.postMessage(
{
command: EXTENSION_COMMANDS.RESET_PAGES,
payload: {
internalName: message.payload.internalName,
resetPages: true
}
},
"*"
);
}
}
}
});
export default mockVsCodeApi;
<file_sep>/templates/Web/Pages/KendoVue.Grid/.template.config/description.md
This is a grid page which demonstrates the components capabilities.
<file_sep>/NOTICES.md
Progress Kendo UI Template Wizard for Visual Studio v1
Copyright © 2019-2020 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved.
Portions of the Product include certain open source and commercial third-party components listed below (ìThird-Party Componentsî). The authors of the Third-Party Components require Progress Software Corporation (ìPSCî) to include the following notices and additional licensing terms as a condition of PSCís use of such Third-Party Components. You acknowledge that the authors of the Third-Party Components have no obligation to provide support to you for the Third-Party Components or the Product. You hereby undertake to comply with all licenses related to the applicable Third-Party Components. Notwithstanding anything to the contrary, to the extent that any of the terms and conditions of the Product Agreement conflict, vary, or are in addition to the terms and conditions of the aforementioned third-party licenses for these technologies, such terms and conditions are offered by PSC alone and not by any other party.
1. Special Notices Regarding Open Source Third-Party Components incorporated in the Product:
(1) MIT-style Licenses:
(a) Progress Kendo UI Template Wizard for Visual Studio v1 incorporates Core Template Studio v1.0.0. Such technology is subject to the following terms and conditions:
Core Template Studio
Copyright (c) .NET Foundation and Contributors. All rights reserved.
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
(b) Progress Kendo UI Template Wizard for Visual Studio v1 incorporates Web Template Studio v0.0.19149-1-dev. Such technology is subject to the following terms and conditions:
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2. Special Notices Regarding Commercially Licensed Third-Party Components incorporated in the Product: None
NOTICE FROM PROGRESS SOFTWARE CORPORATION: Additional notices may be included in the release notes or other documentation that accompanies updates received in connection with support of the Product.
1/13/2020
<file_sep>/src/client/src/actions/modalActions/typeKeys.ts
export enum MODAL_TYPES {
COSMOS_DB_MODAL = "COSMOS_DB_MODAL",
AZURE_FUNCTIONS_MODAL = "AZURE_FUNCTIONS_MODAL",
POST_GEN_MODAL = "POST_GEN_MODAL"
}
export enum MODAL_TYPEKEYS {
OPEN_MODAL = "WTS/modals/OPEN_MODAL",
CLOSE_MODALS = "WTS/modals/CLOSE_MODALS"
}
export type ModalType =
| null
| MODAL_TYPES.COSMOS_DB_MODAL
| MODAL_TYPES.AZURE_FUNCTIONS_MODAL
| MODAL_TYPES.POST_GEN_MODAL;
<file_sep>/src/client/src/actions/azureActions/setAccountAvailability.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
export interface IAvailabilityFromExtension {
isAvailable: boolean;
message: string;
}
export interface ISetCosmosAccountNameAvailability {
type: AZURE_TYPEKEYS.SET_ACCOUNT_AVAILABILITY;
payload: IAvailabilityFromExtension;
}
export interface ISetAzureFunctionsAppNameAvailability {
type: AZURE_TYPEKEYS.SET_APP_NAME_AVAILABILITY;
payload: IAvailabilityFromExtension;
}
export const setAccountAvailability = (
isAccountAvailableObject: IAvailabilityFromExtension
): ISetCosmosAccountNameAvailability => ({
type: AZURE_TYPEKEYS.SET_ACCOUNT_AVAILABILITY,
payload: isAccountAvailableObject
});
export const setAppNameAvailabilityAction = (
isAppNameAvailableObject: IAvailabilityFromExtension
): ISetAzureFunctionsAppNameAvailability => ({
type: AZURE_TYPEKEYS.SET_APP_NAME_AVAILABILITY,
payload: isAppNameAvailableObject
});
<file_sep>/templates/Web/Pages/Angular.MasterDetail/src/app/app-shell/Param_SourceName_Kebab/master-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { MasterDetailService, IMasterDetailText } from './master-detail.service';
@Component({
selector: 'app-master-detail',
templateUrl: './master-detail.component.html',
styleUrls: ['./master-detail.component.css']
})
export class MasterDetailComponent implements OnInit {
GreyAvatar = require('../../../assets/GreyAvatar.svg') as string;
WarningMessageText = 'Request to get master detail text failed:';
WarningMessageOpen = false;
currentDisplayTabIndex = 0;
masterDetailText: IMasterDetailText[] = [];
constructor(private masterDetailService: MasterDetailService) { }
ngOnInit() {
this.masterDetailService.getMasterDetailItems().subscribe(
result => {
this.masterDetailText = result;
},
error => {
this.WarningMessageOpen = true;
this.WarningMessageText = `Request to get master detail text failed: ${error}`;
}
);
}
handleDisplayTabClick(id: number) {
this.currentDisplayTabIndex = id;
}
handleWarningClose(open: boolean) {
this.WarningMessageOpen = open;
this.WarningMessageText = '';
}
}
<file_sep>/templates/Web/Pages/Angular.List/src/app/app-shell/Param_SourceName_Kebab/list.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class ListService {
private listUrl = environment.endpoint.list;
constructor(private http: HttpClient) { }
getListItems(): Observable<IListItem[]> {
return this.http.get<IListItem[]>(this.listUrl);
}
addListItem(inputText: string): Observable<IListItem> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const body = JSON.stringify({
text: inputText
});
return this.http.post<IListItem>(this.listUrl, body, httpOptions);
}
deleteListItem(id: number): Observable<IListItem> {
return this.http.delete<IListItem>(`${environment.endpoint.list}/${id}`);
}
}
export interface IListItem {
_id: number;
text: string;
}
<file_sep>/src/client/src/actions/wizardSelectionActions/typeKeys.ts
export enum WIZARD_SELECTION_TYPEKEYS {
SELECT_FRONTEND_FRAMEWORK = "WTS/wizardSelections/SELECT_FRONTEND_FRAMEWORK",
SELECT_BACKEND_FRAMEWORK = "WTS/wizardSelections/SELECT_BACKEND_FRAMEWORK",
SELECT_PAGES = "WTS/wizardSelections/SELECT_PAGES",
SELECT_THEME = "WTS/wizardSelections/SELECT_THEME",
UPDATE_PAGE_COUNT = "WTS/wizardSelections/UPDATE_PAGE_COUNT",
SELECT_WEB_APP = "WTS/wizardSelections/SELECT_WEB_APP",
UPDATE_PROJECT_NAME = "WTS/wizardSelections/UPDATE_PROJECT_NAME",
UPDATE_OUTPUT_PATH = "WTS/wizardSelections/UPDATE_PROJECT_PATH",
SET_PROJECT_PATH_VALIDATION = "WTS/wizardSelections/SET_PROJECT_PATH_VALIDATION",
RESET_PAGES = "WTS/wizardSelections/RESET_PAGES"
}
<file_sep>/src/client/src/reducers/wizardContentReducers/index.ts
import { combineReducers } from "redux";
import backendOptions from "./backendFrameworkReducer";
import frontendOptions from "./frontendFrameworkReducer";
import pageOptions from "./pagesOptionsReducer";
import projectTypes from "./projectTypeReducer";
import detailsPage from "./detailsPageReducer";
import previewStatus from "./previewReducer";
import serverPort from "./portReducer";
const wizardContentReducer = combineReducers({
backendOptions,
frontendOptions,
pageOptions,
projectTypes,
detailsPage,
serverPort,
previewStatus
});
export default wizardContentReducer;
export type WizardContentType = ReturnType<typeof wizardContentReducer>;
<file_sep>/src/client/src/selectors/cosmosServiceSelector.ts
import _ from "lodash";
import { createSelector } from "reselect";
import { ISelectedCosmosService } from "../reducers/wizardSelectionReducers/services/cosmosDbReducer";
import { AppState } from "../reducers";
interface ISelectedDropdowns {
subscription?: IDropDownOptionType;
resourceGroup?: IDropDownOptionType;
appName?: IDropDownOptionType;
runtimeStack?: IDropDownOptionType;
location?: IDropDownOptionType;
numFunctions?: IDropDownOptionType;
}
interface ISelectionInformation {
dropdownSelection: ISelectedDropdowns;
previousFormData: ISelectedCosmosService;
}
const getServicesSelector = (state: AppState): object =>
state.selection.services;
const isCosmosDbSelected = (services: any): boolean => {
return !_.isEmpty(services.cosmosDB.selection);
};
const isCosmosResourceCreatedSelector = createSelector(
getServicesSelector,
isCosmosDbSelected
);
const getCosmosDbOptions = (services: any, isCosmosSelected: boolean): any => {
if (isCosmosSelected) {
return services.cosmosDB.selection[0];
}
};
const getCosmosDbSelectionSelector = createSelector(
getServicesSelector,
isCosmosResourceCreatedSelector,
getCosmosDbOptions
);
/**
* Returns the CosmosDB selection made by a developer.
* Returns undefined if a selection was not made.
* Currently, only one Cosmos Resource can be added, hence
* the hardcoded value of 0 index.
*
* @param services An object of all the services available in Project Acorn
*/
const getCosmosSelectionInDropdownForm = (services: any): any => {
const { selection } = services.selection.services.cosmosDB;
if (!_.isEmpty(selection)) {
const selectionInformation: ISelectionInformation = {
dropdownSelection: {},
previousFormData: selection[0]
};
for (const selectionKey in selection[0]) {
if (selectionKey) {
// @ts-ignore to allow dynamic key selection
selectionInformation.dropdownSelection[selectionKey] = {
value: selection[0][selectionKey],
label: selection[0][selectionKey]
};
}
}
return selectionInformation;
}
};
const getFunctionsSelection = createSelector(
getCosmosDbOptions,
getCosmosSelectionInDropdownForm
);
export {
getCosmosDbSelectionSelector,
getFunctionsSelection,
getCosmosSelectionInDropdownForm,
getServicesSelector,
isCosmosResourceCreatedSelector
};
<file_sep>/src/client/src/actions/wizardInfoActions/getVersionData.ts
import { IVersions } from "../../types/version";
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
export interface IVersionData {
type: WIZARD_INFO_TYPEKEYS.GET_VERSIONS;
payload: IVersions;
}
const getVersionsDataAction = (versions: IVersions): IVersionData => ({
type: WIZARD_INFO_TYPEKEYS.GET_VERSIONS,
payload: versions
});
export { getVersionsDataAction };
<file_sep>/templates/Web/_composition/NodeJS/Page.Node.List.AddRoutes.NoCosmos/README_postaction.md
## Next Steps
//{[{
### Sample Data
Replace the sample data stored in /server/sampleData.js.
Replace the default images stored in /src/images.
//}]}
### Deployment
.
├── server/ - Express server that provides API routes and serves front-end
│ ├── routes/ - Handles API calls for routes
│ ├── app.js - Adds middleware to the express server
//{[{
│ ├── sampleData.js - Contains all sample text data for generate pages
//}]}
│ └── server.js - Configures Port and HTTP Server
<file_sep>/src/client/src/reducers/wizardSelectionReducers/themeReducer.ts
import { WIZARD_SELECTION_TYPEKEYS } from "../../actions/wizardSelectionActions/typeKeys";
import WizardSelectionActionType from "../../actions/wizardSelectionActions/wizardSelectionActionType";
export interface ITheme {
[key: string]: string;
}
const initialState = { name: "default" };
const themeReducer = (
state: ITheme = initialState,
action: WizardSelectionActionType
) => {
switch (action.type) {
case WIZARD_SELECTION_TYPEKEYS.SELECT_THEME:
return {
...action.payload
};
default:
return state;
}
};
export default themeReducer;
<file_sep>/src/extension/src/signalr-api-module/commandPayload.ts
import { IGenerationPayloadType } from "../types/generationPayloadType";
import { ISyncPayloadType } from "../types/syncPayloadType";
type CommandPayload = IGenerationPayloadType | ISyncPayloadType;
export interface ICommandPayload {
payload: CommandPayload;
port: number;
liveMessageHandler: (message: string, progress?: number) => any;
}
<file_sep>/src/client/src/reducers/azureLoginReducers/subscriptionDataReducer.ts
import { AZURE_TYPEKEYS } from "../../actions/azureActions/typeKeys";
import AzureActionType from "../../actions/azureActions/azureActionType";
/* State Shape
{
SubscriptionData: {
locations: [],
resourceGroups: []
}
}
*/
interface ISubscriptionData {
locations: any[];
resourceGroups: any[];
}
const initialState = {
locations: [],
resourceGroups: []
};
const subscriptionData = (
state: ISubscriptionData = initialState,
action: AzureActionType
) => {
switch (action.type) {
case AZURE_TYPEKEYS.GET_SUBSCRIPTION_DATA:
return action.payload;
default:
return state;
}
};
export default subscriptionData;
<file_sep>/src/client/src/actions/wizardSelectionActions/selectFrontEndFramework.ts
import { ISelected } from "../../types/selected";
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
export interface ISelectFrontendAction {
type: WIZARD_SELECTION_TYPEKEYS.SELECT_FRONTEND_FRAMEWORK;
payload: ISelected;
}
const selectFrontendFramework = (
frontendFramework: ISelected
): ISelectFrontendAction => {
return ({
type: WIZARD_SELECTION_TYPEKEYS.SELECT_FRONTEND_FRAMEWORK,
payload: frontendFramework
});
}
export { selectFrontendFramework };
<file_sep>/templates/Web/_composition/KendoAngular/Page.Kendo.Angular.AddProducts/src/app/common/product-model.ts
export class Product {
public ProductID: number;
public ProductName = '';
public Discontinued = false;
public UnitsInStock: number;
public UnitPrice = 0;
}
<file_sep>/templates/Web/_composition/KendoReact/Page.Kendo.React.AddRoute/src/App_postaction.js
<Route exact path="/" component={Home} />
//^^
//{[{
<Route path = "/Param_SourceName_Pascal" component={Param_SourceName_Pascal} />
//}]}
</div>
<file_sep>/src/client/src/actions/wizardInfoActions/typeKeys.ts
export enum WIZARD_INFO_TYPEKEYS {
GET_VERSIONS = "WTS/GET_VERSIONS",
SET_VISITED_WIZARD_PAGE = "WTS/wizardNavigation/SET_VISITED_WIZARD_PAGE",
SET_DETAILS_PAGE_INFO = "WTS/details/SET_DETAILS_PAGE_INFO",
UPDATE_TEMPLATE_GENERATION_STATUS_MESSAGE = "WTS/postgen/UPDATE_TEMPLATE_GENERATION_STATUS_MESSAGE",
SET_PAGE_WIZARD_PAGE = "WTS/wizardNavigation/SET_PAGE_WIZARD_PAGE",
RESET_VISITED_WIZARD_PAGE = "WTS/wizardNavigation/RESET_VISITED_WIZARD_PAGE",
UPDATE_TEMPLATE_GENERATION_STATUS = "WTS/postgen/UPDATE_TEMPLATE_GENERATION_STATUS",
RESET_WIZARD = "RESET_WIZARD",
UPDATE_DEPENDENCY_INFO = "WTS/dependency/UPDATE_DEPENDENCY_INFO"
}
<file_sep>/templates/Web/_composition/KendoAngular/Page.Kendo.Angular.AddHeaderNav/src/app/components/header/header.component_postaction.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
public projectName = 'Kendo UI for Angular';
public items: any[] = [
{ text: 'Home' },
//{[{
{ text: 'Param_SourceName_Kebab' },
//}]}
];
}
<file_sep>/src/extension/src/signalr-api-module/generateCommand.ts
import { CoreTemplateStudioApiCommand } from "./coreTemplateStudioApiCommand";
import { CONSTANTS } from "../constants";
import { IGenerationPayloadType } from "../types/generationPayloadType";
import { IEngineGenerationPayloadType } from "../types/engineGenerationPayloadType";
export class GenerateCommand extends CoreTemplateStudioApiCommand {
async performCommandAction(connection: signalR.HubConnection): Promise<any> {
let body = this.makeEngineGenerationPayload(<IGenerationPayloadType>(
this.commandPayload.payload
));
connection.on(
CONSTANTS.API.GEN_LIVE_MESSAGE_TRIGGER_NAME,
this.commandPayload.liveMessageHandler
);
const result = await connection
.invoke(CONSTANTS.API.SIGNALR_API_GENERATE_METHOD_NAME, body)
.catch((error: Error) => Promise.reject(error));
connection.stop();
return Promise.resolve(result!.value);
}
private makeEngineGenerationPayload(
payload: IGenerationPayloadType
): IEngineGenerationPayloadType {
let {
projectName,
path,
projectType,
frontendFramework,
backendFramework,
pages,
theme,
services
} = payload;
return {
projectName: projectName,
genPath: path,
projectType: projectType,
frontendFramework: frontendFramework,
backendFramework: backendFramework,
language: "Any",
platform: "Web",
homeName: "Test",
theme: theme,
isTrial: false,
pages: pages.map((page: any) => ({
name: page.name,
templateid: page.identity
})),
features: services.map((service: any) => ({
name: service.name,
templateid: service.identity
}))
};
}
}
<file_sep>/src/client/src/reducers/wizardSelectionReducers/validatingNameReducer.ts
import { AZURE_TYPEKEYS } from "../../actions/azureActions/typeKeys";
import AzureActionType from "../../actions/azureActions/azureActionType";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
const setValidationStatus = (
state = false,
action: AzureActionType | WizardInfoType
) => {
switch (action.type) {
case AZURE_TYPEKEYS.SET_VALIDATION_STATUS:
return action.payload;
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return false;
default:
return state;
}
};
export default setValidationStatus;
<file_sep>/templates/Web/_composition/Flask/Page.Flask.AddSampleData.List/server/sample_data.py
sample_data = {}
# This class holds sample data used by some generated pages to show how they can be used.
# TODO Web Template Studio: Delete this file once your app is using real data.
<file_sep>/docs/deployment.md
# Deployment
After implementing your business logic, we recommend deploying your website to the cloud.
Deploying your website to the cloud allows people to view your website by visiting a URL.
## Azure App Service
One way to deploy is using Azure App Service. This service will allow you to deploy and scale web, mobile and API apps.
## VS Code Extension Method (Recommended)
The Azure App Service Extension provides an easy way to manage and deploy your web application.
1. Download the [Azure App Service Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice).
2. Open the project in Visual Studio Code, and run `yarn build` or `npm build`.
3. Move the build folder into the server folder.
4. Click the deploy button in the Azure App Service Extension.

5. When prompted on which folder to deploy, select the server folder.
6. Click yes when prompted to update your configuration to run `npm install` on the target server.

7. If you are using a Cosmos Database add the Cosmos Keys in the .env file to the Application Settings of your Azure App Service. To run the app in production mode set the variable NODE_ENV to production in your Application Settings. You can add an Application Setting by right clicking the Application Settings tab in the Azure App Service Extension.

8. Consider adding authentication and securing back-end APIs by following [Azure App Service Security](https://docs.microsoft.com/en-us/azure/app-service/overview-security).
## Local Git Deployment Method
This method will require you to have [git](https://git-scm.com/downloads) installed on your computer.
#### Creating the App Service through the Azure Portal
- Go to the [Azure Portal](https://portal.azure.com) and click on the _App Services_ button.

- Click on the _Add_ button in the new window that appears.

- Click the _web app_ button.

- You will be presented with another screen on which you should click _create_.

- Another screen will appear in which you are required to do the following actions:
1. Enter the name of the website in the _app name_ field.
2. Select a subscription.
3. Create a resource group or use an existing one.
4. Select the publish _code_ option.
5. If no _app service_ exists create an _app service_ on this screen (costs money but required if one doesn't already exist).
1. Click on the _App service_ button and you will be to create a new app service.
2. If creating an _app service_ name it and select a location, and finally select the tier you want.

6. Click create resource.

- After clicking create you will get a notification. Click the bell icon on the top right to view notifications, then click the _go to resource_ button.

You now have an app service resource in the cloud, where you can upload your web application.
#### Deploying the website to the App Service
To be able to deploy your web application, you will need to do the following set of commands in either _terminal_ or _git bash_. **Note: you must be in the root of your generated project's directory**.

`npm install && npm build` or `yarn install && yarn build`
You should then have a build folder in the root directory. Run the following command to move the production build of your client side into the server folder. Doing so will remove any prior builds.
`rm -rf server/build && mv build/ server/`
You will then want to `git init` to make the root directory a local git repository.
Finally, run the following command to create a .deployment file with the proper parameters.
```
echo "[config]
project=server" > .deployment
```
Follow the documentation created by the Azure team for [deploying with a local git repository](https://docs.microsoft.com/en-us/azure/app-service/deploy-local-git#open-azure-cloud-shell)
Your newly deployed web app can be found at `<app name>.azurewebsites.net`
<file_sep>/templates/Web/_composition/Flask/Page.Flask.Cosmos.SQL.AddMerging/server/constants_postaction.py
import os
CONSTANTS = {
'PORT': os.environ.get('PORT', 3001),
//{[{
'COSMOS': {
'DATABASE': 'List',
'CONTAINER': 'ListItems',
},
//}]}<file_sep>/src/client/src/types/metadata.d.ts
export interface IMetadata {
name: string;
displayName: string;
summary: string;
longDescription: string;
position: number;
svgUrl: string | undefined;
licenses: string[];
selected: boolean;
author: string;
tags: any;
}
<file_sep>/src/client/src/mockData/login.ts
interface IProfileInfo {
name: string;
email: string;
subscriptions: Array<any>;
}
const loginToAzure = (): Promise<IProfileInfo> => {
return Promise.resolve({
name: "<NAME>",
email: "<EMAIL>",
subscriptions: [{ value: "subscription1", label: "subscription1" }]
});
};
export default loginToAzure;
<file_sep>/templates/Web/_composition/Flask/Page.Flask.Grid.AddRoutes/server/server_postaction.py
from flask import Flask, send_from_directory
from flask import jsonify
from flask import make_response
from constants import CONSTANTS
import os
from os.path import exists, join
//{[{
from sample_data import *
//}]}
app = Flask(__name__, static_folder = 'build')
//{[{
# Grid Page Endpoint
@app.route(CONSTANTS['ENDPOINT']['GRID'])
def get_grid():
return jsonify(
sample_data['text_assets']
)
//}]}
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.Mongo/server/requirements_postaction.txt
//{[{
pymongo==3.8.0
python-dotenv==0.10.3
//}]}
flask==1.0.3<file_sep>/docs/telemetryData.md
# Telemetry for Web Template Studio - DATE
As new features and pages roll out, percentages will adjust.
<file_sep>/templates/Web/Projects/NodeDefault/README_postaction.md
## File Structure
//{[{
The back-end is based on [Express Generator](https://expressjs.com/en/starter/generator.html).
//}]}
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
//{[{
├── server/ - Express server that provides API routes and serves front-end
│ ├── routes/ - Handles API calls for routes
│ ├── app.js - Adds middleware to the express server
│ ├── constants.js - Defines the constants for the endpoints and port
│ └── server.js - Configures Port and HTTP Server
//}]}
└── README.md
```
## Additional Documentation
- Bootstrap CSS - https://getbootstrap.com/
//{[{
- Express - https://expressjs.com/
//}]}
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/src/client/src/reducers/wizardContentReducers/portReducer.ts
import { WIZARD_CONTENT_TYPEKEYS } from "../../actions/wizardContentActions/typeKeys";
import WizardContentActionType from "../../actions/wizardContentActions/wizardContentActionType";
import { API } from "../../services/constants";
/* State Shape
{
serverPort: number
}
*/
const serverPort = (
state: number = API.START_PORT,
action: WizardContentActionType
) => {
switch (action.type) {
case WIZARD_CONTENT_TYPEKEYS.SET_PORT:
return action.payload;
default:
return state;
}
};
export default serverPort;
<file_sep>/templates/Web/Features/Azure.Cosmos.Mongo/.template.config/description.md
This is a long list which can be used for blog comments and feeds.
<file_sep>/src/extension/src/telemetry/telemetryAI.ts
import * as vscode from 'vscode';
import {TelemetryReporterMock} from './telemetryReporterMock';
import { getPackageInfo } from './getPackageInfo';
import { IActionContext, ITelemetryReporter, callWithTelemetryAndCatchErrors } from './callWithTelemetryAndErrorHandling';
import { TelemetryEventName, ExtensionCommand } from '../constants';
import { WizardServant, IPayloadResponse } from '../wizardServant';
export class TelemetryAI extends WizardServant{
clientCommandMap: Map<ExtensionCommand, (message: any) => Promise<IPayloadResponse>> = new Map([
[ExtensionCommand.TrackPageSwitch, this.trackWizardPageTimeToNext],
]);
private static telemetryReporter: ITelemetryReporter;
private wizardSessionStartTime: number;
private pageStartTime: number;
constructor(private vscodeContext: vscode.ExtensionContext, private extensionStartTime: number){
super();
TelemetryAI.telemetryReporter = this.createTelemetryReporter(vscodeContext);
this.wizardSessionStartTime = Date.now();
this.pageStartTime = this.wizardSessionStartTime;
}
private createTelemetryReporter(ctx: vscode.ExtensionContext) {
const { extensionName, extensionVersion, aiKey } = getPackageInfo(ctx);
const reporter: TelemetryReporterMock = new TelemetryReporterMock(extensionName, extensionVersion, aiKey);
// adding to the array of disposables
ctx.subscriptions.push(reporter);
return reporter;
}
public trackExtensionStartUpTime(eventName : string = TelemetryEventName.ExtensionLaunch){
this.trackTimeDuration(eventName, this.extensionStartTime, Date.now());
}
/*
* @param pageToTrack is the name of the page the wizard is on before the user clicks the next button; this page name will be sent to Application Insights as property
*
*/
public async trackWizardPageTimeToNext(payload: any){
this.trackTimeDuration(TelemetryEventName.PageChange, this.pageStartTime, Date.now(), {"Page-Name": payload.pageName});
this.pageStartTime = Date.now();
return {payload: true};
}
public trackWizardTotalSessionTimeToGenerate(eventName : string = TelemetryEventName.WizardSession){
this.trackTimeDuration(eventName, this.wizardSessionStartTime, Date.now());
}
public trackCustomEventTime(customEventName: string, startTime: number, endTime: number = Date.now(), customEventProperties?: { [key: string]: string | undefined }){
this.trackTimeDuration(customEventName, startTime, endTime, customEventProperties);
}
private trackTimeDuration(eventName : string, startTime : number, endTime : number, properties?: { [key: string]: string | undefined }){
var measurement = {
duration: (endTime - startTime) / 1000
};
TelemetryAI.telemetryReporter.sendTelemetryEvent(eventName, properties, measurement)
}
public callWithTelemetryAndCatchHandleErrors<T>(callbackId: string, callback: (this: IActionContext) => T | PromiseLike<T>): Promise<T | undefined>{
return callWithTelemetryAndCatchErrors(this.vscodeContext, callbackId,callback, TelemetryAI.telemetryReporter);
}
public getExtensionName(ctx: vscode.ExtensionContext) {
const { extensionName } = getPackageInfo(ctx);
return extensionName;
}
public getExtensionVersionNumber(ctx: vscode.ExtensionContext){
const { extensionVersion } = getPackageInfo(ctx);
return extensionVersion;
}
}
<file_sep>/src/client/src/actions/wizardSelectionActions/wizardSelectionActionType.ts
import { ISelectBackendAction } from "./selectBackEndFramework";
import { ISelectFrontendAction } from "./selectFrontEndFramework";
import {
ISelectPagesAction,
IUpdatePageCountAction,
IResetPagesAction
} from "./selectPages";
import { ISelectProjectTypeAction } from "./selectWebApp";
import { IProjectPathValidationAction } from "./setProjectPathValidation";
import {
IUpdateProjectNameActionType,
IUpdateProjectPathActionType
} from "./updateProjectNameAndPath";
import { ISelectThemeAction } from "./selectTheme";
type WizardSelectionActionType =
| ISelectBackendAction
| ISelectFrontendAction
| ISelectPagesAction
| ISelectThemeAction
| ISelectProjectTypeAction
| IProjectPathValidationAction
| IUpdatePageCountAction
| IUpdateProjectNameActionType
| IUpdateProjectPathActionType
| IResetPagesAction;
export default WizardSelectionActionType;
<file_sep>/templates/Web/_composition/Flask/Page.Flask.AddSampleData.ForAllExceptList/README_postaction.md
## Next Steps
//{[{
### Sample Data
Replace the sample data stored in /server/sampleData.py.
Replace the default images stored in /src/images.
//}]}
## File Structure
The back-end is based on [Flask](https://github.com/pallets/flask).
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
├── server/ - Flask server that provides API routes and serves front-end
│ ├── constants.py - Defines the constants for the endpoints and port
//{[{
│ ├── sampleData.py - Contains all sample text data for generate pages
//}]}
│ └── server.py - Configures Port and HTTP Server and provides API routes
└── README.md
```
<file_sep>/src/extension/src/azure/azure-functions/utils/validationHelper.ts
import { FunctionSelections } from "../functionProvider";
import { CONSTANTS } from "../../../constants";
export interface FunctionValidationResult {
isValid: boolean;
message: string;
}
export namespace ValidationHelper {
const MAX_NAME_LEN = 60;
const MIN_NAME_LEN = 3;
export function validate(
selections: FunctionSelections
): FunctionValidationResult {
let appNameResult: FunctionValidationResult = validateFunctionAppName(
selections.functionAppName
);
if (!appNameResult.isValid) {
return appNameResult;
}
let functionNameResult: FunctionValidationResult = validateFunctionNames(
selections.functionNames
);
if (!functionNameResult.isValid) {
return functionNameResult;
}
return { isValid: true, message: "" };
}
export function validateFunctionNames(
names: string[]
): FunctionValidationResult {
for (var name of names) {
if (name.length > MAX_NAME_LEN || name.length < MIN_NAME_LEN) {
return {
isValid: false,
message: CONSTANTS.ERRORS.NAME_MIN_MAX(MIN_NAME_LEN, MAX_NAME_LEN)
};
}
let regexResult: FunctionValidationResult = checkFunctionNameRegex(name);
if (!regexResult.isValid) {
return regexResult;
}
}
names = names.map(name => {
return name.toLowerCase();
});
if (new Set(names).size !== names.length) {
return {
isValid: false,
message: CONSTANTS.ERRORS.FUNCTIONS_NO_DUPLICATES
};
}
return { isValid: true, message: "" };
}
export function validateFunctionAppName(
name: string
): FunctionValidationResult {
if (name.length > MAX_NAME_LEN || name.length < MIN_NAME_LEN) {
return {
isValid: false,
message: CONSTANTS.ERRORS.NAME_MIN_MAX(MIN_NAME_LEN, MAX_NAME_LEN)
};
}
return checkFunctionNameRegex(name);
}
function checkFunctionNameRegex(name: string): FunctionValidationResult {
let regexp = /^[a-zA-Z0-9]+[a-zA-Z0-9-]*[a-zA-Z0-9]+$/;
if (!regexp.test(name)) {
return {
isValid: false,
message: CONSTANTS.ERRORS.FUNCTIONS_INVALID_NAME(name)
};
}
return { isValid: true, message: "" };
}
}
<file_sep>/src/client/src/selectors/generationSelector.ts
import _ from "lodash";
import { createSelector } from "reselect";
import { ISelected } from "../types/selected";
import { ITemplateInfo } from "../types/templateInfo";
import { getOutputPath, getProjectName } from "./wizardSelectionSelector";
import {
SERVICE_KEYS,
WIZARD_CONTENT_INTERNAL_NAMES,
COSMOS_APIS
} from "../utils/constants";
import { AppState } from "../reducers";
import { SelectionState } from "../reducers/wizardSelectionReducers";
const DATABASE_INTERNAL_NAME_MAPPING = {
[COSMOS_APIS.MONGO]: WIZARD_CONTENT_INTERNAL_NAMES.COSMOS_DB_MONGO,
[COSMOS_APIS.SQL]: WIZARD_CONTENT_INTERNAL_NAMES.COSMOS_DB_SQL
};
const getWizardSelectionsSelector = (state: AppState): SelectionState =>
state.selection;
const getProjectType = (selection: SelectionState): string => {
const projectType = selection.appType as ISelected;
return projectType.internalName;
};
const getTheme = (selection: SelectionState): string => selection.theme.name;
const getFrontendFramework = (selection: SelectionState): string => {
const { frontendFramework } = selection;
return frontendFramework.internalName;
};
const getBackendFramework = (selection: SelectionState): string => {
const { backendFramework } = selection;
return backendFramework.internalName;
};
const getServices = (selection: SelectionState): ITemplateInfo[] => {
const { services } = selection;
const servicesInfo: ITemplateInfo[] = [];
if (
_.has(services, SERVICE_KEYS.COSMOS_DB) &&
services.cosmosDB.selection.length > 0
) {
servicesInfo.push({
name: "Cosmos",
identity:
DATABASE_INTERNAL_NAME_MAPPING[services.cosmosDB.selection[0].api]
});
}
if (
_.has(services, SERVICE_KEYS.AZURE_FUNCTIONS) &&
services.azureFunctions.selection.length > 0
) {
const { functionNames } = services.azureFunctions.selection[0];
if (functionNames) {
for (const funcName of functionNames) {
servicesInfo.push({
name: funcName.title,
identity: services.azureFunctions.selection[0].internalName.value
});
}
}
}
return servicesInfo;
};
const getPages = (selection: SelectionState): ITemplateInfo[] => {
const { pages } = selection;
const pagesInfo: ITemplateInfo[] = [];
for (const page of pages) {
pagesInfo.push({
name: page.title,
identity: page.internalName
});
}
return pagesInfo;
};
const getProjectTypeSelector = createSelector(
getWizardSelectionsSelector,
getProjectType
);
const getFrontendFrameworkSelector = createSelector(
getWizardSelectionsSelector,
getFrontendFramework
);
const getBackendFrameworkSelector = createSelector(
getWizardSelectionsSelector,
getBackendFramework
);
const getPagesSelector = createSelector(
getWizardSelectionsSelector,
getPages
);
const getServicesSelector = createSelector(
getWizardSelectionsSelector,
getServices
);
const getThemeSelector = createSelector(
getWizardSelectionsSelector,
getTheme
);
const rootSelector = createSelector(
getProjectName,
getOutputPath,
getProjectTypeSelector,
getFrontendFrameworkSelector,
getBackendFrameworkSelector,
getPagesSelector,
getThemeSelector,
getServicesSelector,
(
projectName,
path,
projectType,
frontendFramework,
backendFramework,
pages,
theme,
services
) => {
return {
projectName,
path,
projectType,
frontendFramework,
backendFramework,
pages,
theme,
services
};
}
);
export { rootSelector };
<file_sep>/src/client/src/reducers/wizardContentReducers/previewReducer.ts
import { WIZARD_CONTENT_TYPEKEYS } from "../../actions/wizardContentActions/typeKeys";
import WizardContentActionType from "../../actions/wizardContentActions/wizardContentActionType";
/* State Shape
{
previewStatus: boolean
}
*/
const previewStatus = (
state: boolean = false,
action: WizardContentActionType
) => {
switch (action.type) {
case WIZARD_CONTENT_TYPEKEYS.SET_PREVIEW_STATUS:
return action.payload;
default:
return state;
}
};
export default previewStatus;
<file_sep>/templates/Web/_composition/KendoReact/Page.Kendo.React.AddCommandCell/src/components/myCommandCell.jsx
import React from 'react';
export function MyCommandCell({ edit, remove, add, update, discard, cancel, editField }) {
return class extends React.Component {
render() {
const { dataItem } = this.props;
const inEdit = dataItem[editField];
const isNewItem = dataItem.ProductID === undefined;
return inEdit ? (
<td className="k-command-cell">
<button
className="k-button k-grid-save-command"
onClick={() => isNewItem ? add(dataItem) : update(dataItem)}
>
{isNewItem ? 'Add' : 'Update'}
</button>
<button
className="k-button k-grid-cancel-command"
onClick={() => isNewItem ? discard(dataItem) : cancel(dataItem)}
>
{isNewItem ? 'Discard' : 'Cancel'}
</button>
</td>
) : (
<td className="k-command-cell">
<button
className="k-primary k-button k-grid-edit-command"
onClick={() => edit(dataItem)}
>
Edit
</button>
<button
className="k-button k-grid-remove-command"
onClick={() =>
remove(dataItem)
}
>
Remove
</button>
</td>
);
}
}
};<file_sep>/src/client/src/types/rowType.d.ts
import { FormattedMessage } from "react-intl";
import { IFunctionName } from "../containers/AzureFunctionsSelection";
export interface RowType {
title: string;
svgUrl?: string;
functionNames?: IFunctionName[];
company?: string;
originalTitle?: string;
serviceTitle?: FormattedMessage.MessageDescriptor;
id?: string;
version: string;
internalName?: string;
author?: string;
}
<file_sep>/src/client/src/actions/azureActions/setAzureValidationStatusAction.ts
import { AZURE_TYPEKEYS } from "./typeKeys";
export interface IAzureValidationStatus {
type: AZURE_TYPEKEYS.SET_VALIDATION_STATUS;
payload: boolean;
}
export const setAzureValidationStatusAction = (
status: boolean
): IAzureValidationStatus => ({
payload: status,
type: AZURE_TYPEKEYS.SET_VALIDATION_STATUS
});
<file_sep>/src/client/src/reducers/wizardSelectionReducers/services/cosmosDbReducer.ts
import { AZURE_TYPEKEYS } from "../../../actions/azureActions/typeKeys";
import { FormattedMessage } from "react-intl";
import { messages } from "../../../selectors/wizardSelectionSelector";
import AzureActionType from "../../../actions/azureActions/azureActionType";
import { WIZARD_INFO_TYPEKEYS } from "../../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../../actions/wizardInfoActions/wizardInfoActionType";
/* State Shape
{
cosmosDB: {
appNameAvailability: {
isAppNameAvailable: boolean,
message: string
},
selection: [],
wizardContent: {
serviceType: string,
}
}
}
*/
export interface IAvailability {
isAccountNameAvailable: boolean;
message: string;
}
export interface ISelectedCosmosService {
subscription: string;
resourceGroup: string;
accountName: string;
api: string;
location: string;
internalName: string;
}
interface IServiceContent {
serviceType: FormattedMessage.MessageDescriptor;
}
export interface ICosmosDB {
accountNameAvailability: IAvailability;
selection: ISelectedCosmosService[];
wizardContent: IServiceContent;
}
const initialState = {
accountNameAvailability: {
isAccountNameAvailable: false,
message: "Account name unavailable"
},
selection: [],
wizardContent: {
serviceType: messages.cosmosOriginalTitle
}
};
const services = (
state: ICosmosDB = initialState,
action: AzureActionType | WizardInfoType
) => {
switch (action.type) {
case AZURE_TYPEKEYS.SAVE_COSMOS_DB_RESOURCE_SETTINGS:
const newSelectionState = {
...initialState,
selection: [
{
subscription: action.payload.subscription.value,
resourceGroup: action.payload.resourceGroup.value,
location: action.payload.location.value,
api: action.payload.api.value,
accountName: action.payload.accountName.value,
internalName: action.payload.internalName.value
}
]
};
return newSelectionState;
case AZURE_TYPEKEYS.SET_ACCOUNT_AVAILABILITY:
const newAvailabilityState = {
...state,
accountNameAvailability: {
isAccountNameAvailable: action.payload.isAvailable,
message: action.payload.message
}
};
return newAvailabilityState;
case AZURE_TYPEKEYS.REMOVE_COSMOS_RESOURCE:
const cosmosSelections = [...state.selection];
cosmosSelections.splice(action.payload, 1);
return {
...state,
selection: cosmosSelections
};
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
case AZURE_TYPEKEYS.LOG_OUT_OF_AZURE:
return initialState;
default:
return state;
}
};
export default services;
<file_sep>/src/extension/src/azure/azure-arm/armFileHelper.ts
import * as fsx from "fs-extra";
export namespace ARMFileHelper {
export function creatDirIfNonExistent(dirPath: string): void {
if (!fsx.pathExistsSync(dirPath)) {
fsx.mkdirpSync(dirPath);
}
}
export function writeObjectToJsonFile(
filePath: string,
object: object
): void {
fsx.writeFileSync(filePath, JSON.stringify(object, null, 2), "utf-8");
}
}
<file_sep>/src/client/src/actions/azureActions/azureActionType.ts
import {
IUpdateFunctionNamesAction,
ISaveAzureFunctionsSettings,
IRemoveAzureFunction,
IRemoveAzureFunctionApp
} from "./azureFunctionActions";
import { IsLoggedIntoAzure, ILoginToAzure } from "./logIntoAzure";
import { ILogout } from "./logOutAzure";
import {
ISaveCosmosDbSettings,
IRemoveCosmosDbSettings
} from "./saveCosmosDbSettings";
import {
ISetCosmosAccountNameAvailability,
ISetAzureFunctionsAppNameAvailability
} from "./setAccountAvailability";
import { IAzureValidationStatus } from "./setAzureValidationStatusAction";
import { IGetSubscription } from "./subscriptionData";
type AzureActionType =
| IUpdateFunctionNamesAction
| ISaveAzureFunctionsSettings
| IRemoveAzureFunction
| IRemoveAzureFunctionApp
| IsLoggedIntoAzure
| ILoginToAzure
| ILogout
| ISaveCosmosDbSettings
| IRemoveCosmosDbSettings
| ISetCosmosAccountNameAvailability
| ISetAzureFunctionsAppNameAvailability
| IAzureValidationStatus
| IGetSubscription;
export default AzureActionType;
<file_sep>/src/extension/src/launchExperience.ts
import * as vscode from "vscode";
import { CONSTANTS } from "./constants";
import { CoreTemplateStudio } from "./coreTemplateStudio";
import { ISyncReturnType } from "./types/syncReturnType";
import { IVSCodeProgressType } from "./types/vscodeProgressType";
import { Logger } from "./utils/logger";
export class LaunchExperience {
private static _progressObject: vscode.Progress<IVSCodeProgressType>;
constructor(progressObject: vscode.Progress<IVSCodeProgressType>) {
LaunchExperience._progressObject = progressObject;
}
public async launchApiSyncModule(
context: vscode.ExtensionContext
): Promise<ISyncReturnType> {
await CoreTemplateStudio.GetInstance(context);
LaunchExperience._progressObject.report({
message: CONSTANTS.INFO.STARTING_GENERATION_SERVER
});
let syncObject: ISyncReturnType = {
successfullySynced: false,
templatesVersion: ""
};
let syncAttempts = 0;
while (
!syncObject.successfullySynced &&
syncAttempts < CONSTANTS.API.MAX_SYNC_REQUEST_ATTEMPTS
) {
syncObject = await this.attemptSync();
syncAttempts++;
if (!syncObject.successfullySynced) {
await this.timeout(CONSTANTS.API.SYNC_RETRY_WAIT_TIME);
}
}
if (syncAttempts >= CONSTANTS.API.MAX_SYNC_REQUEST_ATTEMPTS) {
CoreTemplateStudio.DestroyInstance();
throw new Error(CONSTANTS.ERRORS.TOO_MANY_FAILED_SYNC_REQUESTS);
}
return { ...syncObject };
}
private timeout(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
private async attemptSync(): Promise<ISyncReturnType> {
let pathToTemplates: string;
if (process.env.NODE_ENV === "dev") {
pathToTemplates = CONSTANTS.API.DEVELOPMENT_PATH_TO_TEMPLATES;
} else {
pathToTemplates = CONSTANTS.API.PRODUCTION_PATH_TO_TEMPLATES;
}
let apiInstance = CoreTemplateStudio.GetExistingInstance();
return await apiInstance
.sync({
port: apiInstance.getPort(),
payload: { path: pathToTemplates },
liveMessageHandler: this.handleSyncLiveData
})
.then((syncResult: any) => {
Logger.appendLog(
"EXTENSION",
"info",
"Successfully synced templates. Version: " +
syncResult.templatesVersion
);
return {
successfullySynced: true,
templatesVersion: syncResult.templatesVersion
};
})
.catch((error: Error) => {
Logger.appendLog("EXTENSION", "error", error.message);
return { successfullySynced: false, templatesVersion: "" };
});
}
private handleSyncLiveData(status: string, progress?: number) {
let output = `Templates - ${status}`;
let increment: number | undefined;
if (progress) {
output += ` ${progress}%`;
increment = 1;
}
LaunchExperience._progressObject.report({
message: output,
increment
});
vscode.window.setStatusBarMessage(output, 2000);
}
}
<file_sep>/src/extension/src/azure/azure-functions/utils/index.ts
export * from "./fileHelper";
export * from "./validationHelper";
export * from "./zipDeployHelper";
<file_sep>/src/extension/src/services/engineAPIService.ts
import fetch from "node-fetch";
import * as constants from "./constants";
export default class EngineAPIService {
private API: string;
constructor(port: number, url: string | undefined) {
if (url === undefined) {
this.API = "http://localhost:" + port;
} else {
this.API = url + ":" + port;
}
}
public async putSavedTextDocument(filePath: string) {
const url = new URL(constants.API.Endpoints.SavedTextDocument, this.API);
await fetch(url.href, { method: constants.API.Methods.POST, body: filePath })
};
}<file_sep>/src/client/src/reducers/dependencyInfoReducers/index.spec.ts
import { updateDependencyInfo as dependencyInfo, initialState } from "./index";
import { updateDependencyInfoAction } from "../../actions/wizardInfoActions/updateDependencyInfo";
describe("dependencyInfo reducer", () => {
it("should handle initial state", () => {
expect(dependencyInfo(undefined, {})).toEqual(initialState);
});
it("should add new dependencies", () => {
const mockAction = updateDependencyInfoAction({
dependency: "python",
installed: true
});
const expectedState = {
python: {
installed: true
}
};
expect(dependencyInfo(initialState, mockAction)).toEqual(expectedState);
});
it("should change installation state", () => {
const mockAction = updateDependencyInfoAction({
dependency: "node",
installed: true
});
const expectedState = {
node: {
installed: true
}
};
expect(dependencyInfo({ node: { installed: false } }, mockAction)).toEqual(
expectedState
);
});
});
<file_sep>/templates/Web/_composition/ReactJS/Page.React.AddRoute/src/App_postaction.jsx
class App extends Component {
render() {
return (
<React.Fragment>
<NavBar />
<Switch>
//^^
//{[{
<Route path = "/wts.ItemName" component = { wts.ItemName } />
//}]}
</Switch>
<Footer />
</React.Fragment>
);
}
}<file_sep>/src/client/src/reducers/vscodeApiReducer.ts
import { VSCODE_TYPEKEYS } from "../actions/vscodeApiActions/typeKeys";
import { PRODUCTION } from "../utils/constants";
import mockVsCodeApi from "../mockData/mockVsCodeApi";
import { IVSCodeAPIActionType } from "../actions/vscodeApiActions/getVSCodeApi";
/* State Shape
{
vscode: {
isVsCodeApiAcquired: boolean,
vscode: any
}
}
*/
export interface IVSCode {
vscode: IVSCodeAPI;
}
export interface IVSCodeObject {
postMessage: (message: any) => void;
}
interface IVSCodeAPI {
isVsCodeApiAcquired: boolean;
vscodeObject: IVSCodeObject;
}
function vscodeApi(
state: IVSCodeAPI = {
isVsCodeApiAcquired: false,
vscodeObject: mockVsCodeApi()
},
action: IVSCodeAPIActionType
) {
switch (action.type) {
case VSCODE_TYPEKEYS.GET_VSCODE_API:
if (!state.isVsCodeApiAcquired) {
const newState = { ...state };
newState.isVsCodeApiAcquired = true;
newState.vscodeObject =
process.env.NODE_ENV === PRODUCTION
? //
// @ts-ignore because function does not exist in dev environment
// eslint-disable-next-line
acquireVsCodeApi()
: mockVsCodeApi();
return newState;
}
return state;
default:
return state;
}
}
export default vscodeApi;
<file_sep>/templates/Web/_composition/KendoVue/Page.Kendo.Vue.AddImport/src/router/index_postaction.js
import { createWebHistory, createRouter } from "vue-router";
import Home from "../components/Home";
//^^
//{[{
import Param_SourceName_Pascal from "../components/Param_SourceName_Pascal";
//}]}<file_sep>/src/client/src/actions/wizardContentActions/getProjectTypesSuccess.ts
import { IOption } from "../../types/option";
import { WIZARD_CONTENT_TYPEKEYS } from "./typeKeys";
export interface IProjectTypesActionType {
type: WIZARD_CONTENT_TYPEKEYS.GET_PROJECT_TYPES_SUCCESS;
payload: IOption[];
}
const getProjectTypesSuccess = (items: IOption[]): IProjectTypesActionType => ({
type: WIZARD_CONTENT_TYPEKEYS.GET_PROJECT_TYPES_SUCCESS,
payload: items
});
export { getProjectTypesSuccess };
<file_sep>/src/extension/src/signalr-api-module/coreTemplateStudioApiCommand.ts
import { ICommandPayload } from "./commandPayload";
import * as signalR from "@aspnet/signalr";
export abstract class CoreTemplateStudioApiCommand {
protected readonly commandPayload: ICommandPayload;
constructor(commandPayload: ICommandPayload) {
this.commandPayload = commandPayload;
}
public async execute(
connection: signalR.HubConnection
): Promise<any> {
return this.performCommandAction(connection);
}
abstract async performCommandAction(
connection: signalR.HubConnection
): Promise<any>;
}
<file_sep>/docs/telemetry.md
# Web Template Studio Telemetry
Web Template Studio logs usage data and diagnostics telemetry through [Application Insights](https://azure.microsoft.com/en-us/services/monitor/).
## Telemetry Gathered
The wizard for Web Template Studio collects basic diagnostics telemetry and usage data:
- **Diagnostics telemetry:** Unhandled error and exceptions that happened while running the
wizard are logged with Application Insights. This includes the stack trace of the error
- **Usage telemetry:** including wizard usage and user selections.
## Usage Telemetry
Through the Application Insights API, telemetry events are collected to gather basic information regarding Web Template Studio extension usage. The following table describes the Telemetry Events we collect:
| **Property** | **Note** |
| :-------------------: | ---------------------------------------------------------------------------------------------------- |
| **Event Time** | Timestamp for when the event occurred |
| **Event Name** | Unique event name/descriptor for the event. For ex: WebTemplateStudioVsix/Azure-Functions-Deployment |
| **VSCode Session ID** | A unique identifier for the current session. Changes each time the editor is started. |
| **VSCode Machine ID** | A unique identifier for the computer |
| **VSCode Version** | VSCode version being used by the user |
| **Extension Version** | Web Template Studio extension version being used |
| **OS** | User's operating system |
| **Error** | Error description if an error occurs |
| **Stack** | Error stack trace if an error occurs |
| **Result** | If the event succeeded or not |
<file_sep>/templates/Web/_composition/KendoReact/Page.Kendo.React.AddImport/src/App_postaction.js
import React, {useState} from 'react';
import './App.scss';
import { Header } from './components/Header'
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from './components/Home';
import Footer from './components/Footer';
//^^
//{[{
import Param_SourceName_Pascal from "./components/Param_SourceName_Pascal";
//}]}
function App() {<file_sep>/src/client/src/actions/azureActions/typeKeys.ts
export enum AZURE_TYPEKEYS {
IS_LOGGED_IN_TO_AZURE = "WTS/azure/IS_LOGGED_IN_TO_AZURE",
LOG_IN_TO_AZURE = "WTS/azure/LOG_IN_TO_AZURE",
LOG_OUT_OF_AZURE = "WTS/azure/LOG_OUT_OF_AZURE",
SAVE_COSMOS_DB_RESOURCE_SETTINGS = "WTS/azure/SAVE_COSMOS_DB_RESOURCE_SETTINGS",
SAVE_AZURE_FUNCTIONS_SETTINGS = "WTS/azure/SAVE_AZURE_FUNCTIONS_SETTINGS",
GET_SUBSCRIPTION_DATA = "WTS/azure/GET_SUBSCRIPTION_DATA",
SET_ACCOUNT_AVAILABILITY = "WTS/cosmosDb/SET_ACCOUNT_AVAILABILITY",
SET_APP_NAME_AVAILABILITY = "WTS/azureFunctions/SET_APP_NAME_AVAILABILITY",
UPDATE_AZURE_FUNCTION_NAMES = "WTS/azureFunctions/UPDATE_AZURE_FUNCTIONS",
REMOVE_COSMOS_RESOURCE = "WTS/cosmosDB/REMOVE_COSMOS_RESOURCE",
REMOVE_AZURE_FUNCTIONS_APP = "WTS/azureFunctions/REMOVE_AZURE_FUNCTIONS_APP",
REMOVE_AZURE_FUNCTION = "WTS/azureFunctions/REMOVE_AZURE_FUNCTION",
SET_VALIDATION_STATUS = "WTS/azure/SET_VALIDATION_STATUS"
}
<file_sep>/src/client/src/reducers/wizardSelectionReducers/selectPagesReducer.ts
import WizardSelectionActionType from "../../actions/wizardSelectionActions/wizardSelectionActionType";
import { ISelected } from "../../types/selected";
import { WIZARD_SELECTION_TYPEKEYS } from "../../actions/wizardSelectionActions/typeKeys";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
/* State Shape
{
pages: ISelected[]
}
*/
const pagesReducer = (
state: ISelected[] = [],
action: WizardSelectionActionType | WizardInfoType
) => {
switch (action.type) {
case WIZARD_SELECTION_TYPEKEYS.SELECT_PAGES:
const newPages: ISelected[] = [...action.payload];
return newPages;
case WIZARD_SELECTION_TYPEKEYS.RESET_PAGES:
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return [];
default:
return state;
}
};
export default pagesReducer;
<file_sep>/src/client/src/actions/wizardContentActions/setPreviewStatus.ts
import { WIZARD_CONTENT_TYPEKEYS } from "./typeKeys";
export interface IPreviewStatusActionType {
type: WIZARD_CONTENT_TYPEKEYS.SET_PREVIEW_STATUS;
payload: boolean;
}
export const setPreviewStatusAction = (
isPreview: boolean
): IPreviewStatusActionType => ({
payload: isPreview,
type: WIZARD_CONTENT_TYPEKEYS.SET_PREVIEW_STATUS
});
<file_sep>/templates/Web/Pages/Angular.MasterDetail/src/app/app-shell/Param_SourceName_Kebab/Param_SourceName_Kebab.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MasterDetailComponent } from './master-detail.component';
import { MasterDetailSidebarTabComponent } from './master-detail-sidebar-tab/master-detail-sidebar-tab.component';
import { WarningMessageModule } from '../../shared/warning-message/warning-message.module';
import { MasterDetailPageComponent } from './master-detail-page/master-detail-page.component';
import { Param_SourceName_PascalRoutingModule } from './Param_SourceName_Kebab-routing.module';
@NgModule({
declarations: [
MasterDetailComponent,
MasterDetailSidebarTabComponent,
MasterDetailPageComponent
],
imports: [
CommonModule,
WarningMessageModule,
Param_SourceName_PascalRoutingModule
]
})
export class Param_SourceName_PascalModule { }
<file_sep>/src/client/src/selectors/vscodeApiSelector.ts
import { IVSCodeObject } from "../reducers/vscodeApiReducer";
import { IVersions } from "../types/version";
import { AppState } from "../reducers";
const getVSCodeApiSelector = (state: AppState): IVSCodeObject =>
state.vscode.vscodeObject;
const getVersionsSelector = (state: any): IVersions => state.versions;
export { getVSCodeApiSelector, getVersionsSelector };
<file_sep>/src/client/src/actions/modalActions/modalActionType.ts
import { ICloseModal, IOpenModal } from "./modalActions";
type ModalActionType = ICloseModal | IOpenModal;
export default ModalActionType;
<file_sep>/src/client/src/reducers/azureLoginReducers/index.ts
import { combineReducers } from "redux";
import profileData from "./azureProfileReducer";
import isLoggedIn from "./isLoggedInReducer";
import subscriptionData from "./subscriptionDataReducer";
export default combineReducers({
isLoggedIn,
profileData,
subscriptionData
});
<file_sep>/src/extension/src/azure/azureServices.ts
import * as vscode from "vscode";
import {
AzureAuth,
SubscriptionItem,
LocationItem
} from "./azure-auth/azureAuth";
import {
CosmosDBDeploy,
CosmosDBSelections,
DatabaseObject
} from "./azure-cosmosDB/cosmosDbModule";
import {
FunctionProvider,
FunctionSelections
} from "./azure-functions/functionProvider";
import {
CONSTANTS,
AzureResourceType,
DialogMessages,
DialogResponses,
ExtensionCommand
} from "../constants";
import {
SubscriptionError,
AuthorizationError,
ValidationError
} from "../errors";
import { WizardServant, IPayloadResponse } from "../wizardServant";
import {
FunctionValidationResult,
ValidationHelper
} from "./azure-functions/utils/validationHelper";
import { Logger } from "../utils/logger";
export class AzureServices extends WizardServant {
clientCommandMap: Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
> = new Map([
[ExtensionCommand.Login, AzureServices.performLoginForSubscriptions],
[ExtensionCommand.GetUserStatus, AzureServices.sendUserStatusIfLoggedIn],
[ExtensionCommand.Logout, AzureServices.performLogout],
[
ExtensionCommand.SubscriptionDataForCosmos,
AzureServices.sendCosmosSubscriptionDataToClient
],
[
ExtensionCommand.SubscriptionDataForFunctions,
AzureServices.sendFunctionsSubscriptionDataToClient
],
[
ExtensionCommand.NameFunctions,
AzureServices.sendFunctionNameValidationStatusToClient
],
[
ExtensionCommand.NameCosmos,
AzureServices.sendCosmosNameValidationStatusToClient
]
]);
private static AzureFunctionProvider = new FunctionProvider();
private static AzureCosmosDBProvider = new CosmosDBDeploy();
private static subscriptionItemList: SubscriptionItem[] = [];
private static usersCosmosDBSubscriptionItemCache: SubscriptionItem;
private static usersFunctionSubscriptionItemCache: SubscriptionItem;
public static async performLoginForSubscriptions(
message: any
): Promise<IPayloadResponse> {
Logger.appendLog("EXTENSION", "info", "Attempt to log user in");
let isLoggedIn = await AzureAuth.login();
if (isLoggedIn) {
Logger.appendLog("EXTENSION", "info", "User logged in");
return AzureServices.sendUserStatusIfLoggedIn(message);
}
throw new AuthorizationError(CONSTANTS.ERRORS.LOGIN_TIMEOUT);
}
public static async sendUserStatusIfLoggedIn(
message: any
): Promise<IPayloadResponse> {
if (AzureAuth.getEmail()) {
AzureServices.subscriptionItemList = await AzureAuth.getSubscriptions();
const subscriptionListToDisplay = AzureServices.subscriptionItemList.map(
subscriptionItem => {
return {
label: subscriptionItem.label,
value: subscriptionItem.label
};
}
);
return {
payload: {
email: AzureAuth.getEmail(),
subscriptions: subscriptionListToDisplay
}
};
} else {
return { payload: null };
}
}
public static async performLogout(message: any): Promise<IPayloadResponse> {
let success = await AzureAuth.logout();
let payloadResponse: IPayloadResponse = { payload: success };
return payloadResponse;
}
public static async sendCosmosSubscriptionDataToClient(
message: any
): Promise<IPayloadResponse> {
return {
payload: await AzureServices.getSubscriptionData(
message.subscription,
AzureResourceType.Cosmos
)
};
}
public static async sendFunctionsSubscriptionDataToClient(
message: any
): Promise<IPayloadResponse> {
return {
payload: await AzureServices.getSubscriptionData(
message.subscription,
AzureResourceType.Functions
)
};
}
/**
* @param subscriptionLabel subscription label
* @returns a Json object of Formatted Resource and Location strings
*
* */
private static async getSubscriptionData(
subscriptionLabel: string,
AzureType: AzureResourceType
) {
let subscriptionItem = AzureServices.subscriptionItemList.find(
subscriptionItem => subscriptionItem.label === subscriptionLabel
);
if (subscriptionItem === undefined) {
throw new SubscriptionError(CONSTANTS.ERRORS.SUBSCRIPTION_NOT_FOUND);
}
let resourceGroupItems = AzureAuth.getAllResourceGroupItems(
subscriptionItem
).then(resourceGroups => {
let formatResourceGroupList = [];
formatResourceGroupList.push(
...resourceGroups.map(resourceGroup => {
return {
label: resourceGroup.name,
value: resourceGroup.name
};
})
);
return formatResourceGroupList;
});
var locationItems: LocationItem[] = [];
switch (AzureType) {
case AzureResourceType.Cosmos:
locationItems = await AzureAuth.getLocationsForCosmos(subscriptionItem);
break;
case AzureResourceType.Functions:
locationItems = await AzureAuth.getLocationsForFunctions(
subscriptionItem
);
break;
}
let locations = [];
locations.push(
...locationItems.map(location => {
return {
label: location.locationDisplayName,
value: location.locationDisplayName
};
})
);
return {
resourceGroups: await resourceGroupItems,
locations: locations
};
}
public static async sendCosmosNameValidationStatusToClient(
message: any
): Promise<IPayloadResponse> {
await AzureServices.updateCosmosDBSubscriptionItemCache(
message.subscription
);
return await AzureServices.AzureCosmosDBProvider.validateCosmosDBAccountName(
message.appName,
AzureServices.usersCosmosDBSubscriptionItemCache
)
.then((invalidReason: string | undefined) => {
return {
payload: {
isAvailable:
!invalidReason ||
invalidReason === undefined ||
invalidReason === "",
reason: invalidReason
}
};
})
.catch((error: Error) => {
throw error; //to log in telemetry
});
}
public static async sendFunctionNameValidationStatusToClient(
message: any
): Promise<IPayloadResponse> {
await AzureServices.updateFunctionSubscriptionItemCache(
message.subscription
);
return AzureServices.AzureFunctionProvider.checkFunctionAppName(
message.appName,
AzureServices.usersFunctionSubscriptionItemCache
)
.then((invalidReason: string | undefined) => {
return {
payload: {
isAvailable:
!invalidReason ||
invalidReason === undefined ||
invalidReason === "",
reason: invalidReason
}
};
})
.catch((error: Error) => {
throw error; //to log in telemetry
});
}
/*
* Caching is used for performance; when displaying live check on keystroke to wizard
*/
private static async updateCosmosDBSubscriptionItemCache(
subscriptionLabel: string
): Promise<void> {
if (
AzureServices.usersCosmosDBSubscriptionItemCache === undefined ||
subscriptionLabel !==
AzureServices.usersCosmosDBSubscriptionItemCache.label
) {
let subscriptionItem = AzureServices.subscriptionItemList.find(
subscriptionItem => subscriptionItem.label === subscriptionLabel
);
if (subscriptionItem) {
AzureServices.usersCosmosDBSubscriptionItemCache = subscriptionItem;
} else {
throw new SubscriptionError(CONSTANTS.ERRORS.SUBSCRIPTION_NOT_FOUND);
}
}
}
private static async updateFunctionSubscriptionItemCache(
subscriptionLabel: string
): Promise<void> {
if (
AzureServices.usersFunctionSubscriptionItemCache === undefined ||
subscriptionLabel !==
AzureServices.usersFunctionSubscriptionItemCache.label
) {
let subscriptionItem = AzureServices.subscriptionItemList.find(
subscriptionItem => subscriptionItem.label === subscriptionLabel
);
if (subscriptionItem) {
AzureServices.usersFunctionSubscriptionItemCache = subscriptionItem;
} else {
throw new SubscriptionError(CONSTANTS.ERRORS.SUBSCRIPTION_NOT_FOUND);
}
}
}
public static async deployFunctionApp(
selections: any,
appPath: string
): Promise<void> {
await AzureServices.updateFunctionSubscriptionItemCache(
selections.subscription
);
let userFunctionsSelections: FunctionSelections = {
functionAppName: selections.appName,
subscriptionItem: AzureServices.usersFunctionSubscriptionItemCache,
resourceGroupItem: await AzureAuth.getResourceGroupItem(
selections.resourceGroup,
AzureServices.usersFunctionSubscriptionItemCache
),
location: selections.location,
runtime: selections.runtimeStack,
functionNames: selections.functionNames
};
let functionNamesValidation: FunctionValidationResult = ValidationHelper.validateFunctionNames(
userFunctionsSelections.functionNames
);
if (!functionNamesValidation.isValid) {
throw new ValidationError(functionNamesValidation.message);
}
await AzureServices.AzureFunctionProvider.checkFunctionAppName(
userFunctionsSelections.functionAppName,
userFunctionsSelections.subscriptionItem
)
.then(invalidReason => {
if (invalidReason !== undefined && invalidReason === "") {
throw new ValidationError(invalidReason);
}
})
.catch((error: Error) => {
throw error; //to log in telemetry
});
return await AzureServices.AzureFunctionProvider.createFunctionApp(
userFunctionsSelections,
appPath
);
}
public static async deployCosmosResource(
selections: any,
genPath: string
): Promise<DatabaseObject> {
await AzureServices.updateCosmosDBSubscriptionItemCache(
selections.subscription
);
let userCosmosDBSelection: CosmosDBSelections = {
cosmosAPI: selections.api,
cosmosDBResourceName: selections.accountName,
location: selections.location,
resourceGroupItem: await AzureAuth.getResourceGroupItem(
selections.resourceGroup,
AzureServices.usersCosmosDBSubscriptionItemCache
),
subscriptionItem: AzureServices.usersCosmosDBSubscriptionItemCache
};
await AzureServices.AzureCosmosDBProvider.validateCosmosDBAccountName(
userCosmosDBSelection.cosmosDBResourceName,
userCosmosDBSelection.subscriptionItem
)
.then(invalidReason => {
if (invalidReason !== undefined && invalidReason === "") {
throw new ValidationError(invalidReason);
}
})
.catch((error: Error) => {
throw error; //to log in telemetry
});
return await AzureServices.AzureCosmosDBProvider.createCosmosDB(
userCosmosDBSelection,
genPath
);
}
public static async promptUserForCosmosReplacement(
pathToEnv: string,
dbObject: DatabaseObject
) {
return await vscode.window
.showInformationMessage(
DialogMessages.cosmosDBConnectStringReplacePrompt,
...[DialogResponses.yes, DialogResponses.no]
)
.then((selection: vscode.MessageItem | undefined) => {
var start = Date.now();
if (selection === DialogResponses.yes) {
CosmosDBDeploy.updateConnectionStringInEnvFile(
pathToEnv,
dbObject.connectionString
);
vscode.window.showInformationMessage(
CONSTANTS.INFO.FILE_REPLACED_MESSAGE + pathToEnv
);
}
return {
userReplacedEnv: selection === DialogResponses.yes,
startTime: start
};
});
}
}
<file_sep>/templates/Web/Projects/AngularDefault/README_postaction.md
## Getting Started
In the root directory of the project...
1. Install node modules `yarn install` or `npm install`.
2. Start development server `yarn start` or `npm start`.
## Next Steps
//{[{
### Adding a New Page
1. Create a folder in `/src/app/app-shell` with your angular modules.
2. Add a child route for your page to `/src/app/*.module.ts`.
3. Add a button to the navigation bar in `/src/app/app-shell/nav-bar/nav-bar.component.html`.
//}]}
### Deployment
## File Structure
//{[{
The front-end is based on [Angular cli "ng"](https://angular.io/cli).
//}]}
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
//^^
//{[{
├── src - Angular front-end
│ └── app - Angular main root module
│ ├── app-shell - Angular main components
│ └── app.module.ts - Angular root module.
//}]}
└── README.md
```
## Additional Documentation
//{[{
- Angular Docs - https://angular.io/docs
- Angular Router - https://angular.io/guide/router
//}]}
- Bootstrap CSS - https://getbootstrap.com/
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/templates/Web/Pages/KendoReact.Blank/src/components/Param_SourceName_Pascal.jsx
import React from "react";
export default function Param_SourceName_Pascal() {
return (<div>Add a KendoReact component here</div>);
}
<file_sep>/src/client/src/actions/wizardSelectionActions/selectPages.ts
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
import { ISelected } from "../../types/selected";
import { IPageCount } from "../../reducers/wizardSelectionReducers/pageCountReducer";
export interface ISelectPagesAction {
type: WIZARD_SELECTION_TYPEKEYS.SELECT_PAGES;
payload: ISelected[];
}
export interface IUpdatePageCountAction {
type: WIZARD_SELECTION_TYPEKEYS.UPDATE_PAGE_COUNT;
payload: IPageCount;
}
export interface IResetPagesAction {
type: WIZARD_SELECTION_TYPEKEYS.RESET_PAGES;
}
const selectPagesAction = (pages: ISelected[]): ISelectPagesAction => ({
type: WIZARD_SELECTION_TYPEKEYS.SELECT_PAGES,
payload: pages
});
const updatePageCountAction = (
pageCount: IPageCount
): IUpdatePageCountAction => ({
type: WIZARD_SELECTION_TYPEKEYS.UPDATE_PAGE_COUNT,
payload: pageCount
});
const resetPagesAction = (): IResetPagesAction => ({
type: WIZARD_SELECTION_TYPEKEYS.RESET_PAGES
});
export { selectPagesAction, updatePageCountAction, resetPagesAction };
<file_sep>/src/client/src/reducers/wizardSelectionReducers/services/azureFunctionsReducer.ts
import { AZURE_TYPEKEYS } from "../../../actions/azureActions/typeKeys";
import { messages } from "../../../selectors/wizardSelectionSelector";
import { FormattedMessage } from "react-intl";
import AzureActionType from "../../../actions/azureActions/azureActionType";
import { WIZARD_INFO_TYPEKEYS } from "../../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../../actions/wizardInfoActions/wizardInfoActionType";
import { IFunctionName } from "../../../containers/AzureFunctionsSelection";
/* State Shape
{
azureFunctions: {
appNameAvailability: {
isAppNameAvailable: boolean,
message: string
},
selection: [],
wizardContent: {
serviceType: string,
}
}
}
*/
interface IAvailability {
isAppNameAvailable: boolean;
message: string;
}
export interface ISelectedAzureFunctionsService {
[key: string]: IDropDownOptionType | IFunctionName[] | undefined;
subscription: IDropDownOptionType;
resourceGroup: IDropDownOptionType;
appName: IDropDownOptionType;
runtimeStack: IDropDownOptionType;
location: IDropDownOptionType;
internalName: IDropDownOptionType;
numFunctions: IDropDownOptionType;
functionNames?: IFunctionName[];
}
interface IServiceContent {
serviceType: FormattedMessage.MessageDescriptor;
}
export interface IAzureFunctionsSelection {
appNameAvailability: IAvailability;
selection: ISelectedAzureFunctionsService[];
wizardContent: IServiceContent;
}
const initialState = {
appNameAvailability: {
isAppNameAvailable: false,
message: "App name unavailable"
},
selection: [],
wizardContent: {
serviceType: messages.azureFunctionsOriginalTitle
}
};
const getFunctionNames = (functionNames: IFunctionName[]): string[] => {
const names: string[] = [];
functionNames.forEach((functionName: IFunctionName) => {
names.push(functionName.title);
});
return names;
};
const createFunctionNames = (
numFunctions: number,
prevFunctionNames?: IFunctionName[]
): IFunctionName[] => {
if (prevFunctionNames) {
if (prevFunctionNames.length >= numFunctions) {
const numFunctionsToDelete = prevFunctionNames.length - numFunctions;
const startIndex = prevFunctionNames.length - numFunctionsToDelete;
prevFunctionNames.splice(startIndex, numFunctionsToDelete);
} else {
const numFunctionsToCreate = numFunctions - prevFunctionNames.length;
let lastNumberUsed = 1;
for (let i = 1; i <= numFunctionsToCreate; i++) {
let title = `function${lastNumberUsed}`;
while (getFunctionNames(prevFunctionNames).includes(title)) {
lastNumberUsed++;
title = `function${lastNumberUsed}`;
}
prevFunctionNames.push({
title,
isValidTitle: true,
error: "",
id: title
});
}
}
return [...prevFunctionNames];
}
const functionNames: IFunctionName[] = [];
for (let i = 1; i <= numFunctions; i++) {
const title = `function${i}`;
functionNames.push({
title,
isValidTitle: true,
error: "",
id: title
});
}
return functionNames;
};
const azureFunctions = (
state: IAzureFunctionsSelection = initialState,
action: AzureActionType | WizardInfoType
) => {
switch (action.type) {
case AZURE_TYPEKEYS.UPDATE_AZURE_FUNCTION_NAMES:
const newFunctionNamesState = { ...state };
newFunctionNamesState.selection[action.payload.appIndex].functionNames =
action.payload.functionNames;
return newFunctionNamesState;
case AZURE_TYPEKEYS.SET_APP_NAME_AVAILABILITY:
const newAvailabilityState = {
...state,
appNameAvailability: {
isAppNameAvailable: action.payload.isAvailable,
message: action.payload.message
}
};
return newAvailabilityState;
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
case AZURE_TYPEKEYS.LOG_OUT_OF_AZURE:
return initialState;
case AZURE_TYPEKEYS.REMOVE_AZURE_FUNCTIONS_APP:
if (state.selection[0].functionNames) {
// the state must be deeply mutated in order to be recognized as a state change in redux
const newFunctionApp = [...state.selection];
newFunctionApp.splice(action.payload, 1);
const newAppState = {
...state,
selection: [...newFunctionApp]
};
return newAppState;
}
return state;
case AZURE_TYPEKEYS.REMOVE_AZURE_FUNCTION:
// hardcoding 0th index because only 1 function app can currently be added
const newFunctionState = { ...state };
const { functionNames } = newFunctionState.selection[0];
if (functionNames) {
functionNames.splice(action.payload, 1);
newFunctionState.selection[0].functionNames = functionNames;
newFunctionState.selection[0].numFunctions = {
label: functionNames.length,
value: functionNames.length
};
}
return newFunctionState;
case AZURE_TYPEKEYS.SAVE_AZURE_FUNCTIONS_SETTINGS:
const newSelectionState = {
...initialState,
selection: [
{
subscription: action.payload.subscription,
resourceGroup: action.payload.resourceGroup,
location: action.payload.location,
runtimeStack: action.payload.runtimeStack,
internalName: action.payload.internalName,
numFunctions: action.payload.numFunctions,
functionNames: createFunctionNames(
action.payload.numFunctions.value,
state.selection[0] ? state.selection[0].functionNames : undefined
),
appName: action.payload.appName
}
]
};
return newSelectionState;
default:
return state;
}
};
export default azureFunctions;
<file_sep>/src/client/src/reducers/wizardContentReducers/projectTypeReducer.ts
import { WIZARD_CONTENT_TYPEKEYS } from "../../actions/wizardContentActions/typeKeys";
import WizardContentActionType from "../../actions/wizardContentActions/wizardContentActionType";
import { IOption } from "../../types/option";
/* State Shape
{
projectTypes: []
}
*/
const projectTypes = (
state: IOption[] = [],
action: WizardContentActionType
) => {
switch (action.type) {
case WIZARD_CONTENT_TYPEKEYS.GET_PROJECT_TYPES_SUCCESS:
return action.payload;
default:
return state;
}
};
export default projectTypes;
<file_sep>/src/client/src/reducers/dependencyInfoReducers/index.ts
import { combineReducers } from "redux";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import { IUpdateDependencyInfo } from "../../actions/wizardInfoActions/updateDependencyInfo";
interface IDependencyInstalled {
installed: boolean;
}
export interface IDependenciesInstalled {
[key: string]: IDependencyInstalled;
}
export const initialState = {};
export const updateDependencyInfo = (
state: IDependenciesInstalled = initialState,
action: IUpdateDependencyInfo
) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.UPDATE_DEPENDENCY_INFO:
const newState = { ...state };
// tslint:disable-next-line: no-string-literal
newState[action.payload.dependency] = {
installed: action.payload.installed
};
return newState;
default:
return state;
}
};
export default combineReducers({
dependencies: updateDependencyInfo
});
<file_sep>/templates/Web/Pages/React.Blank/src/components/ReactBlank/index.jsx
import React from "react";
export default function Blank() {
return <main id="mainContent" />;
}
<file_sep>/src/client/src/actions/modalActions/modalActions.ts
import { MODAL_TYPEKEYS, MODAL_TYPES, ModalType } from "./typeKeys";
import { Dispatch } from "react";
import ModalActionType from "./modalActionType";
export interface IOpenModal {
type: MODAL_TYPEKEYS.OPEN_MODAL;
payload: ModalType;
}
export interface ICloseModal {
type: MODAL_TYPEKEYS.CLOSE_MODALS;
}
const openModalAction = (modal: ModalType): IOpenModal => ({
type: MODAL_TYPEKEYS.OPEN_MODAL,
payload: modal
});
const closeModalAction = (): ICloseModal => ({
type: MODAL_TYPEKEYS.CLOSE_MODALS
});
const openCosmosDbModalAction = () => {
return (dispatch: Dispatch<ModalActionType>) => {
dispatch(openModalAction(MODAL_TYPES.COSMOS_DB_MODAL));
};
};
const openAzureFunctionsModalAction = () => {
return (dispatch: Dispatch<ModalActionType>) => {
dispatch(openModalAction(MODAL_TYPES.AZURE_FUNCTIONS_MODAL));
};
};
const openPostGenModalAction = () => {
return (dispatch: Dispatch<ModalActionType>) => {
dispatch(openModalAction(MODAL_TYPES.POST_GEN_MODAL));
};
};
export {
closeModalAction,
openAzureFunctionsModalAction,
openCosmosDbModalAction,
openPostGenModalAction
};
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.Mongo/server/mongo/mongo_client.py
from pymongo import MongoClient
from .settings import *
from constants import CONSTANTS
import sys
client = MongoClient(connection_str + '?ssl=true&replicaSet=globaldb')
db = client[CONSTANTS['COSMOS']['COLLECTION']]
db.authenticate(cosmosDB_user, cosmosDB_password)
list_items = db.test<file_sep>/src/extension/src/coreTemplateStudio.ts
import fetch, { Response } from "node-fetch";
import * as signalR from "@aspnet/signalr";
import * as portfinder from "portfinder";
import * as vscode from "vscode";
import * as path from "path";
import * as os from "os";
import * as fs from "fs";
import { ChildProcess, execFile } from "child_process";
import { CONSTANTS } from "./constants";
import { GenerateCommand } from "./signalr-api-module/generateCommand";
import { SyncCommand } from "./signalr-api-module/syncCommand";
import { ICommandPayload } from "./signalr-api-module/commandPayload";
/**
* An interface for CoreTS. It should be transparent to the communication
* channel(s) between WebTS and CoreTS.
*/
export class CoreTemplateStudio {
private static _instance: CoreTemplateStudio | undefined;
private _signalRClient: signalR.HubConnection | undefined;
private _process: ChildProcess;
private _port: number;
private _url: string;
public static GetExistingInstance(): CoreTemplateStudio {
if (CoreTemplateStudio._instance) {
return CoreTemplateStudio._instance;
}
throw new Error("Cannot GetExistingInstance as none has been created");
}
public static async GetInstance(
context: vscode.ExtensionContext | undefined
): Promise<CoreTemplateStudio> {
if (CoreTemplateStudio._instance) {
return Promise.resolve(CoreTemplateStudio._instance);
}
let platform = process.platform;
let executableName = CONSTANTS.API.BASE_APPLICATION_NAME;
let extensionPath;
if (context) {
extensionPath = context.extensionPath;
} else {
extensionPath = path.join(__dirname, "..");
}
if (platform === CONSTANTS.API.WINDOWS_PLATFORM_VERSION) {
executableName += ".exe";
}
let apiPath = path.join(
extensionPath,
"src",
"api",
platform,
executableName
);
let apiWorkingDirectory = path.join(extensionPath, "src", "api", platform);
if (os.platform() !== CONSTANTS.API.WINDOWS_PLATFORM_VERSION) {
// Not unsafe as the parameter comes from trusted source
// tslint:disable-next-line:non-literal-fs-path
fs.chmodSync(apiPath, 0o755);
}
const port = await portfinder.getPortPromise({
port: CONSTANTS.START_PORT
});
let spawnedProcess = execFile(
`${apiPath}`,
[`--urls=http://localhost:${port}`],
{ cwd: apiWorkingDirectory }
);
CoreTemplateStudio._instance = new CoreTemplateStudio(
spawnedProcess,
port,
`http://localhost:${port}`
);
return CoreTemplateStudio._instance;
}
public static DestroyInstance() {
if (CoreTemplateStudio._instance) {
CoreTemplateStudio._instance.stop();
CoreTemplateStudio._instance = undefined;
}
}
private constructor(process: ChildProcess, port: number, url: string) {
this._process = process;
this._port = port;
this._url = url;
}
public getPort(): number {
return this._port;
}
public async getProjectTypes(): Promise<any> {
// TODO: use this in client instead of fetching directly from API server
const url = new URL(CONSTANTS.API.ENDPOINTS.PROJECT_TYPE, this._url);
return await fetch(url.href, { method: CONSTANTS.API.METHODS.GET })
.then((response: Response) => {
return response.json();
})
.catch((error: Error) => {
throw Error(error.toString());
});
}
public async getFrameworks(projectType: string): Promise<any> {
// TODO: use this in client instead of fetching directly from API server
const url = new URL(CONSTANTS.API.ENDPOINTS.FRAMEWORK, this._url);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.PROJECT_TYPE,
projectType
);
return await fetch(url.href, { method: CONSTANTS.API.METHODS.GET })
.then((response: Response) => {
return response.json();
})
.catch((error: Error) => {
throw Error(error.toString());
});
}
public async getFeatures(
projectType: string,
frontendFramework: string,
backendFramework: string
): Promise<any> {
// TODO: use this in client instead of fetching directly from API server
const url = new URL(CONSTANTS.API.ENDPOINTS.FEATURE, this._url);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.PROJECT_TYPE,
projectType
);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.FRONTEND_FRAMEWORK,
frontendFramework
);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.BACKEND_FRAMEWORK,
backendFramework
);
return await fetch(url.href, { method: CONSTANTS.API.METHODS.GET })
.then((response: Response) => {
return response.json();
})
.catch((error: Error) => {
throw Error(error.toString());
});
}
public async getPages(
projectType: string,
frontendFramework: string,
backendFramework: string
): Promise<any> {
// TODO: use this in client instead of fetching directly from API server
const url = new URL(CONSTANTS.API.ENDPOINTS.PAGE, this._url);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.PROJECT_TYPE,
projectType
);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.FRONTEND_FRAMEWORK,
frontendFramework
);
url.searchParams.append(
CONSTANTS.API.QUERY_PARAMS.BACKEND_FRAMEWORK,
backendFramework
);
return await fetch(url.href, { method: CONSTANTS.API.METHODS.GET })
.then((response: Response) => {
return response.json();
})
.catch((error: Error) => {
throw Error(error.toString());
});
}
public async sync(payload: ICommandPayload): Promise<any> {
let connection = await this.connectToCoreApiHub();
let command = new SyncCommand(payload);
return await command.execute(connection);
}
public async generate(payload: ICommandPayload): Promise<any> {
let connection = await this.connectToCoreApiHub();
let command = new GenerateCommand(payload);
return await command.execute(connection);
}
public stop() {
if (this._process) {
this.killProcess(this._process);
}
}
private killProcess(processToKill: ChildProcess) {
if (process.platform === CONSTANTS.API.WINDOWS_PLATFORM_VERSION) {
let pid = processToKill.pid;
let spawn = require("child_process").spawn;
spawn("taskkill", ["/pid", pid, "/f", "/t"]);
} else {
processToKill.kill("SIGKILL");
}
}
private async connectToCoreApiHub(): Promise<signalR.HubConnection> {
// Reusing connections we can save some time on handshake overhead
if (
this._signalRClient &&
this._signalRClient.state === signalR.HubConnectionState.Connected
) {
return this._signalRClient;
}
const connection = new signalR.HubConnectionBuilder()
.withUrl(`${this._url}/corehub`)
.build();
await connection.start().catch((error: Error) => console.log(error));
this._signalRClient = connection;
return connection;
}
}
<file_sep>/src/client/src/reducers/versionsReducer.ts
import { IVersions } from "../types/version";
import { WIZARD_INFO_TYPEKEYS } from "../actions/wizardInfoActions/typeKeys";
/* State Shape
{
{
templatesVersion: string,
wizardVersion: string
}
}
*/
const initialState = {
templatesVersion: "",
wizardVersion: ""
};
const versions = (state: IVersions = initialState, action: any) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.GET_VERSIONS:
return action.payload;
default:
return state;
}
};
export default versions;
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.Mongo/server/mongo/settings.py
import os
from os.path import join, dirname, realpath
from dotenv import load_dotenv
#create .env file path
dotenv_path = join(dirname(dirname(dirname(realpath(__file__)))), '.env')
#load file from path
load_dotenv(dotenv_path)
#access env file variables
connection_str = os.getenv('COSMOSDB_CONNSTR')
cosmosDB_user = os.getenv('COSMOSDB_USER')
cosmosDB_password = <PASSWORD>('COSMOSDB_PASSWORD')<file_sep>/src/extension/src/workspace/fileEvents.ts
import * as vscode from "vscode";
import EngineAPIService from "../services/engineAPIService";
import Progress from "../services/progress";
import { CoreTemplateStudio } from "../coreTemplateStudio";
import { LaunchExperience } from "../launchExperience";
export async function activateCallHomeTracking(context: vscode.ExtensionContext) {
var instance = await CoreTemplateStudio.GetInstance(context);
var port = instance.getPort();
var launchExperience = new LaunchExperience(new Progress());
await launchExperience.launchApiSyncModule(context);
var engineAPI = new EngineAPIService(port, undefined);
vscode.workspace.onDidSaveTextDocument(async (e) => {
await engineAPI.putSavedTextDocument(e.fileName + "^telerik^KENDOUIREACT^KENDOUIVUE^KENDOUIANGULAR");
})
}<file_sep>/templates/Web/Projects/FlaskDefault/README_postaction.md
## Getting Started
In the root directory of the project...
1. Install node modules `yarn install` or `npm install`.
//{[{
2. Install Python dependencies `yarn install-requirements` or `npm install-requirements`
//}]}
2. Start development server `yarn start` or `npm start`.
## File Structure
//{[{
The back-end is based on [Flask](https://github.com/pallets/flask).
//}]}
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
//{[{
├── server/ - Flask server that provides API routes and serves front-end
│ ├── constants.py - Defines the constants for the endpoints and port
│ └── server.py - Configures Port and HTTP Server and provides API routes
//}]}
└── README.md
```
## Additional Documentation
- Bootstrap CSS - https://getbootstrap.com/
//{[{
- Flask - http://flask.pocoo.org/
//}]}
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/templates/Web/Pages/Angular.MasterDetail/src/app/app-shell/Param_SourceName_Kebab/master-detail.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class MasterDetailService {
private listUrl = environment.endpoint.masterdetail;
constructor(private http: HttpClient) { }
getMasterDetailItems(): Observable<IMasterDetailText[]> {
return this.http.get<IMasterDetailText[]>(this.listUrl);
}
}
export interface IMasterDetailText {
title: string;
id: number;
status: string;
orderDate: string;
shipTo: string;
orderTotal: number;
shortDescription: string;
longDescription: string;
}
<file_sep>/src/extension/src/utils/logger.ts
import * as vscode from "vscode";
import { WizardServant, IPayloadResponse } from "../wizardServant";
import { ExtensionCommand } from "../constants";
import path = require("path");
import log4js = require("log4js");
type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
type LogSource = "WIZARD" | "EXTENSION" | "CORE";
type ILoggingPayload = {
level: LogLevel;
data: string;
};
const ABSOLUTE_LOG_PATH = path.join(__dirname, "../../logs");
const OUTPUT_CHANNEL_DEFAULT = "Kendo UI Template Wizard";
log4js.configure({
appenders: {
webtemplatestudio: {
type: "file",
filename: path.join(ABSOLUTE_LOG_PATH, "wts.log"),
pattern: ".yyyy-MM-dd",
daysToKeep: 5
}
},
categories: {
default: {
appenders: ["webtemplatestudio"],
level: "all"
}
}
});
export class Logger extends WizardServant {
clientCommandMap: Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
> = new Map([[ExtensionCommand.Log, Logger.receiveLogfromWizard]]);
public static outputChannel: vscode.OutputChannel;
private static logger: log4js.Logger = log4js.getLogger();
public static initializeOutputChannel(extensionName: string): void {
if (Logger.outputChannel === undefined) {
Logger.outputChannel = vscode.window.createOutputChannel(extensionName);
}
Logger.appendLog("EXTENSION", "info", "Launched");
}
public static appendLog(
source: LogSource,
level: LogLevel,
data: string
): void {
if (Logger.outputChannel === undefined) {
Logger.initializeOutputChannel(OUTPUT_CHANNEL_DEFAULT);
}
Logger.logger[level]("[", source, "] ", data);
Logger.outputChannel.appendLine(
"[".concat(new Date().toLocaleString(), "]", "[", source, "] ", data)
);
}
public static display(level: LogLevel): void {
if (Logger.outputChannel === undefined) {
Logger.initializeOutputChannel(OUTPUT_CHANNEL_DEFAULT);
}
Logger.outputChannel.show(true);
}
private static async receiveLogfromWizard(
message: ILoggingPayload
): Promise<IPayloadResponse> {
Logger.appendLog("WIZARD", message.level, message.data);
Logger.display(message.level);
return {
payload: null
};
}
}
<file_sep>/src/client/src/actions/vscodeApiActions/typeKeys.ts
export enum VSCODE_TYPEKEYS {
GET_VSCODE_API = "WTS/vscode/GET_VSCODE_API"
}
<file_sep>/src/client/src/actions/wizardSelectionActions/selectTheme.ts
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
import { ITheme } from "../../reducers/wizardSelectionReducers/themeReducer";
export interface ISelectThemeAction {
type: WIZARD_SELECTION_TYPEKEYS.SELECT_THEME;
payload: ITheme;
}
const selectThemeAction = (theme: ITheme): ISelectThemeAction => ({
type: WIZARD_SELECTION_TYPEKEYS.SELECT_THEME,
payload: theme
});
export { selectThemeAction };
<file_sep>/src/extension/src/services/constants.ts
export const API = {
Endpoints: {
SavedTextDocument:"/api/savedTextDocument",
},
Methods: {
GET: "get",
POST: "post"
},
};<file_sep>/src/extension/src/constants.ts
import { MessageItem } from "vscode";
import * as nls from "vscode-nls";
const localize: nls.LocalizeFunc = nls.config({
messageFormat: nls.MessageFormat.file
})();
export const CONSTANTS = {
ERRORS: {
TOO_MANY_FAILED_SYNC_REQUESTS: localize(
"error.tooManyFailedSyncRequests",
"Could not sync to template repository"
),
INVALID_COMMAND: localize("error.invalidCommand", "Invalid command used"),
INVALID_MODULE: localize("error.invalidModule", "Invalid module called"),
RESOURCE_GROUP_NOT_FOUND: localize(
"error.resourceGroupNotFound",
"No resource group found with this name"
),
SUBSCRIPTION_NOT_FOUND: localize(
"error.subscriptionNotFound",
"No subscription found with this name."
),
FUNCTION_APP_NAME_NOT_AVAILABLE: (functionName: string) => {
return localize(
"error.functionAppNameNotAvailable",
"Function app name {0} is not available",
functionName
);
},
LOGOUT_FAILED: localize(
"error.loginTimeout",
"Timeout. User is not logged in"
),
LOGIN_TIMEOUT: localize(
"error.loginTimeout",
"Timeout. User is not logged in"
),
SESSION_NOT_AVAILABLE: localize(
"error.sessionNotAvailable",
"There is no session available. Make sure the user is logged in."
),
SUBSCRIPTION_NOT_DEFINED: localize(
"error.subscriptionNotDefined",
"Subscription Item cannot have undefined values."
),
WEBSITE_CLIENT_NOT_DEFINED: localize(
"error.websiteClientNotDefined",
"Website management client cannot be undefined."
),
COSMOS_CLIENT_NOT_DEFINED: localize(
"error.cosmosClientNotDefined",
"Cosmos client cannot be undefined"
),
CONNECTION_STRING_FAILED: localize(
"error.connectionStringFailed",
"CosmosDBDeploy: GetConnectionString Failed to create Client with SubscriptionItem - "
),
RUNTIME_NOT_IMPLEMENTED: localize(
"error.runtimeNotImplemented",
"Runtime not implemented yet"
),
FUNCTIONS_NO_DUPLICATES: localize(
"error.functionsNoDuplicate",
"No duplicates allowed for function names"
),
FUNCTIONS_INVALID_NAME: (name: string) => {
return localize(
"error.functionInvalidName",
"Invalid function name {0}. Name can only include alphanumeric characters and dashes, and must start/end with alphanumeric characters",
name
);
},
EMPTY_OUTPUT_PATH: localize(
"error.emptyOutputPath",
"Output Path cannot be empty."
),
EMPTY_PROJECT_NAME: localize(
"error.emptyProjectName",
"Project Name cannot be empty."
),
PROJECT_NAME_LENGTH_EXCEEDED_MAX: localize(
"error.projectNameLengthExceededMax",
"Project Name has to be less than 50 chars long."
),
INVALID_OUTPUT_PATH: (path: string) => {
return localize(
"error.invalidOutputPath",
"Path {0} does not exist.",
path
);
},
INVALID_PROJECT_NAME: (name: string) => {
return localize(
"error.invalidProjectName",
"{0} is invalid. The project name attribute may only contain letters, numbers, and spaces",
name
);
},
PROJECT_PATH_EXISTS: (path: string, name: string) => {
return localize(
"error.projectPathExists",
"There exists a directory named {0} in the specified path '{1}', please choose a unique path",
name,
path
);
},
COSMOS_ACCOUNT_NOT_AVAILABLE: (name: string) => {
return localize(
"error.cosmosAccountNotAvailable",
'Account name "{0}" is not available.',
name
);
},
COSMOS_VALID_CHARACTERS: localize(
"error.cosmosValidCharacters",
"The name can only contain lowercase letters, numbers, and the '-' character."
),
NAME_MIN_MAX: (min: number, max: number) => {
return localize(
"error.nameMinMax",
"The name must be between {0} and {1} characters.",
min,
max
);
}
},
INFO: {
COSMOS_ACCOUNT_DEPLOYED: (accountName: string) => {
return localize(
"info.cosmosAccountDeployed",
"{0} has been deployed!",
accountName
);
},
FUNCTION_APP_DEPLOYED: (appName: string) => {
return localize(
"info.functionAppDeployed",
"Function App {0} has been deployed and is ready to use!",
appName
);
},
FILE_REPLACED_MESSAGE: localize(
"info.fileReplacedMessage",
"Replaced file at: "
),
STARTING_GENERATION_SERVER: localize(
"info.startingServerMessage",
"Starting Generation Server"
),
SYNC_STATUS: localize("info.syncStatus", "Sync Status: ")
},
API: {
WINDOWS_PLATFORM_VERSION: "win32",
BASE_APPLICATION_NAME: "CoreTemplateStudio.Api",
PRODUCTION_PATH_TO_TEMPLATES: "..",
DEVELOPMENT_PATH_TO_TEMPLATES: "../../../../..",
SYNC_LIVE_MESSAGE_TRIGGER_NAME: "syncMessage",
GEN_LIVE_MESSAGE_TRIGGER_NAME: "genMessage",
SIGNALR_API_SYNC_METHOD_NAME: "SyncTemplates",
SIGNALR_API_GENERATE_METHOD_NAME: "Generate",
MAX_SYNC_REQUEST_ATTEMPTS: 51,
SYNC_RETRY_WAIT_TIME: 250,
ENDPOINTS: {
PAGE: "/api/page",
FEATURE: "/api/feature",
FRAMEWORK: "/api/framework",
PROJECT_TYPE: "/api/projectType"
},
METHODS: {
GET: "get",
POST: "post"
},
QUERY_PARAMS: {
FRONTEND_FRAMEWORK: "frontendFramework",
BACKEND_FRAMEWORK: "backendFramework",
PROJECT_TYPE: "projectType",
PLATFORM: "platform",
PATH: "path"
}
},
AZURE_LOGIN_STATUS: {
LOGGED_IN: "LoggedIn",
LOGGING_IN: "LoggingIn",
INITIALIZING: "Initializing",
LOGGED_OUT: "LoggedOut"
},
REACT_PANEL: {
Project_Title: "Kendo UI Template Wizard"
},
GENERATE_ENDPOINT: "/api/generate",
ENGINE_DIRECTORY: "./src/api/darwin/CoreTemplateStudio.Api",
CONNECTION_STRING_MONGO: function(
username: string,
password: string,
origin: string
) {
return `COSMOSDB_CONNSTR=${origin}/${username}\nCOSMOSDB_USER=${username}\nCOSMOSDB_PASSWORD=${password}\n`;
},
CONNECTION_STRING_SQL: function(origin: string, primaryKey: string) {
return `COSMOSDB_URI=${origin}\nCOSMOSDB_PRIMARY_KEY=${primaryKey}\n`;
},
SQL_CONNECTION_STRING_PREFIX: "accountendpoint=",
MAX_PROJECT_NAME_LENGTH: 50,
START_PORT: 9502,
VSCODE_COMMAND: {
OPEN_FOLDER: "vscode.openFolder"
},
DEPENDENCY_CHECKER: {
NODE: 'node',
PYTHON: 'python',
PYTHON3: 'python3',
PYTHON_LAUNCHER: 'py -3'
}
};
export enum ExtensionCommand {
Log = "log",
Login = "login",
Logout = "logout",
Subscriptions = "subscriptions",
SubscriptionDataForCosmos = "subscription-data-for-cosmos",
SubscriptionDataForFunctions = "subscription-data-for-functions",
NameFunctions = "name-functions",
NameCosmos = "name-cosmos",
DeployFunctions = "deploy-functions",
DeployCosmos = "deploy-cosmos",
Generate = "generate",
GetOutputPath = "get-output-path",
GetFunctionsRuntimes = "get-functions-runtimes",
GetCosmosAPIs = "get-cosmos-apis",
GetUserStatus = "get-user-status",
TrackPageSwitch = "track-page-switch",
ProjectPathValidation = "project-path-validation",
UpdateGenStatusMessage = "update-status-message",
UpdateGenStatus = "update-status",
OpenProjectVSCode = "open-project-vscode",
GetVersions = "get-versions",
CloseWizard = "close-wizard",
GetPort = "get-port",
ResetPages = "reset-pages",
GetPreviewStatus = "get-preview",
CheckDependency = "check-dependency"
}
export enum ExtensionModule {
Azure = "Azure",
Generate = "GenerateExperience",
Telemetry = "Telemetry",
Validator = "Validator",
VSCodeUI = "VSCodeUI",
Logger = "Logger",
DependencyChecker = "DependencyChecker"
}
export enum TelemetryEventName {
ExtensionLaunch = "Extension-Launch-Time",
WizardSession = "Wizard-To-Generate-Session-Time",
Subscriptions = "Acquire-Subscription-Names",
SubscriptionData = "Acquire-Subscription-Data",
EngineGeneration = "Engine-Generation-Time",
CosmosDBDeploy = "Azure-Cosmos-Deployment",
FunctionsDeploy = "Azure-Functions-Deployment",
PageChange = "Wizard-Page-Change",
SyncEngine = "Sync-Engine",
ConnectionStringReplace = "Connection-String-Replaced",
PerformLogin = "Perform-Login",
PerformLogout = "Perform-Logout",
GetUserLoginStatus = "Get-User-Login-Status"
}
export namespace DialogResponses {
export const yes: MessageItem = { title: localize("dialog.yes", "Yes") };
export const no: MessageItem = { title: localize("dialog.no", "No") };
export const cancel: MessageItem = {
title: localize("dialog.cancel", "Cancel"),
isCloseAffordance: true
};
export const deleteResponse: MessageItem = {
title: localize("dialog.delete", "Delete")
};
export const learnMore: MessageItem = {
title: localize("dialog.learnMore", "Learn more")
};
export const dontWarnAgain: MessageItem = {
title: localize("dialog.dontWarnAgain", "Don't warn again")
};
export const skipForNow: MessageItem = {
title: localize("dialog.skipForNow", "Skip for now")
};
export const reportAnIssue: MessageItem = {
title: localize("dialog.reportAnIssue", "Report an issue")
};
}
export namespace DialogMessages {
export const multiLineError: string = localize(
"dialog.multilineError",
"An error has occured. Check output window for more details."
);
export const cosmosDBConnectStringReplacePrompt: string = localize(
"dialog.cosmosDBConnectStringReplacePrompt",
"Replace your DB connection string in the .env file with the generated CosmosDB connection string?"
);
export const resetPagesPrompt: string = localize(
"dialog.resetPagesPrompt",
"Switching Frameworks will reset pages in your queue. Are you sure you want to proceed?"
);
}
export enum AzureResourceType {
Cosmos = "cosmos",
Functions = "functions"
}
<file_sep>/templates/Web/Projects/KendoReactDefault/src/components/Footer.jsx
import React from 'react';
import LinkedinIcon from './img/linkedin.svg';
import TwitterIcon from './img/twitter.svg';
import FacebookIcon from './img/facebook.svg';
import YoutubeIcon from './img/youtube.svg';
const Footer = (props) => {
return (
<div className="container-fluid">
<div className='d-flex'>
<div>
<div className='mb-2 links'>
<a href="https://www.telerik.com/purchase/license-agreement/progress-kendoreact?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext">License Agreement</a>
</div>
<div className='copyright'>
Copyright © 2019 Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
</div>
</div>
<div className='d-flex ml-auto'>
<div className="social">
<a href="https://www.facebook.com/KendoUI/"><img src={FacebookIcon} alt="facebook" /></a>
<a href="https://twitter.com/kendoreact"><img src={TwitterIcon} alt="twitter" /></a>
<a href="https://www.youtube.com/results?search_query=kendoreact"><img src={YoutubeIcon} alt="youtube" /></a>
<a href="https://www.linkedin.com/showcase/telerik/"><img src={LinkedinIcon} alt="linkedin" /></a>
</div>
</div>
</div>
</div>
)
}
export default Footer;<file_sep>/src/client/src/containers/PostGenerationModal/strings.ts
import { defineMessages } from "react-intl";
export const strings = defineMessages({
failedToGenerate: {
id: "postGenerationModal.failedToGenerate",
defaultMessage: "ERROR: Templates could not be generated"
},
deploymentHalted: {
id: "postGenerationModal.deploymentHalted",
defaultMessage: "ERROR: Halted due to template error."
},
restartWizard: {
id: "postGenerationModal.restartWizard",
defaultMessage: "Restart Wizard"
},
error: {
id: "postGenerationModal.error",
defaultMessage: "ERROR:"
},
deploymentFailure: {
id: "postGenerationModal.deploymentFailure",
defaultMessage: "failed to deploy."
},
closeWizard: {
id: "postGenerationModal.closeWizard",
defaultMessage: "Close Wizard"
},
deploymentSuccess: {
id: "postGenerationModal.success",
defaultMessage: "is deployed on"
},
isDeploying: {
id: "postGenerationModal.isDeploying",
defaultMessage: "Deploying"
},
working: {
id: "postGenerationModal.working",
defaultMessage: "Working"
},
openInCode: {
id: "postGenerationModal.openInCode",
defaultMessage: "Open project in VSCode."
},
unknownStatus: {
id: "postGenerationModal.unknownStatus",
defaultMessage: "Unknown Status"
},
noServicesToDeploy: {
id: "postGenerationModal.noServicesToDeploy",
defaultMessage: "No services to deploy."
},
help: {
id: "postGenerationModal.help",
defaultMessage: "Give Feedback or Report an issue"
},
azureServices: {
id: "postGenerationModal.azureServices",
defaultMessage: "Azure Services"
},
generationStatus: {
id: "postGenerationModal.generationStatus",
defaultMessage: "Generation Status"
},
generationComplete: {
id: "postGenerationModal.generationComplete",
defaultMessage: "Generation complete."
},
templateGeneration: {
id: "postGenerationModal.templateGeneration",
defaultMessage: "Template Generation"
}
});
<file_sep>/src/client/src/actions/wizardSelectionActions/setProjectPathValidation.ts
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
export interface IProjectPathValidationAction {
type: WIZARD_SELECTION_TYPEKEYS.SET_PROJECT_PATH_VALIDATION;
payload: any; //FIXME: Type is declared in future PR in validation reducer, replace when merged
}
export const setProjectPathValidation = (
validation: any
): IProjectPathValidationAction => ({
type: WIZARD_SELECTION_TYPEKEYS.SET_PROJECT_PATH_VALIDATION,
payload: validation
});
<file_sep>/src/extension/src/types/syncReturnType.ts
export interface ISyncReturnType {
successfullySynced: boolean;
templatesVersion: string;
}
<file_sep>/src/client/src/utils/validateName.ts
import { defineMessages, FormattedMessage } from "react-intl";
const messages = defineMessages({
duplicateName: {
id: "pageNameError.duplicateName",
defaultMessage: "Name has to be unique"
},
emptyName: {
id: "pageNameError.emptyName",
defaultMessage: "Name cannot be empty"
},
invalidRegex: {
id: "pageNameError.invalidRegex",
defaultMessage:
"Name may only contain letters, numbers, spaces, dashes or underscores"
},
nameStartLetter: {
id: "pageNameError.nameStartLetter",
defaultMessage: "Name may only start with letters"
},
invalidProjectName: {
id: "projectNameError.invalidRegex",
defaultMessage:
"Name may only contain letters, numbers, dashes or underscores"
},
functionNameInvalidFirstLetter: {
id: "FunctionNameError.invalidFunctionStartLetter",
defaultMessage: "Name may only start with letters or numbers"
},
invalidFunctionName: {
id: "FunctionNameError.invalidRegex",
defaultMessage: "Name may only contain letters, numbers or dashes"
}
});
export function validateName(title: string, type: string): any {
let isValid = true;
let error: FormattedMessage.MessageDescriptor | undefined;
if (/^[ ]*$/.test(title)) {
isValid = false;
error = messages.emptyName;
}
if (type === "page") {
if (!/^[A-Za-z][A-Za-z0-9_\- ]*$/i.test(title)) {
isValid = false;
if (/^[_\-0-9 ]*$/i.test(title[0])) {
error = messages.nameStartLetter;
} else {
error = messages.invalidRegex;
}
}
} else if (type === "project") {
if (!/^[A-Za-z][A-Za-z0-9_\-]*$/i.test(title)) {
isValid = false;
if (/^[_\-0-9]*$/i.test(title[0])) {
error = messages.nameStartLetter;
} else {
error = messages.invalidProjectName;
}
}
} else if (type === "function") {
if (!/^[A-Za-z0-9][A-Za-z0-9-]*[a-zA-Z0-9]$/.test(title)) {
isValid = false;
if (/^[-]$/.test(title[0])) {
error = messages.functionNameInvalidFirstLetter;
} else {
error = messages.invalidFunctionName;
}
}
}
return {
isValid,
error
};
}
<file_sep>/templates/Web/Pages/KendoReact.Grid/src/components/Param_SourceName_Pascal.jsx
import React, { useState } from 'react';
import { sampleProducts } from '../common/sample-products';
import { MyCommandCell } from './myCommandCell.jsx';
import { Grid, GridColumn as Column, GridToolbar } from '@progress/kendo-react-grid';
import { process } from '@progress/kendo-data-query';
const Param_SourceName_Pascal = (props) => {
const editField = "inEdit";
const [data, setData] = useState(sampleProducts);
const [dataState, setDataState ] = useState({skip: 0, take: 10 })
const generateId = data => data.reduce((acc, current) => Math.max(acc, current.ProductID), 0) + 1;
const removeItem = (data, item) => {
let index = data.findIndex(p => p === item || item.ProductID && p.ProductID === item.ProductID);
if (index >= 0) {
data.splice(index, 1);
}
}
const enterEdit = (dataItem) => {
setData(data.map(item =>
item.ProductID === dataItem.ProductID ?
{ ...item, inEdit: true } : item
));
}
const remove = (dataItem) => {
const newData = [...data];
removeItem(newData, dataItem);
removeItem(sampleProducts, dataItem);
setData([...newData]);
}
const add = (dataItem) => {
dataItem.inEdit = undefined;
dataItem.ProductID = generateId(sampleProducts);
sampleProducts.unshift(dataItem);
setData([...data])
}
const discard = (dataItem) => {
const newData = [...data];
removeItem(newData, dataItem);
setData(newData);
}
const update = (dataItem) => {
const newData = [...data]
const updatedItem = { ...dataItem, inEdit: undefined };
updateItem(newData, updatedItem);
updateItem(sampleProducts, updatedItem);
setData(newData);
}
const cancel = (dataItem) => {
const originalItem = sampleProducts.find(p => p.ProductID === dataItem.ProductID);
const newData = data.map(item => item.ProductID === originalItem.ProductID ? originalItem : item);
setData(newData);
}
const updateItem = (data, item) => {
let index = data.findIndex(p => p === item || (item.ProductID && p.ProductID === item.ProductID));
if (index >= 0) {
data[index] = { ...item };
}
}
const itemChange = (event) => {
const newData = data.map(item =>
item.ProductID === event.dataItem.ProductID ?
{ ...item, [event.field]: event.value } : item
);
setData(newData);
}
const addNew = () => {
const newDataItem = { inEdit: true, Discontinued: false };
setData([newDataItem, ...data]);
}
const cancelCurrentChanges = () => {
setData([...sampleProducts]);
}
let CommandCell = MyCommandCell({
edit: enterEdit,
remove: remove,
add: add,
discard: discard,
update: update,
cancel: cancel,
editField: editField
});
const hasEditedItem = data.some(p => p.inEdit);
return (
<div className="container-fluid">
<div className='row my-4'>
<div className='col-12 col-lg-9 border-right'>
<Grid
data={process(data, dataState)}
onItemChange={itemChange}
editField={editField}
// pageable // uncomment to enable paging
// sortable // uncomment to enable sorting
// filterable // uncomment to enable filtering
// onDataStateChange={(e) => setDataState(e.data)} // uncomment to enable data operations
// {...dataState} // uncomment to enable data operations
>
<GridToolbar>
<button
title="Add new"
className="k-button k-primary"
onClick={addNew}
>
Add new
</button>
{hasEditedItem && (
<button
title="Cancel current changes"
className="k-button"
onClick={cancelCurrentChanges}
>
Cancel current changes
</button>
)}
</GridToolbar>
<Column field="ProductID" title="Id" width="50px" editable={false} />
<Column field="ProductName" title="Product Name" width="250px"/>
<Column field="UnitsInStock" title="Units" width="150px" editor="numeric" />
<Column field="Discontinued" title="Discontinued" editor="boolean" />
<Column cell={CommandCell} width="240px" />
</Grid>
</div>
<div className='col-12 col-lg-3 mt-3 mt-lg-0'>
<h3>KendoReact Grid</h3>
<p>The KendoReact Data Grid (Table) provides 100+ ready-to-use features covering everything from paging, sorting, filtering, editing, and grouping to row and column virtualization, export to PDF and Excel and accessibility.</p>
<p>For documentation and demos of all available Grid features (filtering, sorting, paging, editing etc), please visit the <a href="https://www.telerik.com/kendo-react-ui/components/grid/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext">KendoReact Grid documentation page.</a> </p>
</div>
</div>
</div>
);
}
export default Param_SourceName_Pascal;<file_sep>/src/client/src/reducers/wizardSelectionReducers/validateProjectPath.ts
import { WIZARD_SELECTION_TYPEKEYS } from "../../actions/wizardSelectionActions/typeKeys";
import WizardSelectionActionType from "../../actions/wizardSelectionActions/wizardSelectionActionType";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
/* State Shape
{
projectPathValidation: {
isInvalidProjectPath: boolean,
projectPathError: string
}
}
*/
interface IProjectPathValidation {
isInvalidProjectPath?: boolean;
projectPathError?: string;
}
const initialState = {};
const projectPathValidation = (
state: IProjectPathValidation = initialState,
action: WizardSelectionActionType | WizardInfoType
) => {
switch (action.type) {
case WIZARD_SELECTION_TYPEKEYS.SET_PROJECT_PATH_VALIDATION:
return action.payload;
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return initialState;
default:
return state;
}
};
export default projectPathValidation;
<file_sep>/src/client/src/actions/wizardInfoActions/setDetailsPage.ts
import { IOption } from "../../types/option";
import { WIZARD_INFO_TYPEKEYS } from "./typeKeys";
export interface IDetail {
data: IOption;
isIntlFormatted: boolean;
}
export interface ISetDetails {
type: WIZARD_INFO_TYPEKEYS.SET_DETAILS_PAGE_INFO;
payload: IDetail;
}
export const setDetailPageAction = (
detailPageInfo: IOption,
isIntlFormatted: boolean = false
): ISetDetails => ({
type: WIZARD_INFO_TYPEKEYS.SET_DETAILS_PAGE_INFO,
payload: {
data: detailPageInfo,
isIntlFormatted
}
});
<file_sep>/src/extension/src/azure/azure-functions/functionProvider.ts
import { ValidationHelper, FileHelper } from "./utils";
import { ServiceClientCredentials } from "ms-rest";
import { WebSiteManagementClient } from "azure-arm-website";
import {
FileError,
DeploymentError,
AuthorizationError,
SubscriptionError
} from "../../errors";
import { SubscriptionItem, ResourceGroupItem } from "../azure-auth/azureAuth";
import { ZipDeployHelper } from "./utils/zipDeployHelper";
import * as fs from "fs";
import * as path from "path";
import {
ResourceManagementClient,
ResourceManagementModels
} from "azure-arm-resource/lib/resource/resourceManagementClient";
import { ResourceManager } from "../azure-arm/resourceManager";
import * as appRoot from "app-root-path";
import { ARMFileHelper } from "../azure-arm/armFileHelper";
import { CONSTANTS } from "../../constants";
import { FunctionValidationResult } from "./utils/validationHelper";
/*
* Runtime for the deployment, can be either 'dotnet' or 'node'.
*/
export type Runtime = "dotnet" | "node";
/*
* Implemented runtime selections
* value: the runtime which should be returned as selection
* label: String to display to user
*/
export interface RuntimeObject {
value: Runtime;
label: string;
}
const FUNCTION_APP_DOMAIN = ".azurewebsites.net";
const MAX_STORAGE_NAME = 24;
const FUNCTIONS_DEPLOYMENT_SUFFIX = "-functions";
/*
* Returns an array of available/implemented RuntimeObjects for functions app
*/
export function GetAvailableRuntimes(): RuntimeObject[] {
return [
{
value: "node",
label: "JavaScript"
}
];
}
/*
* User selections from the wizard
*
* functionAppName: Globally unique app name for your function. Use checkFunctionAppName to validate
* subscriptionItem: Subscription Item for user's selected subscription
* resourceGroupItem ResourceGroupItem for user's selected resource group
* location: Location for deployment, can be West US/East US/China North/East Asia etc.
* The location is in same format as found on Azure portal
* runtime: Runtime for the deployment, can be either 'dotnet' or 'node'. Throws validation error otherwise.
* Note: 'dotnet' isn't supported yet!
* functionNames: Names of all the functions created by user, can only include alphanumeric characters and dashes.
* No duplicates allowed!
*
*
* Format:
* {
* functionAppName: "YOUR_FUNCTION_APP_NAME",
* subscriptionItem: {label: , subscriptionId: , session: , subscription: },
* location: "West US",
* runtime: "node",
* resourceGroupItem: {location: , name: resourceGroup: },
* functionNames: ["function1", "function2", "function3"]
* },
*/
export interface FunctionSelections {
functionAppName: string;
subscriptionItem: SubscriptionItem;
resourceGroupItem: ResourceGroupItem;
location: string;
runtime: Runtime;
functionNames: string[];
}
export class FunctionProvider {
private webClient: WebSiteManagementClient | undefined;
/*
* Create and deploy a function app from the given user selections.
* Validates the user selections
* Throws ValidationError if user input is invalid.
* Throws AuthorizationError if authorization fails.
* Throws DeploymentError if deployment fails.
*
* @param selections The user selection object (FunctionSelections)
*
* @param appPath The path to original app being created by Web Template Studio
* The function app folder would be added under this
*
* @returns Promise<void> Throws a void promise, catch errors as required
*/
public async createFunctionApp(
selections: FunctionSelections,
appPath: string
): Promise<void> {
try {
this.setWebClient(selections.subscriptionItem);
} catch (error) {
throw new AuthorizationError(error.message);
}
try {
FileHelper.initFunctionDirectory(
appPath,
selections.functionAppName,
selections.functionNames,
selections.runtime
);
} catch (error) {
throw new FileError(error.message);
}
let template = this.getFunctionsARMTemplate();
let parameters = this.getFunctionsARMParameters(selections);
let deploymentParams = parameters.parameters;
try {
var options: ResourceManagementModels.Deployment = {
properties: {
mode: "Incremental",
parameters: deploymentParams,
template: template
}
};
let azureResourceClient: ResourceManagementClient = new ResourceManager().getResourceManagementClient(
selections.subscriptionItem
);
/*
* Azure Resource Client to generate a function app using resource group name, function app name, and options
*/
await azureResourceClient.deployments
.createOrUpdate(
selections.resourceGroupItem.name,
selections.functionAppName + FUNCTIONS_DEPLOYMENT_SUFFIX,
options
)
.then(async result => {
this.writeARMTemplatesToApp(appPath, template, parameters);
await ZipDeployHelper.zipDeploy(
selections.subscriptionItem.session.credentials,
appPath,
selections.functionAppName
);
return result;
});
} catch (error) {
throw new DeploymentError(error.message);
}
try {
FileHelper.deleteTempZip(appPath);
} catch (error) {
throw new FileError(error.message);
}
/*
* restarts the app to load new deployment
*/
await this.webClient!.webApps.restart(
selections.resourceGroupItem.name,
selections.functionAppName
);
}
private convertAppNameToStorageName(appName: string): string {
return (
appName
.toLowerCase()
.replace(/[^0-9a-z]/gi, "")
.substring(0, MAX_STORAGE_NAME - 4) +
Math.random()
.toString(36)
.slice(-4)
);
}
/*
* gets ARM template for Azure Functions
*/
private getFunctionsARMTemplate(): any {
let templatePath = path.join(
appRoot.toString(),
"src",
"azure",
"azure-functions",
"arm-templates",
"template.json"
);
return JSON.parse(fs.readFileSync(templatePath, "utf8"));
}
/*
* sets and returns ARM templates parameters with user selections
*/
private getFunctionsARMParameters(selections: FunctionSelections): any {
let parametersPath = path.join(
appRoot.toString(),
"src",
"azure",
"azure-functions",
"arm-templates",
"parameters.json"
);
let parameters = JSON.parse(fs.readFileSync(parametersPath, "utf8"));
parameters.parameters = {
name: {
value: selections.functionAppName
},
location: {
value: selections.location
},
runtime: {
value: selections.runtime
},
subscriptionId: {
value: selections.subscriptionItem.subscriptionId
},
storageName: {
value: this.convertAppNameToStorageName(selections.functionAppName)
}
};
return parameters;
}
private writeARMTemplatesToApp(
appPath: string,
template: any,
parameters: any
) {
ARMFileHelper.creatDirIfNonExistent(path.join(appPath, "arm-templates"));
ARMFileHelper.writeObjectToJsonFile(
path.join(appPath, "arm-templates", "functions-template.json"),
template
);
ARMFileHelper.writeObjectToJsonFile(
path.join(appPath, "arm-templates", "functions-parameters.json"),
parameters
);
}
/*
* Sets a web client from a users selected subscription item's credentials
*/
private setWebClient(userSubscriptionItem: SubscriptionItem): void {
if (
this.webClient === undefined ||
this.webClient.subscriptionId !== userSubscriptionItem.subscriptionId
) {
this.webClient = this.createWebClient(userSubscriptionItem);
}
}
private createWebClient(
userSubscriptionItem: SubscriptionItem
): WebSiteManagementClient {
let credentials: ServiceClientCredentials =
userSubscriptionItem.session.credentials;
if (
userSubscriptionItem === undefined ||
userSubscriptionItem.subscription === undefined ||
userSubscriptionItem.subscriptionId === undefined
) {
throw new SubscriptionError(CONSTANTS.ERRORS.SUBSCRIPTION_NOT_DEFINED);
}
return new WebSiteManagementClient(
credentials,
userSubscriptionItem.subscriptionId
);
}
/*
* Check if a function app name is available
*
* @param appName function app name to check uniqueness/availability for
*
* @param subscriptionItem Subscription Item for user's selected subscription/random subscription for user
*
* @returns Promise<string | undefined> Returns an error message if function name is invalid or not
* available. Returns undefined otherwise
*
*/
public async checkFunctionAppName(
appName: string,
subscriptionItem: SubscriptionItem
): Promise<string | undefined> {
try {
this.setWebClient(subscriptionItem);
} catch (error) {
return error.message;
}
let validationStatus: FunctionValidationResult = ValidationHelper.validateFunctionAppName(
appName
);
if (!validationStatus.isValid) {
return validationStatus.message;
}
if (this.webClient === undefined) {
return CONSTANTS.ERRORS.WEBSITE_CLIENT_NOT_DEFINED;
}
return await this.webClient
.checkNameAvailability(appName + FUNCTION_APP_DOMAIN, "Site", {
isFqdn: true
})
.then(res => {
if (res.nameAvailable) {
return undefined;
} else {
return CONSTANTS.ERRORS.FUNCTION_APP_NAME_NOT_AVAILABLE(appName);
}
})
.catch(error => {
return error.message;
});
}
}
<file_sep>/src/client/src/mockData/logout.ts
interface ILogOutResponse {
status: string;
body: string;
}
const logOutOfAzure = (): Promise<ILogOutResponse> => {
return Promise.resolve({
status: "200 OK",
body: "success"
});
};
export default logOutOfAzure;
<file_sep>/templates/Web/Pages/Angular.List/src/app/app-shell/Param_SourceName_Kebab/list-item/list-item.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-list-item',
templateUrl: './list-item.component.html',
styleUrls: ['./list-item.component.css']
})
export class ListItemComponent implements OnInit {
// tslint:disable-next-line
@Input() _id: number;
@Input() text: string;
@Output() deleteText = new EventEmitter<number>();
constructor() { }
ngOnInit() {
}
onDeleteListItem() {
this.deleteText.emit(this._id);
}
}
<file_sep>/src/extension/src/azure/azure-functions/utils/zipDeployHelper.ts
import { ServiceClientCredentials } from "ms-rest";
import * as path from "path";
import * as fs from "fs";
import * as request from "request";
export namespace ZipDeployHelper {
const FUNCTION_ZIP_DEPLOY_DOMAIN = ".scm.azurewebsites.net/api/zipdeploy";
export async function zipDeploy(
credentials: ServiceClientCredentials,
appPath: string,
appName: string
): Promise<void> {
const zipPath = path.join(appPath, "tmp", "out.zip");
const zipRequestUrl = `https://${appName.toLowerCase()}${FUNCTION_ZIP_DEPLOY_DOMAIN}`;
let tokenCache = await (<any>credentials).tokenCache;
const options = {
url: zipRequestUrl,
headers: {
Authorization: "Bearer " + tokenCache.target._entries[0].accessToken,
Accept: "*/*"
}
};
await fs.createReadStream(zipPath).pipe(
request.post(options, (uploadZipError: any, uploadZipResponse: any) => {
if (uploadZipError) {
throw uploadZipError;
} else {
return uploadZipResponse;
}
})
);
}
}
<file_sep>/src/client/src/reducers/azureLoginReducers/azureProfileReducer.ts
import { AZURE_TYPEKEYS } from "../../actions/azureActions/typeKeys";
import AzureActionType from "../../actions/azureActions/azureActionType";
/* State Shape
{
profileData: {}
}
*/
interface IAzureProfile {
email: string | undefined;
subscriptions: any;
}
const initialState = {
email: undefined,
subscriptions: {}
};
const profileData = (
state: IAzureProfile = initialState,
action: AzureActionType
) => {
switch (action.type) {
case AZURE_TYPEKEYS.LOG_OUT_OF_AZURE:
return initialState;
case AZURE_TYPEKEYS.LOG_IN_TO_AZURE:
const newState = {
...state,
email: action.payload.email,
subscriptions: action.payload.subscriptions
};
return newState;
default:
return state;
}
};
export default profileData;
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.Mongo/server/mongo/utils.py
from bson import ObjectId
def serialize(items):
for index in items:
if isinstance(items[index], ObjectId):
items[index] = str(items[index])
return items<file_sep>/src/client/src/reducers/modalReducers/modalReducer.ts
import { AZURE_TYPEKEYS } from "../../actions/azureActions/typeKeys";
import { MODAL_TYPEKEYS, ModalType } from "../../actions/modalActions/typeKeys";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import RootAction from "../../actions/ActionType";
const openModal = (state: ModalType = null, action: RootAction) => {
switch (action.type) {
case MODAL_TYPEKEYS.OPEN_MODAL:
return action.payload;
case AZURE_TYPEKEYS.SAVE_AZURE_FUNCTIONS_SETTINGS:
case AZURE_TYPEKEYS.SAVE_COSMOS_DB_RESOURCE_SETTINGS:
case MODAL_TYPEKEYS.CLOSE_MODALS:
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return null;
default:
return state;
}
};
export { openModal };
<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.SQL/server/requirements_postaction.txt
//{[{
azure-cosmos==3.1.0
python-dotenv==0.10.3
//}]}
flask==1.0.3<file_sep>/src/client/src/reducers/azureLoginReducers/isLoggedInReducer.ts
import { AZURE_TYPEKEYS } from "../../actions/azureActions/typeKeys";
import AzureActionType from "../../actions/azureActions/azureActionType";
/* State Shape
{
isLoggedIn: boolean
}
*/
const profileData = (state: boolean = false, action: AzureActionType) => {
switch (action.type) {
case AZURE_TYPEKEYS.LOG_OUT_OF_AZURE:
return false;
case AZURE_TYPEKEYS.LOG_IN_TO_AZURE:
return true;
case AZURE_TYPEKEYS.IS_LOGGED_IN_TO_AZURE:
default:
return state;
}
};
export default profileData;
<file_sep>/src/client/src/selectors/modalSelector.ts
import { createSelector } from "reselect";
import { AppState } from "../reducers";
import { ModalType, MODAL_TYPES } from "../actions/modalActions/typeKeys";
const getOpenModal = (state: AppState): ModalType => state.modals.openModal;
const isCosmosDbModalOpen = (modal: ModalType): boolean =>
modal === MODAL_TYPES.COSMOS_DB_MODAL;
const isAzureFunctionsModalOpen = (modal: ModalType): boolean =>
modal === MODAL_TYPES.AZURE_FUNCTIONS_MODAL;
const isPostGenModalOpen = (modal: ModalType): boolean =>
modal === MODAL_TYPES.POST_GEN_MODAL;
const isCosmosDbModalOpenSelector = createSelector(
getOpenModal,
isCosmosDbModalOpen
);
const isAzureFunctionsModalOpenSelector = createSelector(
getOpenModal,
isAzureFunctionsModalOpen
);
const isPostGenModalOpenSelector = createSelector(
getOpenModal,
isPostGenModalOpen
);
export {
isAzureFunctionsModalOpenSelector,
isCosmosDbModalOpenSelector,
isPostGenModalOpenSelector
};
<file_sep>/templates/Web/Pages/KendoReact.Form/src/components/Param_SourceName_Pascal.jsx
import React, { useState } from 'react';
import { Input, Checkbox } from '@progress/kendo-react-inputs';
import { DatePicker } from '@progress/kendo-react-dateinputs';
import { Form, Field } from '@progress/kendo-react-form';
import { Dialog, DialogActionsBar } from '@progress/kendo-react-dialogs';
import FormContainer from './FormContainer';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);
const emailValidator = (value) => (emailRegex.test(value) ? "" : "Please enter a valid email.");
const EmailInput = (fieldRenderProps) => {
const { validationMessage, visited, ...others } = fieldRenderProps;
return (
<div>
<Input {...others} />
{
visited && validationMessage &&
(<div className={"k-required"}>{validationMessage}</div>)
}
</div>
);
};
const Param_SourceName_Pascal = (props) => {
const initialForm = {
firstName: '',
lastName: '',
dateOfBirth: new Date(),
email: '',
company: '',
userName: '',
password: '',
twoFactor: false
};
const [showDialog, setShowDialog] = useState(false)
const toggleDialog = () => {
setShowDialog(!showDialog);
}
const handleSubmit = () => {
setShowDialog(!showDialog);
}
return (
<div className="container-fluid">
{showDialog && <Dialog onClose={toggleDialog}>
<p style={{ margin: "25px", textAlign: "center" }}>The form is successfully submitted!</p>
<DialogActionsBar>
<button className="k-button" onClick={toggleDialog}>OK</button>
</DialogActionsBar>
</Dialog>}
<div className='row my-4'>
<FormContainer>
<Form
initialValues={initialForm}
onSubmit={handleSubmit}
render={(formRenderProps) => (
<form onSubmit={formRenderProps.onSubmit} className={'k-form'}>
<fieldset>
<legend>User Details</legend>
<div>
<Field name={'firstName'} component={Input} label={'First name'} />
</div>
<div>
<Field name={'lastName'} component={Input} label={'Last name'} />
</div>
<div style={{ marginTop: "1rem" }}>
<Field name={'dateOfBirth'} component={DatePicker} label={'Date of Birth'} />
</div>
<div>
<Field name={"email"} type={"email"} component={EmailInput} label={"Email"} validator={emailValidator} />
</div>
<div>
<Field name={'company'} component={Input} label={'Your Company'} />
</div>
</fieldset>
<fieldset>
<legend>Credentials</legend>
<div>
<Field name={'userName'} component={Input} label={'Username'} placeholder="Your username" />
</div>
<div>
<Field name={'<PASSWORD>'} component={Input} label={'<PASSWORD>'} placeholder="<PASSWORD>" />
</div>
<div style={{ marginTop: "1rem" }}>
<Field name={'twoFactor'} component={Checkbox} label={'Enable two-factor authentication'} />
</div>
</fieldset>
<div className="text-right">
<button type="button" className="k-button" onClick={formRenderProps.onFormReset}>Clear</button>
<button type="submit" className="k-button k-primary" disabled={!formRenderProps.allowSubmit}>Submit</button>
</div>
</form>
)} />
</FormContainer>
<div className='col-12 col-lg-3 mt-3 mt-lg-0'>
<h3>KendoReact Forms</h3>
<p>KendoReact includes a wide offering of UI components that can be used to build forms, including CSS classes to easily create and structure gorgeous forms.</p>
<p>The required inputs get validated upon form submission and if the validation fails, the form submission is prevented. Out of the box, KendoReact delivers components which support the HTML5 form validation and also provide props for configuring a set of minimal requirements for a component to be in a valid state.</p>
<p>For documentation and demos of the many form-friendly components please visit their documentation (<a href="https://www.telerik.com/kendo-react-ui/components/dateinputs/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext"> Date Inputs</a>, <a href="https://www.telerik.com/kendo-react-ui/components/dropdowns/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext"> DropDowns</a>, <a href="https://www.telerik.com/kendo-react-ui/components/inputs/?utm_medium=product&utm_source=vs&utm_campaign=kendo-ui-react-branding-vs-ext">Inputs</a> etc).</p>
</div>
</div>
</div>
)
}
export default Param_SourceName_Pascal;<file_sep>/templates/Web/_composition/Flask/Feature.Flask.Azure.Cosmos.SQL/server/sql/sql_service.py
from flask import jsonify, make_response, request
from .sql_client import SQLObj
sql_database_obj = SQLObj()
def get():
query_str = {
'query': "SELECT r.id as _id, r.text FROM root r ORDER BY r._ts DESC"}
options = {}
options['enableCrossPartitionQuery'] = True
options['maxItemCount'] = 2
results_iterable = sql_database_obj.get_client().QueryItems(
sql_database_obj.get_container()['_self'], query_str, options)
return jsonify(
list(results_iterable)
)
def create():
data = request.get_json()
list_item = {'text': data['text']}
created = sql_database_obj.get_client().CreateItem(
sql_database_obj.get_container()['_self'], list_item)
return make_response(
jsonify(
{'_id': created['id'], 'text': list_item['text']}
),
201
)
def destroy(id):
# use parameterized queries to avoid SQL injection attacks
findStr = "SELECT * FROM c where c.id = @id"
query_str = {
'query': findStr,
'parameters': [
{'name': '@id', 'value': id}
]
}
result = sql_database_obj.get_client().QueryItems(
sql_database_obj.get_container()['_self'], query_str)
count = sum(1 for _ in iter(result))
if count == 0:
return make_response(
jsonify(
{'error': 'Could not find an item with given id'}
),
404
)
for item in iter(result):
sql_database_obj.get_client().DeleteItem(item['_self'])
return jsonify(
{'_id': id, 'text': 'This comment was deleted'}
)<file_sep>/src/client/src/actions/wizardContentActions/getPagesOptions.ts
import EngineAPIService from "../../services/EngineAPIService";
import { IApiTemplateInfo } from "../../types/apiTemplateInfo";
import { IOption } from "../../types/option";
import getSvgUrl from "../../utils/getSvgUrl";
import { WIZARD_CONTENT_TYPEKEYS } from "./typeKeys";
import WizardContentActionType from "./wizardContentActionType";
import { Dispatch } from "react";
export interface IPageOptionsActionType {
type: WIZARD_CONTENT_TYPEKEYS.GET_PAGES_OPTIONS_SUCCESS;
payload: IOption[];
}
const getPagesOptionsAction = (
projectType: string,
frontendFramework: string,
backendFramework: string,
serverPort: number
) => {
return async (dispatch: Dispatch<WizardContentActionType>) => {
const api = new EngineAPIService(serverPort, undefined);
try {
const pagesJson = await api.getPages(
projectType,
frontendFramework,
backendFramework
);
if (pagesJson.detail == null) {
dispatch(
getPagesOptionsSuccess(
getOptionalFromApiTemplateInfo(
getApiTemplateInfoFromJson(pagesJson)
)
)
);
} else {
console.log("FAILED");
}
} catch (error) {
console.log(error);
}
};
};
const getPagesOptionsSuccess = (
pagesOptions: IOption[]
): IPageOptionsActionType => ({
payload: pagesOptions,
type: WIZARD_CONTENT_TYPEKEYS.GET_PAGES_OPTIONS_SUCCESS
});
function getApiTemplateInfoFromJson(items: any[]): IApiTemplateInfo[] {
return items.map<IApiTemplateInfo>(val => ({
displayName: val.name,
licenses: val.licenses,
longDescription: val.richDescription,
name: val.templateId,
position: val.displayOrder,
selected: false,
summary: val.description,
svgUrl: val.icon,
tags: val.tags,
defaultName: val.defaultName,
author: val.author
}));
}
function getOptionalFromApiTemplateInfo(items: IApiTemplateInfo[]): IOption[] {
return items.map<IOption>(val => ({
body: val.summary,
internalName: val.name,
licenses: val.licenses,
position: val.position,
longDescription: val.longDescription,
selected: val.selected,
svgUrl: getSvgUrl(val.name),
title: val.displayName,
defaultName: val.defaultName,
isValidTitle: true,
author: val.author
})).sort((a,b) => (a.position || 0) - (b.position || 0));
}
export { getPagesOptionsAction, getPagesOptionsSuccess };
<file_sep>/templates/Web/_composition/KendoReact/Page.Kendo.React.AddFormContainer/src/components/FormContainer.jsx
import React from 'react';
const FormContainer = (props) => {
return (
<div className='col-12 col-lg-9 border-right'>
<div className="row example-wrapper">
<div className="col-xs-12 col-sm-6 offset-sm-3 example-col">
<div className="card-block">
{props.children}
</div>
</div>
</div>
</div>
);
}
export default FormContainer;<file_sep>/src/client/src/reducers/wizardRoutes/navigationReducer.ts
import { ROUTES } from "../../utils/constants";
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
export interface IRoutes {
[key: string]: boolean;
}
const initialState = {
[ROUTES.NEW_PROJECT]: true,
[ROUTES.SELECT_FRAMEWORKS]: false,
[ROUTES.SELECT_PAGES]: false,
[ROUTES.REVIEW_AND_GENERATE]: false
};
const wizardNavigation = (
state: IRoutes = initialState,
action: WizardInfoType
) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.SET_VISITED_WIZARD_PAGE:
const newSelectionState = {
...state,
[action.payload]: true
};
return newSelectionState;
case WIZARD_INFO_TYPEKEYS.RESET_WIZARD:
return initialState;
default:
return state;
}
};
export const selected = (
state = "/",
action: WizardInfoType
) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.SET_PAGE_WIZARD_PAGE:
return action.payload;
default:
return state;
}
};
export const isVisited = (
state: IRoutes = initialState,
action: WizardInfoType
) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.SET_VISITED_WIZARD_PAGE:
const newSelectionState = {
...state,
[action.payload]: true
};
return newSelectionState;
case WIZARD_INFO_TYPEKEYS.RESET_VISITED_WIZARD_PAGE:
return initialState;
default:
return state;
}
};
export default wizardNavigation;
<file_sep>/src/extension/src/azure/azure-functions/utils/fileHelper.ts
import * as fs from "fs";
import * as fsx from "fs-extra";
import * as path from "path";
import * as appRoot from "app-root-path";
import * as archiver from "archiver";
import { Runtime } from "../functionProvider";
import * as rimraf from "rimraf";
import { CONSTANTS } from "../../../constants";
export namespace FileHelper {
const FUNCTION_TEMPLATES_RELATIVE_PATH =
"/src/azure/azure-functions/templates";
const BASE_NODE_FUNCTION_PATH = "/base/node/index.js";
const BASE_NODE_FUNCTION_CONFIG_PATH = "/base/node/function.json";
const APP_NODE_SETTINGS_PATH = "/app/node";
export function initFunctionDirectory(
basePath: string,
appName: string,
functionNames: string[],
runtime: Runtime
): void {
let funcAppPath: string = path.join(basePath, appName);
createFolder(funcAppPath);
for (let i = 0; i < functionNames.length; i++) {
switch (runtime) {
case "node":
createFolderForNode(path.join(funcAppPath, functionNames[i]));
break;
case "dotnet":
throw new Error(CONSTANTS.ERRORS.RUNTIME_NOT_IMPLEMENTED);
}
}
copySettingsFiles(funcAppPath);
createTempZip(basePath, appName);
}
function copySettingsFiles(funcAppPath: string) {
let appSettingsPath: string = path.join(
appRoot.toString(),
FUNCTION_TEMPLATES_RELATIVE_PATH,
APP_NODE_SETTINGS_PATH
);
fsx.copySync(appSettingsPath, funcAppPath);
}
function createFolderForNode(dirPath: string): void {
createFolder(dirPath);
let indexPath: string = path.join(
appRoot.toString(),
FUNCTION_TEMPLATES_RELATIVE_PATH,
BASE_NODE_FUNCTION_PATH
);
let funcJsonPath: string = path.join(
appRoot.toString(),
FUNCTION_TEMPLATES_RELATIVE_PATH,
BASE_NODE_FUNCTION_CONFIG_PATH
);
fs.copyFileSync(indexPath, path.join(dirPath, "index.js"));
fs.copyFileSync(funcJsonPath, path.join(dirPath, "function.json"));
}
function createFolder(dirPath: string): void {
if (fsx.pathExistsSync(dirPath)) {
fsx.removeSync(dirPath);
}
fsx.mkdirpSync(dirPath);
}
function createTempZip(basePath: string, funcAppName: string): void {
fsx.mkdirpSync(path.join(basePath, "tmp"));
let zipPath: string = path.join(basePath, "tmp", "out.zip");
const output = fs.createWriteStream(zipPath);
var archive = archiver("zip", {
zlib: { level: 9 } // Sets the compression level.
});
output.on("error", function(error: any) {
throw error;
});
archive.on("error", function(error: any) {
throw error;
});
archive.pipe(output);
archive.directory(path.join(basePath, funcAppName), false);
archive.finalize();
}
export function deleteTempZip(basePath: string): void {
fsx.removeSync(path.join(basePath, "tmp"));
rimraf(path.join(basePath, "tmp"), () => {});
}
}
<file_sep>/src/extension/src/telemetry/telemetryReporterMock.ts
export class TelemetryReporterMock {
constructor(extensionName?: string, extensionVersion?: any, aiKey?: string){
}
updateUserOptIn = function (key?: string) {
};
createAppInsightsClient = function (key?: string) {
};
getCommonProperties = function () {
};
sendTelemetryEvent = function (eventName?: string, properties?: any, measurements?: any) {
};
dispose = function () {
};
TELEMETRY_CONFIG_ID = 'telemetry';
TELEMETRY_CONFIG_ENABLED_ID = 'enableTelemetry';
};
<file_sep>/src/extension/LICENSE.md
End User License Agreement for Progress Kendo UI Template Wizard for Visual Studio Code
(Last Updated January 9, 2020)
The Software is being made available by Progress Software Corporation (“Progress,” “Licensor”, “we,” “us,” or “our”) to You on the condition that You agree to these terms and conditions (the “Agreement”). “Licensee,” “You,” or “Your” refers to the person accessing or using the Software, or, if the Software is being used on behalf of an organization, such as an employer, “Licensee,” "You," or “Your” means such organization. In the latter case, the person accessing or using the Software represents and warrants that he or she has the authority to do so and bind such organization to this Agreement. Violation of any of the terms below will result in the termination of this Agreement. BY DOWNLOADING, INSTALLING OR OTHERWISE USING THE SOFTWARE MADE AVAILABLE BY PROGRESS THROUGH THE VISUAL STUDIO MARKETPLACE (https://marketplace.visualstudio.com/),, YOU ACKNOWLEDGE THAT YOU HAVE REVIEWED AND THAT YOU ACCEPT THESE TERMS AND ARE AUTHORIZED TO ACT ON BEHALF OF, AND BIND TO THIS AGREEMENT, THE COMPANY ON BEHALF OF WHICH YOU ENTER IN THIS AGREEMENT. IF YOU DO NOT HAVE SUCH AUTHORITY, OR IF YOU DO NOT AGREE WITH THESE TERMS, YOU MUST NOT DOWNLOAD, INSTALL OR USE THE SOFTWARE.
Content Management System and/or component vendors are not allowed to use the Software (as defined below) without the express permission of Progress. If You or the company You represent is a Content Management System and/or component vendor, You may not purchase a license for or use the Software unless You contact Progress directly and obtain permission.
This is a license agreement and not an agreement for sale.
1. Definitions For purposes of this Agreement:
“Integrated Products” means Your proprietary software applications which: (i) are developed by Your Licensed Developers; (ii) add substantial functionality beyond the functionality provided by the incorporated components of the Programs; and (iii) are not commercial alternatives for, or competitive in the marketplace with, the Programs or any components of the Programs.
“Licensed Developers” means Your employees or third-party contractors authorized to develop software specifically for You using the Software in accordance with this Agreement.
2. Software License
2.1 This Software (as defined below) is an extension or template for certain separately licensed Progress Products. The Software is licensed to You for use with validly licensed Progress Products only. This Agreement does not grant You a license or any rights to use or distribute such Progress Products. To obtain more information about Progress Products and/or to obtain a license for one or more Progress Products please visit www.progress.com or www.telerik.com.
You are granted the following limited license rights while You maintain, and are in compliance with the terms of, a valid license to one or more Progress Product(s).
License Grant. Subject to the terms and conditions set forth in this Agreement, Progress hereby grants to Licensee and Licensee hereby accepts, a limited, non-transferable, perpetual, sublicenseable (solely as set forth in Section 2.3), non-exclusive license (the “License”) to use the Progress computer software identified as Progress Kendo UI Template Wizard and any updates, upgrades, modifications and error corrections thereto provided to Licensee (the “Programs”) and any accompanying documentation (the “Documentation”, together with the Programs, collectively the “Software”) solely as specified in this Agreement. You are granted a Developer License pursuant to Section 2.4.
2.2 Scope of Use. The Software is licensed, not sold, on a per-seat basis. The number of Licensed Developers using the Software must correspond to the maximum number of License seats You have obtained from Progress hereunder. This means that, at any given time, the number of Licensed Developers cannot exceed the number of License seats that You have obtained from Progress and for which You have paid Progress any applicable License Fees pursuant to this Agreement. The Software is in “use” on a computer when it is loaded into temporary memory (i.e. RAM) or installed into permanent memory (e.g. hard disk or other storage device). Your Licensed Developers may install the Software on multiple machines, so long as the Software is not being used simultaneously for development purposes at any given time by more Licensed Developers than You have License seats. You are not limited by the number of License seats with respect to how many individuals within Your organization may access and use the Software for testing and building purposes. You may also embed copies of the Programs in Your Integrated Products that You license and distribute to Your own end-user licensees, including but not limited to, Your employees (“Authorized End-Users”), solely in accordance with the requirements set forth in Section 2.3 below.
2.3 License for Redistribution
2.3.1 License Grant. Subject to the terms of this Agreement, You are granted a limited, nontransferable, royalty-free license to redistribute and sublicense the use of the Programs solely to Authorized End-Users: (i) in object code form only; (ii) as embedded within Your Integrated Product for internal company use, hosted applications, websites, commercial solutions deployed at Your Authorized End Users sites, or shrink- or click-wrapped software solutions; and (iii) pursuant to an end user license agreement or terms of use that: imposes the limitations set forth in this paragraph on Your Authorized End-Users; prohibits distribution of the Programs by Your Authorized End-Users; limits the liability of Your licensors or suppliers to the maximum extent permitted by applicable law; and prohibits any attempt to disassemble the code, or attempt in any manner to reconstruct, discover, reuse or modify any source code or underlying algorithms of the Programs, except to the limited extent as is permitted by law notwithstanding contractual prohibition. Notwithstanding subsection 2.3.1(iii), if Your Integrated Product is only distributed to Your employees for internal use, You are not required to distribute Your Integrated Product pursuant to an end user license agreement or terms of use. In no event are You allowed to distribute the Software or sublicense its use (a) in any format other than in object form, (b) as a standalone product or (c) as a part of any product other than Your Integrated Product.
2.3.2 The foregoing license to redistribute the Programs is conditioned upon the following:
2.3.2.1 You hereby acknowledge and agree that You are solely responsible for Your Authorized End-User’s use of the Programs in accordance with the limitations set forth in subsection 2.3.1 and liable for such Authorized End-User’s breach of such limitations, even if You are not required to distribute an end user license agreement or terms of use under subsection 2.3.1(iii).
2.3.2.2 You must ensure that the Software is not distributed in any form that allows it to be reused by any application other than Your Integrated Product. If You have any questions regarding redistribution, please contact <EMAIL>. For use of the Software in design-time (i.e. within a development environment) Your Authorized End-Users need to obtain their own Developer Licenses from Progress.
2.3.2.3 You must prohibit Your Authorized End-Users from using the Software independently from Your Integrated Products, or from decompiling, reverse engineering or otherwise seeking to discover the source code of the Programs.
2.3.2.4 You must include a valid copyright message in Your Integrated Products in a location viewable by Authorized End-Users (e.g. “About” box) that will serve to protect Progress’ copyright and other intellectual property rights in the Software.
2.3.2.5 You are not allowed to, and are expressly prohibited from granting Your Authorized End-Users any right to further sublicense the Software.
2.4 Developer License
2.4.1 General. Subject to the terms and conditions set forth in this Agreement, Licensor hereby grants to Licensee and Licensee hereby accepts, a limited, non-transferable, perpetual, royalty-free, sublicenseable (solely as set forth in Section 2.3), non-exclusive license to install, use, include with Integrated Products and redistribute the Programs in executable, object code form only.
2.4.2 Support. No dedicated technical support is provided with the Software, however, as part of your license you are allowed to access those support resources offered by Progress at its sole discretion (which may include documentation, Knowledge Base articles, forums). Technical support may be available for purchase separately, please contact Progress if you are interested in more information about obtaining a paid support subscription.
2.4.3 Updates. During the Term of this License, Progress may, but is under no obligation to, provide updates to the Software. Updates, if any, will replace and/or supplement (and may disable) the version of the Software that formed the basis for Your eligibility for the update. You may use the resulting updated Software only in accordance with the terms of this License.
3. License Limitations
3.1 You are not allowed to use, copy, modify, distribute, resell, transfer, rent, lease, or sublicense the Software and Your associated rights except as expressly permitted in this Agreement. Under no circumstances shall You grant further redistribution or sublicense rights to any Authorized End-Users or third party or redistribute any source code of the Programs to any Authorized End-User or third party.
3.2 You may not use the Progress product names, logos or trademarks to market Your Integrated Product.
3.3 Except to the limited extent as is permitted by law notwithstanding contractual prohibition, You are not allowed to disassemble, decompile or “unlock”, decode or otherwise reverse translate or engineer, or attempt in any manner to reconstruct or discover any source code or underlying algorithms of the Programs that are provided to You in object code form only.
4. Delivery
Progress shall make available for download to Licensee a master copy of the Software.
5. Term and Termination
This Agreement and the License granted hereunder shall continue until terminated in accordance with this Section. Unless otherwise specified in this Agreement, the License granted hereunder shall last as long as You use the Software in compliance with the terms herein. Unless otherwise prohibited by law, and without prejudice to Progress’ other rights or remedies, Progress shall have the right to terminate this Agreement and the License granted hereunder immediately if You breach any of the material terms of this Agreement, and You fail to cure such material breach within thirty (30) days of receipt of notice from Progress. Upon termination of this Agreement, all Licenses granted to You hereunder shall terminate automatically and You shall immediately cease use and distribution of the Programs; provided, however, that any sublicenses granted to Your Authorized End-Users in accordance with Section 2.3 shall survive such termination. You must also destroy (i) all copies of the Programs not integrated into a live, functioning instance(s) of Your Integrated Product(s) already installed, implemented and deployed for Your Authorized End-User(s), and (ii) any product and company logos provided by Progress in connection with this Agreement.
6. Product Discontinuance
Progress reserves the right to discontinue the Software or any component of the Software, whether offered as a standalone product or solely as a component, at any time.
7. Intellectual Property
All title and ownership rights in and to the Software (including but not limited to any images, photographs, animations, video, audio, music, or text embedded in the Software), the intellectual property embodied in the Software, and any trademarks or service marks of Progress that are used in connection with the Software are and shall at all times remain exclusively owned by Progress and its licensors. All title and intellectual property rights in and to the content that may be accessed through use of the Software is the property of the respective content owner and may be protected by applicable copyright or other intellectual property laws and treaties. This Agreement grants You no rights to use such content. This Software may contain or be accompanied by certain third party components which are subject to additional restriction. These components, if any, are identified in, and subject to, special license terms and conditions set forth in the “readme.txt” file, the “notices.txt” file, or the “Third Party Software” file accompanying the Software (“Special Notices”). The Special Notices include important licensing and warranty information and disclaimers. In the event of a conflict between the Special Notices and the other portions of this Agreement, the Special Notices will take precedence (but solely with respect to the third party component(s) to which the Special Notice relates). Any open source software that may be delivered by Progress embedded in or in association with Progress products is provided pursuant to the open source license applicable to the software and subject to the disclaimers and limitations on liability set forth in such license.
8. Collection and Use of Data
Progress uses tools to deliver certain Software features and extensions, identify trends and bugs, collect activation information, usage statistics and track other data related to Your use of the Software as further described in the most current version of Progress’ Privacy Policy (located at: https://www.progress.com/legal/privacy-policy). By Your acceptance of the terms of this Agreement and/or use of the Software, You authorize the collection, use and disclosure of this data for the purposes provided for in this Agreement and/or the Privacy Policy.
9. Limited Warranty
THE SOFTWARE IS LICENSED ‘AS IS’. YOU BEAR THE RISK OF USING THE SOFTWARE. PROGRESS GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. YOU MAY HAVE ADDITIONAL RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, PROGRESS EXCLUDES THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. YOUR SOLE REMEDY FOR ANY FAILURE OR ANY FORM OF DAMAGE CAUSED BY THIS SOFTWARE IS A FULL REFUND OF THE LICENSE FEE WE HAVE RECEIVED FROM YOU, WHICH IN THE CASE OF A FREE OR NO COST LICENSE IS $0.
10. Limitation of Liability
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL PROGRESS BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF ADVISED OF THE POSSIBILITY THEREOF, AND REGARDLESS OF THE LEGAL OR EQUITABLE THEORY (CONTRACT, TORT OR OTHERWISE) UPON WHICH THE CLAIM IS BASED. IN ANY CASE, PROGRESS’ ENTIRE LIABILITY UNDER ANY PROVISION OF THIS AGREEMENT SHALL NOT EXCEED FIVE U.S. DOLLARS ($5), NOTWITHSTANDING ANY FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT BE APPLICABLE. PROGRESS IS NOT RESPONSIBLE FOR ANY LIABILITY ARISING OUT OF CONTENT PROVIDED BY LICENSEE OR A THIRD PARTY THAT IS ACCESSED THROUGH THE SOFTWARE AND/OR ANY MATERIAL LINKED THROUGH SUCH CONTENT. ANY DATA INCLUDED WITH OR IN THE SOFTWARE IS FOR TESTING USE ONLY AND PROGRESS HEREBY DISCLAIMS ANY AND ALL LIABILITY ARISING THEREFROM.
11. Indemnity
You agree to indemnify, hold harmless, and defend Progress and its resellers from and against any and all claims, lawsuits and proceedings (collectively “Claims”), and all expenses, costs (including attorney's fees), judgments, damages and other liabilities resulting from such Claims, that arise or result from (i) Your use of the Software in violation of this Agreement, (ii) the use or distribution of Your Integrated Product or (iii) Your modification of the Program’s source code.
12. Confidentiality
Except as otherwise provided herein, each party expressly undertakes to retain in confidence all information and know-how transmitted or disclosed to the other that the disclosing party has identified as being proprietary and/or confidential or that, by the nature of the circumstances surrounding the disclosure, ought in good faith to be treated as proprietary and/or confidential, and expressly undertakes to make no use of such information and know-how except under the terms and during the existence of this Agreement. However, neither party shall have an obligation to maintain the confidentiality of information that: (i) it received rightfully from a third party without an obligation to maintain such information in confidence; (ii) the disclosing party has disclosed to a third party without any obligation to maintain such information in confidence; (iii) was known to the receiving party prior to its disclosure by the disclosing party; or (iv) is independently developed by the receiving party without use of the confidential information of the disclosing party. Further, either party may disclose confidential information of the other party as required by governmental or judicial order, provided such party gives the other party prompt written notice prior to such disclosure and complies with any protective order (or equivalent) imposed on such disclosure. Without limiting the foregoing, Licensee shall treat any source code for the Programs as confidential information and shall not disclose, disseminate or distribute such materials to any third party without Progress’ prior written permission. Each party’s obligations under this Section 12 shall apply at all times during the term of this Agreement and for five (5) years following termination of this Agreement, provided, however, that (i) obligations with respect to source code shall survive in perpetuity and (ii) trade secrets shall be maintained as such until they fall into the public domain.
13. Governing Law
This License will be governed by the law of the Commonwealth of Massachusetts, U.S.A., without regard to the conflict of laws principles thereof. If any dispute, controversy, or claim cannot be resolved by a good faith discussion between the parties, then it shall be submitted for resolution to a state or Federal court or competent jurisdiction in Boston, Massachusetts, USA, and the parties hereby agree to submit to the jurisdiction and venue of such court. The Uniform Computer Information Transactions Act and the United Nations Convention on the International Sale of Goods shall not apply to this Agreement. Failure of a party to enforce any provision of this Agreement shall not constitute or be construed as a waiver of such provision or of the right to enforce such provision.
14. Entire Agreement
This Agreement shall constitute the entire agreement between the parties with respect to the subject matter hereof and supersedes all prior and contemporaneous communications regarding the subject matter hereof. Use of any purchase order or other Licensee document in connection herewith shall be for administrative convenience only and all terms and conditions stated therein shall be void and of no effect unless otherwise agreed to in writing by both parties. In cases where this license is being obtained through an approved third party, these terms shall supersede any third party license or purchase agreement.
15. No Assignment
You may not assign, sublicense, sub-contract, or otherwise transfer this Agreement, or any rights or obligations under it, without Progress’ prior written consent.
16. Survival
Any provisions of the Agreement containing license restrictions, including but not limited to those related to the Program source code, warranties and warranty disclaimers, confidentiality obligations, limitations of liability and/or indemnity terms, and any provision of the Agreement which, by its nature, is intended to survive shall remain in effect following any termination or expiration of the Agreement.
17. Severability
If a particular provision of this Agreement is terminated or held by a court of competent jurisdiction to be invalid, illegal, or unenforceable, this Agreement shall remain in full force and effect as to the remaining provisions.
18. Force Majeure
Neither party shall be deemed in default of this Agreement if failure or delay in performance is caused by an act of God, fire, flood, severe weather conditions, material shortage or unavailability of transportation, government ordinance, laws, regulations or restrictions, war or civil disorder, or any other cause beyond the reasonable control of such party.
19. Export Classifications
You expressly agree not to export or re-export Progress Software or Your Integrated Product to any country, person, entity or end user subject to U.S. export restrictions. You specifically agree not to export, re-export, or transfer the Software to any country to which the U.S. has embargoed or restricted the export of goods or services, or to any national of any such country, wherever located, who intends to transmit or transport the products back to such country, or to any person or entity who has been prohibited from participating in U.S. export transactions by any federal agency of the U.S. government. You warrant and represent that neither the U.S.A. Bureau of Industry and Security nor any other federal agency has suspended, revoked or denied Your export privileges.
20. Commercial Software
The Programs and the Documentation are "Commercial Items", as that term is defined at 48 C.F.R. §2.101, consisting of "Commercial Computer Software" and "Commercial Computer Software Documentation", as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States.
21. Reports and Audit Rights
Licensee shall grant Progress audit rights against Licensee twice within a calendar three hundred and sixty-five (365) day period upon two weeks written notice, to verify Licensee’s compliance with this Agreement. Licensee shall keep adequate records to verify Licensee’s compliance with this Agreement.
YOU ACKNOWLEDGE THAT YOU HAVE READ THIS AGREEMENT, THAT YOU UNDERSTAND THIS AGREEMENT, AND UNDERSTAND THAT BY CONTINUING THE INSTALLATION OF THE SOFTWARE PRODUCT, BY LOADING OR RUNNING THE SOFTWARE PRODUCT, OR BY PLACING OR COPYING THE SOFTWARE ONTO YOUR COMPUTER HARD DRIVE, YOU AGREE TO BE BOUND BY THIS AGREEMENT’S TERMS AND CONDITIONS. YOU FURTHER AGREE THAT, EXCEPT FOR WRITTEN SEPARATE AGREEMENTS BETWEEN PROGRESS AND YOU, THIS AGREEMENT IS A COMPLETE AND EXCLUSIVE STATEMENT OF THE RIGHTS AND LIABILITIES OF THE PARTIES.
<file_sep>/src/extension/src/signalr-api-module/syncCommand.ts
import { CoreTemplateStudioApiCommand } from "./coreTemplateStudioApiCommand";
import { CONSTANTS } from "../constants";
export class SyncCommand extends CoreTemplateStudioApiCommand {
async performCommandAction(connection: signalR.HubConnection): Promise<any> {
connection.on(
CONSTANTS.API.SYNC_LIVE_MESSAGE_TRIGGER_NAME,
this.commandPayload.liveMessageHandler
);
const result = await connection
.invoke(
CONSTANTS.API.SIGNALR_API_SYNC_METHOD_NAME,
this.commandPayload.payload!.path
)
.catch((error: Error) => {
Promise.reject(error);
});
connection.stop();
return Promise.resolve(result!.value);
}
}
<file_sep>/src/client/src/actions/wizardSelectionActions/updateProjectNameAndPath.ts
import { WIZARD_SELECTION_TYPEKEYS } from "./typeKeys";
import { validateName } from "../../utils/validateName";
import { IProjectName } from "../../reducers/wizardSelectionReducers/updateProjectName";
export interface IUpdateProjectNameActionType {
type: WIZARD_SELECTION_TYPEKEYS.UPDATE_PROJECT_NAME;
payload: IProjectName;
}
export interface IUpdateProjectPathActionType {
type: WIZARD_SELECTION_TYPEKEYS.UPDATE_OUTPUT_PATH;
payload: string;
}
const updateProjectNameAction = (
projectName: string
): IUpdateProjectNameActionType => {
const validation = validateName(projectName, "project");
const projectNameObject = {
projectName: projectName,
validation: validation
};
return {
type: WIZARD_SELECTION_TYPEKEYS.UPDATE_PROJECT_NAME,
payload: projectNameObject
};
};
const updateOutputPathAction = (outputPath: string): any => ({
type: WIZARD_SELECTION_TYPEKEYS.UPDATE_OUTPUT_PATH,
payload: outputPath
});
export { updateOutputPathAction, updateProjectNameAction };
<file_sep>/templates/Web/Pages/Angular.Grid/src/app/app-shell/Param_SourceName_Kebab/grid.component.ts
import { Component, OnInit } from '@angular/core';
import { GridService, IGridTextItem } from './grid.service';
@Component({
selector: 'app-grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.css']
})
export class GridComponent implements OnInit {
GreyBox = require('../../../assets/GreyBox.svg') as string;
WarningMessageText = 'Request to get grid text failed:';
WarningMessageOpen = false;
gridTextAssets: IGridTextItem[] = [
{
description: 'example1',
header: 'example1',
id: 0
},
{
description: 'example2',
header: 'example2',
id: 1
}
];
constructor(private gridService: GridService) { }
ngOnInit() {
this.gridService.getGridItems().subscribe(
result => {
this.gridTextAssets = result;
},
error => {
this.WarningMessageOpen = true;
this.WarningMessageText = `Request to get grid text failed: ${error}`;
}
);
}
handleWarningClose(open: boolean) {
this.WarningMessageOpen = open;
this.WarningMessageText = '';
}
}
<file_sep>/templates/Web/Pages/KendoAngular.Chart/src/app/components/Param_SourceName_Kebab/Param_SourceName_Kebab.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-Param_SourceName_Kebab',
templateUrl: './Param_SourceName_Kebab.component.html'
})
export class Param_SourceName_PascalComponent {
public series = [
{ category: 'EUROPE', value: 0.3 },
{ category: 'NORTH AMERIKA', value: 0.23 },
{ category: 'AUSTRALIA', value: 0.18 },
{ category: 'ASIA', value: 0.15 },
{ category: 'SOUTH AMERIKA', value: 0.09 },
{ category: 'AFRICA', value: 0.05 }
];
}
<file_sep>/src/client/src/reducers/wizardContentReducers/detailsPageReducer.ts
import { WIZARD_INFO_TYPEKEYS } from "../../actions/wizardInfoActions/typeKeys";
import WizardInfoType from "../../actions/wizardInfoActions/wizardInfoActionType";
import { IDetail } from "../../actions/wizardInfoActions/setDetailsPage";
/* State Shape
{
details: {
data: IOption,
isIntlFormatted: boolean
}
}
*/
const initialState = {
isIntlFormatted: false,
data: {
title: "",
internalName: "",
body: "",
name: "",
displayName: "",
summary: "",
longDescription: "",
position: 0,
svgUrl: undefined,
licenses: [],
selected: false,
author: "",
tags: undefined
}
};
const detailPage = (state: IDetail = initialState, action: WizardInfoType) => {
switch (action.type) {
case WIZARD_INFO_TYPEKEYS.SET_DETAILS_PAGE_INFO:
return action.payload;
default:
return state;
}
};
export default detailPage;
<file_sep>/templates/Web/Projects/VueDefault/README_postaction.md
## Getting Started
In the root directory of the project...
1. Install node modules `yarn install` or `npm install`.
2. Start development server `yarn start` or `npm start`.
## Next Steps
//{[{
### Adding a New Page
1. Create a file in `/src/views` with your Vue Template.
2. Add a route for your page to `/src/router/index.js`.
3. Add a button to the navigation bar in `/src/components/TheNavBar.vue`.
//}]}
### Deployment
The generated templates can be deployed to Azure App Service using the following steps:
1. In the root directory of the project `yarn build` or `npm build` to create a build folder.
2. Move the build folder inside the server folder.
3. Deploy the server folder to Azure App Service using the [Azure App Service Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice).
4. If a database is used, add the environment variables defined in .env to your Application Settings.
5. Consider adding authentication and securing back-end API's by following [Azure App Service Security](https://docs.microsoft.com/en-us/azure/app-service/overview-security).
Full documentation for deployment to Azure App Service can be found here: [Deployment Docs](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/deployment.md).
## File Structure
//{[{
The front-end is based on [Vue CLI](https://cli.vuejs.org/).
//}]}
The front-end is served on http://localhost:3000/ and the back-end on http://localhost:3001/.
```
.
//^^
/{[{
├── src - Vue front-end
│ ├── assets/ - Default images
│ ├── components/ - Common Vue components shared between different views
│ ├── router/ - Vue routes
│ ├── views/ - The main pages displayed
│ ├── constants.js - Contains constants for error messages and endpoints
│ ├── App.vue - Base Vue template
│ └── main.js - Root Vue Component
//}]}
└── README.md
```
## Additional Documentation
//{[{
- Vue - https://vuejs.org/v2/guide/
- Vue Router - https://router.vuejs.org/
//}]}
- Bootstrap CSS - https://getbootstrap.com/
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).
<file_sep>/templates/Web/Pages/KendoAngular.Grid/src/app/components/Param_SourceName_Kebab/Param_SourceName_Kebab.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { products } from '../../common/products';
import { Product } from '../../common/product-model';
@Component({
selector: 'app-Param_SourceName_Kebab.component',
templateUrl: './Param_SourceName_Kebab.component.html'
})
export class Param_SourceName_PascalComponent {
public gridData: Product[] = products;
public pageSize = 10;
public formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {}
public createFormGroup = (args: any): FormGroup => {
const item = args.isNew ? new Product() : args.dataItem;
this.formGroup = this.formBuilder.group({
ProductID: item.ProductID,
ProductName: [item.ProductName, Validators.required],
UnitPrice: item.UnitPrice,
UnitsInStock: [item.UnitsInStock, Validators.compose([Validators.required, Validators.pattern('^[0-9]{1,3}')])],
Discontinued: item.Discontinued
});
return this.formGroup;
}
}
<file_sep>/src/client/src/utils/constants.ts
import { defineMessages } from "react-intl";
const PAGE_DETAILS = "/PageDetail";
const DEFAULT = "default";
const BOOTSTRAP = "bootstrap";
const MATERIAL = "material";
const SELECT_FRAMEWORKS = "/SelectFrameworks";
const SELECT_THEME = "/SelectTheme";
const SELECT_PAGES = "/SelectPages";
const AZURE_LOGIN = "/AzureLogin";
const REVIEW_AND_GENERATE = "/ReviewAndGenerate";
const NEW_PROJECT = "/";
const PRODUCTION = "production";
const DEVELOPMENT = "development";
const INTL_MESSAGES = defineMessages({
EMPTY_FIELD: {
id: "constants.emptyField",
defaultMessage: "{fieldId} field cannot be empty"
}
});
const MAX_PAGES_ALLOWED = 20;
const KENDOKAS = {
ORANGE : "orange",
BLUE: "blue",
GREEN: "green",
RED: "red"
}
const ROUTES = {
PAGE_DETAILS,
SELECT_FRAMEWORKS,
SELECT_PAGES,
SELECT_THEME,
REVIEW_AND_GENERATE,
NEW_PROJECT
};
const THEMES = [
DEFAULT,
BOOTSTRAP,
MATERIAL,
];
// Presents the routes in the order of the wizard
const ROUTES_ARRAY = [
NEW_PROJECT,
SELECT_FRAMEWORKS,
SELECT_PAGES,
SELECT_THEME,
REVIEW_AND_GENERATE
];
const SERVICE_KEYS = {
COSMOS_DB: "cosmosDB",
AZURE_FUNCTIONS: "azureFunctions"
};
const COSMOS_APIS = {
MONGO: "MongoDB",
SQL: "SQL"
};
const WIZARD_CONTENT_INTERNAL_NAMES = {
ANGULAR: "Angular",
AZURE: "wts.Feature.Azure",
AZURE_FUNCTIONS: "wts.Feature.Azure.AzureFunctions",
REACT_BLANK_PAGE: "wts.Page.React.Blank",
KENDO_REACT_BLANK_PAGE: "wts.Page.Kendo.React.Blank",
KENDO_REACT_HELLO_PAGE: "wts.Page.Kendo.React.Hello",
KENDO_REACT_GRID_PAGE: "wts.Page.Kendo.React.Grid",
KENDO_REACT_CHART_PAGE: "wts.Page.Kendo.React.Chart",
KENDO_REACT_FORM_PAGE: "wts.Page.Kendo.React.Form",
KENDO_ANGULAR_BLANK_PAGE: "wts.Page.Kendo.Angular.Blank",
KENDO_ANGULAR_HELLO_PAGE: "wts.Page.Kendo.Angular.Hello",
KENDO_ANGULAR_GRID_PAGE: "wts.Page.Kendo.Angular.Grid",
KENDO_ANGULAR_CHART_PAGE: "wts.Page.Kendo.Angular.Chart",
KENDO_ANGULAR_FORM_PAGE: "wts.Page.Kendo.Angular.Form",
KENDO_VUE_BLANK_PAGE: "wts.Page.Kendo.Vue.Blank",
KENDO_VUE_HELLO_PAGE: "wts.Page.Kendo.Vue.Hello",
KENDO_VUE_GRID_PAGE: "wts.Page.Kendo.Vue.Grid",
KENDO_VUE_CHART_PAGE: "wts.Page.Kendo.Vue.Chart",
KENDO_VUE_FORM_PAGE: "wts.Page.Kendo.Vue.Form",
KENDO_PLUS_ICON: "plusicon",
KENDO_MINUS_ICON: "minusicon",
KENDO_DEFAULT_THEME: "default",
KENDO_BOOTSTRAP_THEME: "bootstrap",
KENDO_MATERIAL_THEME: "material",
REACT_CONTENT_GRID: "wts.Page.React.Grid",
REACT_MASTER_DETAIL: "wts.Page.React.MasterDetail",
REACT_LIST: "wts.Page.React.List",
ANGULAR_BLANK_PAGE: "wts.Page.Angular.Blank",
ANGULAR_CONTENT_GRID: "wts.Page.Angular.Grid",
ANGULAR_MASTER_DETAIL: "wts.Page.Angular.MasterDetail",
ANGULAR_LIST: "wts.Page.Angular.List",
COSMOS_DB: "wts.Feature.Azure.Cosmos",
COSMOS_DB_MONGO: "wts.Feature.Azure.Cosmos.Mongo",
COSMOS_DB_SQL: "wts.Feature.Azure.Cosmos.SQL",
FULL_STACK_APP: "KendoWebApp",
NODE_JS: "NodeJS",
FLASK: "Flask",
REACT_JS: "ReactJS",
KENDO_REACT: "KendoReact",
KENDO_ANGULAR: "KendoAngular",
KENDO_VUE: "KendoVue",
REST_API: "RestAPI",
VUE: "Vue",
VUE_BLANK_PAGE: "wts.Page.Vue.Blank",
VUE_CONTENT_GRID: "wts.Page.Vue.Grid",
VUE_MASTER_DETAIL: "wts.Page.Vue.MasterDetail",
VUE_LIST: "wts.Page.Vue.List"
};
const EXTENSION_MODULES = {
AZURE: "Azure",
GENERATE: "GenerateExperience",
TELEMETRY: "Telemetry",
VALIDATOR: "Validator",
VSCODEUI: "VSCodeUI",
DEPENDENCYCHECKER: "DependencyChecker",
CORETS: "CoreTSModule",
DEFAULTS: "Defaults"
};
// Define extension commands here that should be received from the extension
const EXTENSION_COMMANDS = {
AZURE_LOGIN: "login",
AZURE_LOGOUT: "logout",
GENERATE: "generate",
GET_OUTPUT_PATH: "get-output-path",
GET_PROJECT_NAME: "get-project-name",
GET_USER_STATUS: "get-user-status",
NAME_COSMOS: "name-cosmos",
NAME_FUNCTIONS: "name-functions",
NAME_APP_SERVICE: "name-app-service",
PROJECT_PATH_VALIDATION: "project-path-validation",
SUBSCRIPTION_DATA_COSMOS: "subscription-data-for-cosmos",
SUBSCRIPTION_DATA_FUNCTIONS: "subscription-data-for-functions",
SUBSCRIPTION_DATA_APP_SERVICE: "subscription-data-for-app-service",
TRACK_PAGE_SWITCH: "track-page-switch",
GEN_STATUS_MESSAGE: "update-status-message",
GEN_STATUS: "update-status",
GET_PORT: "get-port",
OPEN_PROJECT_IN_VSCODE: "open-project-vscode",
GET_VERSIONS: "get-versions",
CLOSE_WIZARD: "close-wizard",
RESET_PAGES: "reset-pages",
GET_PREVIEW_STATUS: "get-preview",
GET_DEPENDENCY_INFO: "check-dependency",
GET_FRAMEWORKS: "get-frameworks",
GET_PAGES: "get-pages"
};
export {
PRODUCTION,
EXTENSION_MODULES,
EXTENSION_COMMANDS,
ROUTES,
KENDOKAS,
ROUTES_ARRAY,
MAX_PAGES_ALLOWED,
SERVICE_KEYS,
WIZARD_CONTENT_INTERNAL_NAMES,
INTL_MESSAGES,
COSMOS_APIS,
THEMES,
DEVELOPMENT
};
<file_sep>/CONTRIBUTING.md
# Contributing to the Kendo UI VsCode Scaffolder
Thank you for your interest in contributing to Kendo UI!
## Ways to Contribute
You can contribute by:
* Submitting bug-fixes.
* Proposing changes in the documentation or updates to existing code.
* Adding features or missing functionality.
## Commit Message Guideliens
### Overview
We follow some rules as to how our Git commit messages can be best formatted in such a way that they are more readable and easy to follow when going through the project history. Moreover, we use the Git commit messages to generate the changelog.
### Formats
> The length of each commit message should not exceed 50 characters. This allows for a greater readability on GitHub and for using various Git tools.
Each commit message consists of a:
* [(Mandatory) Header](#header)
* [(Optional) Body](#body)
* [(Optional) Footer](#footer)
The following example demonstrates the regular pattern format of a commit message.
```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
### Header
The header is mandatory to include in a commit message and follows a special pattern that contains:
* [Type](#type)
* [Scope](#scope)
* [Subject](#subject)
##### Type
The type header is mandatory and has to be any of the following options:
* **chore**—A change that affects the build system or external dependencies. For example, `scopes: gulp, npm`.
* **docs**—A change in the documentation only.
* **feat**—A new feature.
* **fix**—A bug fix.
* **perf**—A change in the code for improving the performance.
* **refactor**—A change in the code that neither fixes a bug nor adds a feature.
* **style**—A change that does not affect the meaning of the code. For example, white-space, formatting, missing semi-colons, and other.
* **test**—An addition of missing tests or a correction of existing tests.
The following examples provide commit messages of the `docs` and `fix` types.
```
docs: add content on data back from server, fix links
```
```
fix: sync locked containers when height changes
```
##### Scope
The scope of the header is optional. It should be the name of the component which is affected, as perceived by someone who reads the changelog that was generated on the base of the commit messages.
##### Subject
The subject contains a succinct description of the change. When creating the subject:
* Use the Imperative Mood. For example, "change", and not "changed" or "changes".
* Don't capitalize the first letter.
* Don't put a period (`.`) at the end.
* Try to limit the subject to 50 characters. GitHub hides the rest of the message.
### Body
When creating the body:
* Use the Imperative Mood. For example, "change", and not "changed" or "changes".
* Include the motivation for the change and contrast this with the previous behavior.
* Reference the GitHub issues that this commit targets.
The following example provides a Git command for a commit message of the `fix` type.
```
git commit -m 'fix(grid): missing left border' -m 'telerik/kendo-themes/issues/1234'
```
### Footer
When creating the footer:
* Include all the information about any **Breaking Changes**.
When implementing a **Breaking Change** commit message:
* Start with `BREAKING CHANGE:`.
* Follow the intro line with a space or two newlines. The rest of the commit message is then used to describe the change.
## Steps to Contribute
To submit a pull request:
1. If this is your first contribution to Kendo UI, read and sign the [Kendo UI Contribution License Agreement (CLA)](https://docs.google.com/forms/d/e/1FAIpQLSdSzuLLij8dtytTeiXCzlHcTmHYZIxgrAa7BSaO_fno79ua1A/viewform?c=0&w=1). The CLA confirms that you acknowledge the legal aspects of your contributions.
1. Fork the repo
1. Make changes in a git branch, dedicated to the issue you are fixing:
```shell
git checkout -b my-fix-branch develop
```
1. Add your contribution, following the [coding guidelines](#coding-guidelines) and [commit message guidelines](#commit-message-guidelines).
1. [Submit a Pull Request](https://help.github.com/articles/creating-a-pull-request/).
1. Address any feedback to the Pull Request until the PR is approved.
1. Rebase your PR onto the latest changes from the `develop` branch.
<file_sep>/templates/Web/Projects/FlaskDefault/server/server.py
from flask import Flask, send_from_directory
from flask import jsonify
from flask import make_response
from constants import CONSTANTS
import os
from os.path import exists, join
app = Flask(__name__, static_folder = 'build')
# Catching all routes
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
if path != "" and exists(join(app.static_folder, path)):
return send_from_directory(app.static_folder, path)
else:
return send_from_directory(app.static_folder, 'index.html')
# Error Handler
@app.errorhandler(404)
def page_not_found(error):
return make_response(
jsonify(
{'error': 'Page not found'}
),
404
)
if __name__ == '__main__':
app.run(port=CONSTANTS['PORT'])<file_sep>/src/extension/src/services/progressType.ts
import { IVSCodeProgressType } from "../types/vscodeProgressType";
export default class ProgressType implements IVSCodeProgressType {
}<file_sep>/src/client/src/reducers/wizardSelectionReducers/index.ts
import { combineReducers } from "redux";
import backendFramework from "./selectBackendFrameworkReducer";
import frontendFramework from "./selectFrontendFrameworkReducer";
import pages from "./selectPagesReducer";
import appType from "./selectWebAppReducer";
import projectNameObject from "./updateProjectName";
import outputPathObject from "./updateOutputPath";
import services from "./services";
import pageCount from "./pageCountReducer";
import theme from "./themeReducer";
import isValidatingName from "./validatingNameReducer";
const selectionStateReducer = combineReducers({
appType,
frontendFramework,
backendFramework,
pages,
services,
theme,
outputPathObject,
pageCount,
isValidatingName,
projectNameObject
});
export default selectionStateReducer;
export type SelectionState = ReturnType<typeof selectionStateReducer>;
<file_sep>/src/client/src/actions/wizardContentActions/wizardContentActionType.ts
import { IBackendFrameworksSuccessActionType } from "./getBackendFrameworks";
import { IFrontendFrameworksActionType } from "./getFrontendFrameworks";
import { IPageOptionsActionType } from "./getPagesOptions";
import { IProjectTypesActionType } from "./getProjectTypesSuccess";
import { IPreviewStatusActionType } from "./setPreviewStatus";
import { ISetPortActionType } from "./setPort";
type WizardContentActionType =
| IBackendFrameworksSuccessActionType
| IFrontendFrameworksActionType
| IPageOptionsActionType
| IProjectTypesActionType
| IPreviewStatusActionType
| ISetPortActionType;
export default WizardContentActionType;
<file_sep>/templates/Web/_composition/NodeJS/Page.Node.Cosmos.SQL.AddMerging/README_postaction.md
## Next Steps
//^^
//{[{
### Cosmos Database
**Do Not share the keys stored in the .env file publicly.**
The Cosmos database will take approximately 5 minutes to deploy. Upon completion of deployment,
a notification will appear in VS Code and your connection string will be automatically added in
the .env file. The schema and operations for the Cosmos database are defined in `/server` folder.
Additional documentation can be found here: [Cosmos Docs](https://github.com/Microsoft/WebTemplateStudio/blob/dev/docs/services/azure-cosmos.md).
//}]}
### Deployment
The generated templates can be deployed to Azure App Service using the following steps:
├── server/ - Express server that provides API routes and serves front-end
//{[{
│ ├── sql/ - Handles all interactions with the cosmos database
//}]}
│ ├── routes/ - Handles API calls for routes
│ ├── app.js - Adds middleware to the express server
│ ├── constants.js - Defines the constants for the endpoints and port
│ └── server.js - Configures Port and HTTP Server
//^^
//{[{
├── .env - API Keys
//}]}
└── README.md
```
## Additional Documentation
- Bootstrap CSS - https://getbootstrap.com/
//^^
//{[{
- Cosmos DB - https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs
//}]}
This project was created using [Microsoft Web Template Studio](https://github.com/Microsoft/WebTemplateStudio).<file_sep>/src/client/src/actions/wizardContentActions/setPort.ts
import { WIZARD_CONTENT_TYPEKEYS } from "./typeKeys";
export interface ISetPortActionType {
type: WIZARD_CONTENT_TYPEKEYS.SET_PORT;
payload: number;
}
export const setPortAction = (port: number): ISetPortActionType => ({
payload: port,
type: WIZARD_CONTENT_TYPEKEYS.SET_PORT
});
<file_sep>/src/client/src/actions/vscodeApiActions/getVSCodeApi.ts
import { VSCODE_TYPEKEYS } from "./typeKeys";
export interface IVSCodeAPIActionType {
type: VSCODE_TYPEKEYS.GET_VSCODE_API;
}
const getVSCodeApi = (): IVSCodeAPIActionType => ({
type: VSCODE_TYPEKEYS.GET_VSCODE_API
});
export { getVSCodeApi };
<file_sep>/src/extension/src/types/generationPayloadType.ts
export interface IGenerationPayloadType {
backendFramework: string;
frontendFramework: string;
pages: any;
path: string;
theme: string;
projectName: string;
projectType: string;
services: any;
}
<file_sep>/src/client/src/actions/wizardContentActions/getBackendFrameworks.ts
import { getFrameworks } from "./getFrameworks";
import { WIZARD_CONTENT_TYPEKEYS } from "./typeKeys";
import { IOption } from "../../types/option";
import WizardContentActionType from "./wizardContentActionType";
import { Dispatch } from "react";
export interface IBackendFrameworksSuccessActionType {
type: WIZARD_CONTENT_TYPEKEYS.GET_BACKEND_FRAMEWORKS_SUCCESS;
payload: IOption[];
}
export const getBackendFrameworksSuccess = (
frameworks: IOption[]
): IBackendFrameworksSuccessActionType => ({
type: WIZARD_CONTENT_TYPEKEYS.GET_BACKEND_FRAMEWORKS_SUCCESS,
payload: frameworks
});
// thunk
export const getBackendFrameworksAction = (
projectType: string,
isPreview: boolean,
serverPort: number
) => {
return async (dispatch: Dispatch<WizardContentActionType>) => {
return dispatch(
getBackendFrameworksSuccess(
await getFrameworks(projectType, "backend", isPreview, serverPort)
)
);
};
};
<file_sep>/src/extension/src/utils/validator.ts
import * as vscode from "vscode";
import { CONSTANTS, ExtensionCommand } from "../constants";
import fs = require("fs");
import path = require("path");
import { WizardServant, IPayloadResponse } from "../wizardServant";
export class Validator extends WizardServant {
clientCommandMap: Map<
ExtensionCommand,
(message: any) => Promise<IPayloadResponse>
> = new Map([
[ExtensionCommand.GetOutputPath, Validator.sendOutputPathSelectionToClient],
[
ExtensionCommand.ProjectPathValidation,
Validator.handleProjectPathValidation
]
]);
public static async sendOutputPathSelectionToClient(
message: any
): Promise<IPayloadResponse> {
return vscode.window
.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false
})
.then((res: any) => {
let path = undefined;
if (res !== undefined) {
if (process.platform === CONSTANTS.API.WINDOWS_PLATFORM_VERSION) {
path = res[0].path.substring(1, res[0].path.length);
} else {
path = res[0].path;
}
}
return {
payload: {
outputPath: path
}
};
});
}
public static async handleProjectPathValidation(
message: any
): Promise<IPayloadResponse> {
const projectPath = message.projectPath;
const projectName = message.projectName;
let projectPathError = "";
let isInvalidProjectPath = false;
let validationObject = Validator.isValidProjectPath(
projectPath,
projectName
);
projectPathError = validationObject.error;
isInvalidProjectPath = !validationObject.isValid;
return {
payload: {
projectPathValidation: {
isValid: !isInvalidProjectPath,
error: projectPathError
}
}
};
}
private static isValidProjectPath = (path: string, name: string) => {
let isValid = true;
let error = "";
if (!fs.existsSync(path) && path !== "") {
error = CONSTANTS.ERRORS.INVALID_OUTPUT_PATH(path);
isValid = false;
} else if (name !== "" && !Validator.isUniquePath(path, name)) {
error = CONSTANTS.ERRORS.PROJECT_PATH_EXISTS(path, name);
isValid = false;
}
return {
isValid: isValid,
error: error
};
};
private static isUniquePath = (projectPath: string, name: string) => {
return !fs.existsSync(path.join(projectPath, name));
};
}
<file_sep>/templates/Web/Projects/KendoAngularDefault/CONTRIBUTING.md
# Guidelines to Contribution
We accept third-party contributions.
## Ways to Contribute
You can contribute by:
* Submitting bug-fixes.
* Proposing changes in documentation or updates to existing code.
* Adding features or missing functionalities.
## Steps to Contribute
To submit your suggestions:
1. If a first-time contributor, read and sign the [Kendo UI for Angular Contribution License Agreement (CLA)](https://docs.google.com/forms/d/e/1FAIpQLSdSzuLLij8dtytTeiXCzlHcTmHYZIxgrAa7BSaO_fno79ua1A/viewform?c=0&w=1). The Agreement confirms that you acknowledge the legal aspects of your contributions.
1. Branch out the repo you want to update.
1. Add your contribution.
1. Submit a [Pull Request](https://help.github.com/articles/creating-a-pull-request/).
## Support-Related Issues
Refer to our [**Community & Support**](http://www.telerik.com/kendo-angular-ui/support/) page for more information on:
* How to report a bug
* New upcoming features
* Support-related questions
<file_sep>/templates/Web/Pages/React.List/src/components/ReactList/index.jsx
import React, { Component } from "react";
import ListItem from "./ListItem";
import ListForm from "./ListForm";
import WarningMessage from "../WarningMessage";
import CONSTANTS from "../../constants";
export default class ReactList extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
WarningMessageOpen: false,
WarningMessageText: ""
};
this.handleWarningClose = this.handleWarningClose.bind(this);
this.handleDeleteListItem = this.handleDeleteListItem.bind(this);
this.handleAddListItem = this.handleAddListItem.bind(this);
}
// Get the sample data from the back end
componentDidMount() {
fetch(CONSTANTS.ENDPOINT.LIST)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(result => this.setState({ list: result }))
.catch(error =>
this.setState({
WarningMessageOpen: true,
WarningMessageText: `${CONSTANTS.ERROR_MESSAGE.LIST_GET} ${error}`
})
);
}
handleDeleteListItem(listItem) {
fetch(`${CONSTANTS.ENDPOINT.LIST}/${listItem._id}`, { method: "DELETE" })
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(result => {
let list = this.state.list;
list = list.filter(item => item._id !== result._id);
this.setState({ list: list });
})
.catch(error => {
this.setState({
WarningMessageOpen: true,
WarningMessageText: `${CONSTANTS.ERROR_MESSAGE.LIST_DELETE} ${error}`
});
});
}
handleAddListItem(textField) {
// Warning Pop Up if the user submits an empty message
if (!textField) {
this.setState({
WarningMessageOpen: true,
WarningMessageText: CONSTANTS.ERROR_MESSAGE.LIST_EMPTY_MESSAGE
});
return;
}
fetch(CONSTANTS.ENDPOINT.LIST, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: textField
})
})
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(result =>
this.setState(prevState => ({
list: [result, ...prevState.list]
}))
)
.catch(error =>
this.setState({
WarningMessageOpen: true,
WarningMessageText: `${CONSTANTS.ERROR_MESSAGE.LIST_ADD} ${error}`
})
);
}
handleWarningClose() {
this.setState({
WarningMessageOpen: false,
WarningMessageText: ""
});
}
render() {
const {
list,
WarningMessageOpen,
WarningMessageText
} = this.state;
return (
<main id="mainContent" className="container">
<div className="row">
<div className="col mt-5 p-0">
<h3>Bootstrap ReactList Template</h3>
</div>
<div className="col-12 p-0">
<ListForm
onAddListItem={this.handleAddListItem}
/>
</div>
{list.map(listItem => (
<ListItem
key={listItem._id}
listItem={listItem}
onDeleteListItem={this.handleDeleteListItem}
/>
))}
<WarningMessage
open={WarningMessageOpen}
text={WarningMessageText}
onWarningClose={this.handleWarningClose}
/>
</div>
</main>
);
}
}
| 0305622407bc7f82f7260aac51840b72178ba194 | [
"JavaScript",
"Markdown",
"Python",
"Text",
"TypeScript"
] | 208 | JavaScript | telerik/kendo-vscode-extensions | 8f3286accc388c955de88e3b3b087e566b639602 | 6589f613bb12502f1b93afcb239f09013b19d974 |
refs/heads/master | <file_sep># user stats; the stats are built here from the table
# note that the stats are being built for player controlled pcs;
# if I implement player creator, users character will be created/stored elsewhere
from data_reader import *
from player_setup import user_name, opponent_name
#combat card dict builder
def user_stats(user_name):
user_card = {'name': user_name,
'score': score_calculator(user_name),
'stamina': stamina_calculator(user_name),
'speed': speed_calculator(user_name),
'offense': offense_calculator(user_name),
'defense': defense_calculator(user_name),
'special offense': special_offense_calculator(user_name),
'special defense': special_defense_calculator(user_name)
}
return user_card
#combat cards; builds a card for the player entering combat and opponent
user_profile = user_stats(user_name)
opponent_profile = user_stats(opponent_name)
<file_sep>
#user setup
user_name = raw_input("Who are you? ")
opponent_name = raw_input("Who are you going to dunk all over? ")
<file_sep>import random
from data_reader import player_stat_ripper
from player_cards import user_profile, opponent_profile
#feed into probabilities below
offense_name = user_profile['name']
defense_name = opponent_profile['name']
offense_stamina = user_profile['stamina']
defense_stamina = opponent_profile['stamina']
offense_speed = user_profile['speed']
defense_speed = opponent_profile['speed']
defense_mid_stamina = 1.05 * (opponent_profile['stamina']) #these constants are arbitrary; figure out someway to weight this
defense_mid_speed = 1.5 * (opponent_profile['speed'])
defense_close_stamina = 1.5 * (opponent_profile['stamina'])
defense_close_speed = 2 * (opponent_profile['speed'])
offense_mid_stamina = .95 * (user_profile['stamina'])
offense_mid_speed = offense_speed
offense_close_stamina = .75 * (user_profile['stamina'])
offense_close_speed = .75 * (user_profile['speed'])
#how these are defined needs to change; there has to be an easier way
#weighted probabilities
offense_to_take_shot = [float(player_stat_ripper(offense_name, 'TOV%')), (100 - float(player_stat_ripper(offense_name, 'TOV%')))]
defense_to_steal = [(100 - float(player_stat_ripper(defense_name, 'STL%'))), (float(player_stat_ripper(defense_name, 'STL%')))]
defense_to_block = [(100 - float(player_stat_ripper(defense_name, 'BLK%'))), (float(player_stat_ripper(defense_name, 'BLK%')))]
defense_to_rebound = [(100 - float(player_stat_ripper(defense_name, 'DRB%'))), (float(player_stat_ripper(defense_name, 'DRB%')))]
offense_to_score = '' #see above
offense_to_rebound = [(100 - float(player_stat_ripper(offense_name, 'ORB%'))), (float(player_stat_ripper(offense_name, 'ORB%')))]
#making a defense stat up
def_combined_mod = 100 - (float(player_stat_ripper(defense_name, 'BLK%')) + float(player_stat_ripper(defense_name, 'STL%')))
defense_to_block_and_steal = [def_combined_mod, 100 - def_combined_mod]
#weighted probability roller
def encounterweights(weights):
totals = []
running_total = 0
for w in weights:
running_total += w
totals.append(running_total)
rnd = random.random() * running_total
for i, total in enumerate(totals):
if rnd < total:
return i
#redefine these functions into a class
def stamina_comp_check(ostamina, dstamina):
if ostamina > dstamina:
return offense_name
else:
return defense_name
def speed_comp_check(ospeed, dspeed):
if ospeed > dspeed:
return offense_name
else:
return defense_name
######################################
# fail or success checks - merge these functions
######################################
def off_fail_long(fail_check):
if encounterweights(fail_check) == 0:
return stamina_comp_check(offense_stamina, defense_stamina)
else:
return defense_name
def off_suc_long(suc_check):
if encounterweights(suc_check) == 0:
return offense_name
else:
return speed_comp_check(offense_speed, defense_speed)
def off_fail_mid(fail_check):
if encounterweights(fail_check) == 0:
return stamina_comp_check(offense_mid_stamina, defense_mid_stamina)
else:
return defense_name
def off_suc_mid(suc_check):
if encounterweights(suc_check) == 0:
return offense_name
else:
return speed_comp_check(offense_mid_speed, defense_mid_speed)
def off_fail_close(fail_check):
if encounterweights(fail_check) == 0:
return stamina_comp_check(offense_close_stamina, defense_close_stamina)
else:
return defense_name
def off_suc_close(suc_check):
if encounterweights(suc_check) == 0:
return offense_name
else:
return speed_comp_check(offense_close_speed, defense_close_speed)
####################################
#long range shot; 3 pt shot
def offense_long_range(offense, defense):
if encounterweights(offense) == 0: #
return off_fail_long(defense)
else:
return off_suc_long(defense)
#mid range shot; from 10ft to <3 point shot
def offense_mid_range(offense, defense): #
if encounterweights(offense) == 0:
return off_fail_mid(defense)
else:
return off_suc_mid(defense)
#close range shot; from DUNK/layup to 10ft
def offense_close_range(offense, defense):
if encounterweights(offense) == 0: #
return off_fail_close(defense)
else:
return off_suc_close(defense)
###############################################
#this needs to be written differently/different spot
#testing output for shot types
def shot_mid():
i = 0
counter = []
while i < 100:
output_counter = offense_mid_range(offense_to_take_shot, defense_to_block)
counter.append(output_counter)
i += 1
counters = ''.join(counter)
offense_output = offense_name + ' : ' + str(counters.count(offense_name))
defense_output = defense_name + ' : ' + str(counters.count(defense_name))
return offense_output + '\n' + defense_output
def shot_long():
i = 0
counter = []
while i < 100:
output_counter = offense_long_range(offense_to_take_shot, defense_to_steal)
counter.append(output_counter)
i += 1
counters = ''.join(counter)
offense_output = offense_name + ' : ' + str(counters.count(offense_name))
defense_output = defense_name + ' : ' + str(counters.count(defense_name))
return offense_output + '\n' + defense_output
def shot_close():
i = 0
counter = []
while i < 100:
output_counter = offense_close_range(offense_to_take_shot, defense_to_block_and_steal)
counter.append(output_counter)
i += 1
counters = ''.join(counter)
offense_output = offense_name + ' : ' + str(counters.count(offense_name))
defense_output = defense_name + ' : ' + str(counters.count(defense_name))
return offense_output + '\n' + defense_output
def shot_maker(shot_value):
if shot_value == 'shot_close':
return shot_close()
if shot_value == 'shot_mid':
return shot_mid()
if shot_value == 'shot_long':
return shot_long()
#I'm sorry world
<file_sep>#this will be modified; just a testing tool right now
import player_setup
import combat_functions
from combat_functions import shot_maker
offense_type = raw_input("What type of shot do you take? (long, mid, close) ")
shot_func = "shot_" + offense_type
print shot_maker(shot_func)
raw_input()
<file_sep>import csv
#sql-like stat ripping function from CSV tables
def player_stat_ripper(table_player_name, table_stat_category):
rawplayerdata = csv.DictReader(open('../data/players.csv', 'rb'))
dict_list = []
for line in rawplayerdata:
dict_list.append(line)
dict_length = len(dict_list)
dict_max = dict_length
dict_counter = 0
#return dict_lists' index number for a given player's name; see below
#it's case sensitive; ie '<NAME>' won't pass but '<NAME>' does
player_key = {}
while dict_counter < dict_max:
#print dict_counter
player_key[dict_list[dict_counter].get('Player')] = dict_counter
dict_counter += 1
if dict_list[player_key[table_player_name]].get(table_stat_category) is '':
return 0 #this may throw errors later if expecting a string like Team or Player
else:
return dict_list[player_key[table_player_name]].get(table_stat_category)
#for teams: enter team name and stat field you want; bam you get it
def team_stat_ripper(table_team_name, table_stat_category):
rawplayerdata = csv.DictReader(open('../data/teams.csv', 'rb'))
dict_list = []
for line in rawplayerdata:
dict_list.append(line)
dict_length = len(dict_list)
dict_max = dict_length
dict_counter = 0
#return dict_lists' index number for a given player's name; see below
#it's case sensitive; ie <NAME> won't pass but <NAME> does
team_key = {}
while dict_counter < dict_max:
#print dict_counter
team_key[dict_list[dict_counter].get('team')] = dict_counter
dict_counter += 1
return dict_list[team_key[table_team_name]].get(table_stat_category)
#examples
#name = "<NAME>"
#team = player_stat_ripper(name, 'Team')
#calculates speed; calculated by bref position and team pace
def speed_calculator(name):
playerteam = player_stat_ripper(name, 'Team')
team_pace = float(team_stat_ripper(playerteam, 'adj pace'))
player_base_speed = float(player_stat_ripper(name, 'Position'))
#i just like the way this made up stat looks, YA'LL
adj_player_speed = (10 - player_base_speed)*10
#modifier 1.176 makes Ty lawson fastest player; i took out the modifier
#there's really no reason for it; it takes away from ability to alter
player_speed = round(team_pace * adj_player_speed)
return player_speed
#calculates 'hit points' or rather 'score' needed before they give up
def score_calculator(name):
player_minutes = float(player_stat_ripper(name, '%Min'))
#find_max_hp =
#couple modifiers here; minimum of 5 hps; 21 is the base score weight;
# the 1.266 number should be modified to a generic, like w/speed
player_hit_points = round(((player_minutes * 1.266)*21) + 5)
return player_hit_points
def stamina_calculator(name):
player_minutes = float(player_stat_ripper(name, '%Min'))
player_age = float(player_stat_ripper(name, 'Age on Jan 1 2012'))
adj_player_minutes = player_minutes * 1.266 #see above for constant change
adj_player_age = 100 - player_age
player_stamina = round(adj_player_minutes * adj_player_age)
return player_stamina
#still need to fix this one; this is just a test version now
def offense_calculator(name):
player_usage = (float(player_stat_ripper(name, 'USG%'))*.01)
player_offense = player_usage * float(player_stat_ripper(name, 'ORtg')) * float(player_stat_ripper(name, 'eFG%'))
adj_player_offense = round((player_offense * 3.5458) + 5)
return adj_player_offense
#don't know how I'm going to factor these stats into the dice roll checks yet
#that's the main issue, then i can set them better
def special_offense_calculator(name):
player_special_offense = 5 #fix this formula
return player_special_offense
def defense_calculator(name):
player_defense = 5 #fix this formula
return player_defense
def special_defense_calculator(name):
player_special_defense = 5 #fix this formula
return player_special_defense
#build a player_profile class, using all the calculators;
#offense, defense, special offense, special defense, stamina, speed
| 6896d9d56dfb8aa22a710f441c16d045fa1eea2f | [
"Python"
] | 5 | Python | kevinthew/21lockout | a79238a35f54298e95049bfe5fb2b7cacf021d1e | 82c3c839d5af79a241521ffac0be017904aad673 |
refs/heads/master | <file_sep># NonnaScan
Auto digitalization of recipees of Nonna's across the world.
# Installation
The project rely on other OCR engines. Please install them before.
**tesseract**:
Follow `https://github.com/tesseract-ocr/tesseract` for instructions. The short answer being:
`sudo apt install tesseract-ocr`
### Installation in itself:
`pip install .`
In future:
`pip install NonnaScan`
<file_sep>#!/usr/bin/env python
from distutils.core import setup
from setuptools import setup, find_namespace_packages, wheel
NAME = "nonnascan"
with open("VERSION") as f:
version = f.readline()
setup(
name=NAME,
version=version,
description="Package to digitalize nonna's recipees.",
author=["LucaZampieri"],
author_email="<EMAIL>",
python_requires=">=3.6",
package_data={"": ["*.o", "*.so", "*.cu.o", "*.pyc"]},
packages=find_namespace_packages(include=[NAME, f"{NAME}.*"]),
install_requires=["numpy", "sklearn", "pandas"],
)
<file_sep>"""
Might use https://cloud.google.com/vision/docs/handwriting instead
"""
import glob
import argparse
import subprocess
import os
from PIL import Image
# import Image
def main():
parser = argparse.ArgumentParser(description="Digitalize a bunch of images.")
parser.add_argument("--data", type=str, default="../../data/nonna_paola/", help="")
parser.add_argument("-l", "--lang", type=str, default="eng", help="")
args = parser.parse_args()
data_folder = args.data
files = glob.glob(data_folder + "/*.jpeg")
print("Preprocessing")
preprocessed_files = []
for file in files:
out_file = os.path.dirname(file) + "/../tmp/" + os.path.basename(file)
print(out_file)
adapt_dpi(file, out_file, 300)
preprocessed_files.append(out_file)
print(f"Analysing {preprocessed_files}")
processed_files = []
for file in preprocessed_files:
file = os.path.abspath(file)
content = digitalize_file(file, lang=args.lang)
processed_files.append(content)
for i, x in enumerate(processed_files):
print(f"File {i} --- results ---")
print(x)
def digitalize_file(file_path, lang=""):
# TODO accept many languages
language = f"-l {lang}" # "-l eng" # pass as an argument
result_file = file_path[: file_path.rfind(".")]
print(result_file)
tesseract_cmd = f"tesseract {file_path} {result_file} {language}"
subprocess.call(tesseract_cmd.split())
with open(result_file + ".txt", "r") as f:
content = f.read()
return content
def adapt_dpi(in_file, out_file, dpi=300):
im = Image.open(in_file)
im.save(out_file, dpi=(dpi, dpi))
if __name__ == "__main__":
main()
<file_sep># OCR
This part is currently handled by tesseract by CLI. For other implementations or API calls to other
libraries, please put them here.
| dda51b76414542dca8777db4e36a5e70f4d62046 | [
"Markdown",
"Python"
] | 4 | Markdown | LucaZampieri/NonnaScan | c681ed6d3827040700aa2495013fd4d4236e6000 | f31231251454299f19941e4df7d3adb6e108a964 |
refs/heads/master | <file_sep># VaultDragon Test #
## Server is deployed at ##
http://172.16.31.10:3000/
## Test GET request ##
http://172.16.31.10:3000/object/key1
## POST your own object at ##
http://172.16.31.10:3000/object/
with the object's format {"keyName":"valueName"}
## Some points ##
* Code is separated into model, controller, routes folder for easy adding of new API endpoints
* the main querying's condition of the GET request is abstracted out for easy addition of future query, such as location
* timestamp is stored in two separate fields (i.e. timestamp and timestampMS) to enable quicker comparison of queried collections and the user-provided timestamp (faster to compare in terms of milliseconds than Date object)
## Few learning points: ##
* reconnecting to the test database before every single unit test to ensure 'clean testing'
* managing of error handling using express middleware and next()
* deploying to digitalocean - new to me but surprisingly manageable
<file_sep>const express = require('express')
const router = express.Router()
const objectController = require('../controllers/object_controller')
router.post('/', objectController.postObject)
router.get('/:key', objectController.getObject)
module.exports = router
<file_sep>const Object = require('../models/object')
const assert = require('assert')
const objectController = {
getObject: (req, res, next) => {
var condition = [req.params]
// makes adding more conditions (e.g. location) in the future possible and more manageable
if (req.query.hasOwnProperty('timestamp')) {
var timestampCondition = { 'timestampMS': { $lte: (parseInt(req.query.timestamp) * 1000) } }
condition.push(timestampCondition)
}
condition = { $and: condition }
Object.findOne(condition, '-_id -__v -timestampMS')
.sort('-timestampMS')
.exec((err, object) => {
if (err) {
next(err)
} else {
res.json(object)
}
})
},
postObject: (req, res, next) => {
var newObject = new Object()
var dateNow = new Date()
var dateNowReadable = dateNow.toString()
var dateNowInMS = dateNow.getTime()
for (var key in req.body) {
newObject['key'] = key
newObject['value'] = req.body[key]
newObject['timestamp'] = dateNowReadable
newObject['timestampMS'] = dateNowInMS
}
newObject.save((err, doc) => {
if (err) {
next(err)
} else {
res.status(200).json(doc)
}
})
}
}
module.exports = objectController
| 14de983161482bc829c33b5746e86b58f35e56de | [
"Markdown",
"JavaScript"
] | 3 | Markdown | chengkoon/vaultdragontest | 4c251e5cb9186a40b0e4b67a180bd797ec84a9a6 | 5fb68f950659b57ef8fb01e341cbaa48c0c938b1 |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 3.5.2.2
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jun 08, 2017 at 03:58 PM
-- Server version: 5.5.27
-- PHP Version: 5.4.7
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `itv_blazon1`
--
-- --------------------------------------------------------
--
-- Table structure for table `doctor_view`
--
CREATE TABLE IF NOT EXISTS `doctor_view` (
`username` varchar(30) NOT NULL,
`emp_id` varchar(6) NOT NULL,
`emp_code` int(11) NOT NULL,
`password` varchar(15) NOT NULL,
`email_id` varchar(30) NOT NULL,
`contact_no` int(10) NOT NULL,
PRIMARY KEY (`email_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `doctor_view`
--
INSERT INTO `doctor_view` (`username`, `emp_id`, `emp_code`, `password`, `email_id`, `contact_no`) VALUES
('meet_doc', 'doc101', 10, 'meet_doc', '<EMAIL>', 2147483647),
('shashi_trainer', '<PASSWORD>', 20, 'shashi_trainer', '<EMAIL>', 2147483647);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`email` varchar(60) NOT NULL,
`password` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES
(9, 'were', '<EMAIL>', '<PASSWORD>');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><!DOCTYPE html>
<html>
<link href="style.css" rel="stylesheet" type="text/css">
<style type="text/css">
</style>
<body>
<?php
$con=mysqli_connect("localhost","root","","itv_blazon1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<div id='box'>
<form method="post" enctype="multipart/form-data" >
<?php
//print_r ($_FILES['file']);
if(isset($_FILES['file'])){
$name = $_FILES['file']['name'];
$extension = explode('.', $name);
$extension = end($extension);
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'] /1024/1024;
$random_name = rand();
$tmp = $_FILES['file']['tmp_name'];
if ((strtolower($type) != "video/mp4") && (strtolower($type) != "video/mpeg") && (strtolower($type) != "video/mpeg1") && (strtolower($type) != "video/mpeg4") && (strtolower($type) != "video/avi") && (strtolower($type) != "video/flv") && (strtolower($type) != "video/wmv") && (strtolower($type) != "video/mov"))
{
$message= "Video Format is not supported !";
}elseif($size >= 13835670)
{
$message="File must not greater than 20mb";
}else
{
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$extension);
mysqli_query($con, "INSERT INTO vid_entry VALUES('', '$name' , '$random_name.$extension')");
$message="Video has been successfully uploaded !";
}
echo "$message <br/> <br/>";
echo "size: $size mb<br/>";
echo "random_name: $random_name <br/>";
echo "name: $name <br/>";
echo "type: $type <br/><br/>";
}
?>
Select Video : <br/>
<input name="UPLOAD_MAX_FILESIZE" value="13835670" type="hidden"/>
<input type="file" name="file" id="file" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</div>
<div id='box'>
<?php
$query = mysqli_query($con, "SELECT * FROM vid_entry");
while($row = mysqli_fetch_array($query)){
?>
<div id='url'>
<a href="view_video.php?video=<?php echo $row['url']; ?>">
<?php echo $row['name'];?>
</div>
<a/>
<?php
}
mysqli_close($con);
?>
</div>
</body>
</html> | 22f35b7e26aa6e53d3e26246431e626c52aca523 | [
"SQL",
"PHP"
] | 2 | SQL | nasirahmad1997/Fitness-world-with-php-mysql | d09e20e90fa4759304df5d8c7c1a1c25bd1625b9 | f2e792c46b8e48f5fdd1a5138654a2597a8a8ecc |
refs/heads/main | <file_sep>Installation
To start off with to run this program you need to have python and flask installed.
To install python it will vary depending on what OS you are running, for me I use windows so I just went to the python website to install it at python.org.
Then to install flask it needs to have python 3.6.5 or above to be installed first. If you are running on windows the python interpreter needs to be in the path.
To Run The Project
How I ran the program was by selecting Python: Select Interpreter and then selecting python venv which is the python environment.
Then I used the debugger in VS code with python flask selected. It should then run and show a local host link
To Use The Website
The first page should be a submission page where you can enter your information such as the food name, your name, your email, and the image of the food.
After submitting the image it should redirect you to the display page with a comment section for you to comment on the images.
But if you don't want to submit anything you could click to the display page and it will display two random images from the database.
<file_sep>from flask import Flask
from flask import render_template
from flask import request,redirect
import sys
from werkzeug.utils import secure_filename
import sqlite3 as sql
import os
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['UPLOAD_FOLDER'] = os.getcwd() + '\\static\\img\\'
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'dbase.db')
with sql.connect(my_file) as db:
cursor = db.cursor()
sqql = ''' CREATE TABLE IF NOT EXISTS NEW( name text, email text, food_name, img);'''
cursor.execute(sqql)
db.commit()
def writeTofile(data, filename):
with open(filename, 'wb') as file:
file.write(data)
print("Stored blob data into: ", filename, "\n")
def convertToBinaryData(filename):
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
@app.route('/',methods = ['POST', 'GET'])
def submission():
if request.method == 'POST':
name = request.form['username']
email = request.form['usermail']
food_name = request.form['foodtyp']
img = request.files['upload']
filename = secure_filename(img.filename)
img.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
imgDIR = os.getcwd() + '\\static\\img\\'+filename
filelocation = 'img/'+filename
convertToBinaryData(imgDIR)
con = sql.connect('dbase.db')
cur = con.cursor()
cur.execute("INSERT INTO NEW(name,email,food_name,img) Values (?,?,?,?)",(' '+name+' ', email+' ', food_name+' ',filelocation))
con.commit()
cur.execute("SELECT * FROM NEW ORDER BY rowid DESC LIMIT 1")
row1 = cur.fetchone()
print(row1)
cur.execute("SELECT * FROM NEW ORDER BY RANDOM() LIMIT 100;")
row2 =cur.fetchone()
con.close()
return render_template('index.html',row1 = row1,row2 = row2)
else:
return render_template('submission-page.html')
@app.route('/index/')
def index():
connection = sql.connect('dbase.db')
cursor = connection.cursor()
cursor.execute("SELECT * FROM NEW ORDER BY RANDOM() LIMIT 1000;")
row1 = cursor.fetchone()
print(row1)
row2 = cursor.fetchone()
cursor.close()
return render_template('index.html',row1 = row1,row2 = row2)
| 66236c52c8c219247b24ec2999f108ef83e2cc26 | [
"Markdown",
"Python"
] | 2 | Markdown | 16ericchen/349-Project1 | 35b2575d9999d732d32d963777dd6c62f28cc628 | 642e313e639dbfd857842271d132d04623452c94 |
refs/heads/master | <repo_name>reivax0z/interview-prep<file_sep>/src/main/java/reivax/norac/interviewprep/webapp/Entry.java
package reivax.norac.interviewprep.webapp;
public class Entry {
private String question;
private long timeout;
public Entry(){
}
public Entry(String question){
this.question = question;
}
public Entry(String question, long timeout){
this.question = question;
this.timeout = timeout;
}
@Override
public boolean equals(Object o){
return o instanceof Entry && ((Entry)o).getQuestion().equals(this.getQuestion());
}
@Override
public int hashCode(){
return this.question.hashCode();
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
}
<file_sep>/src/main/java/reivax/norac/interviewprep/webapp/QuestionsServlet.java
package reivax.norac.interviewprep.webapp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QuestionsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public QuestionsServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processData(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processData(request, response);
}
private void processData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(Model.getInstance().getCurrentQuestionsList() == null
|| Model.getInstance().getCurrentQuestionsList().isEmpty()){
List<Entry> questions = new ArrayList<Entry>();
questions.add(new Entry("Why did you choose our company?", 120));
questions.add(new Entry("Why working in consulting?"));
questions.add(new Entry("Any extracurricular activity?", 60));
questions.add(new Entry("Where do you see yourself in 3 years from now?"));
questions.add(new Entry("What do you expect from the first year in our company?"));
questions.add(new Entry("What core value of our company describes you the most accurately?", 60));
questions.add(new Entry("What is your most recent major achievement?", 180));
questions.add(new Entry("What is your weakness?", 60));
questions.add(new Entry("What is your best quality?", 60));
questions.add(new Entry("Give me an example where you used your good relationship with your previous employer?"));
questions.add(new Entry("Tell me about a time you showed leadership"));
questions.add(new Entry("Tell me about a time you showed courage", 90));
questions.add(new Entry("Tell me about a challenging situation you successfully overtook", 120));
questions.add(new Entry("Tell me about a failure you faced. How did you fix it?"));
questions.add(new Entry("Tell me about a time when you worked under pressure?"));
Model.getInstance().setCurrentQuestionsList(questions);
}
List<Entry> questions = Model.getInstance().getCurrentQuestionsList();
Collections.shuffle(questions);
// Forward the info to the appropriate JSP
request.setAttribute("questions", questions);
request.getRequestDispatcher("DisplayQuestions.jsp").forward(request, response);
}
}
| 5b38aed8c11df4049ff86ced264546272e6c0402 | [
"Java"
] | 2 | Java | reivax0z/interview-prep | c0e0b402fe65f1159a8e39b379b3d08dabfab7c5 | bdffd3dab166f4b9cb93b6dc3eadf52adab331d7 |
refs/heads/master | <repo_name>ozzyjohnson/chef-bcpc<file_sep>/vbox_save.sh
#!/bin/bash
for i in `seq 1 3`; do
VBoxManage snapshot bcpc-vm$i take initial-install
done
<file_sep>/vbox_restore.sh
#!/bin/bash
for i in `seq 1 3`; do
VBoxManage controlvm bcpc-vm$i poweroff
VBoxManage snapshot bcpc-vm$i restore initial-install
vagrant ssh -c "cd chef-bcpc && knife client delete -y bcpc-vm$i.local.lan" || true
vagrant ssh -c "cd chef-bcpc && knife node delete -y bcpc-vm$i.local.lan" || true
VBoxManage startvm bcpc-vm$i
done
| d83f7122902efb97d184095e8f40bf3060d61de3 | [
"Shell"
] | 2 | Shell | ozzyjohnson/chef-bcpc | e9062beb8dd323b869b4c6c2b44167336f1e051f | 8b730959ffd1fec64b72d192b153f26d9f0442be |
refs/heads/master | <file_sep>compile: P1.c
gcc -std=c99 -pthread P1.c -o ThreadHello
run:
./ThreadHello
clean:
rm ./ThreadHello
<file_sep>#include <stdio.h>
#include <stdlib.h> // exit function
#include <pthread.h>
void * print_hello(void * args)
{
printf("Hello world, from the 2nd thread!\n");
}
int main()
{
pthread_t HelloWorld;
int tret; // will be used to accumulate value returned by some pthread_function()
if (tret = pthread_create(&HelloWorld, NULL, print_hello, NULL))
{
fprintf(stderr,"Error from pthread_create(). Returned %i instead of 0.", tret); // error code display
exit(EXIT_FAILURE);
}
if (tret = pthread_join(HelloWorld, NULL)) // joins back the pthread
{
fprintf(stderr, "Error from pthread_join(). Returned %i instead of 0.", tret); // error code display
exit(EXIT_FAILURE);
}
return 0;
}
| 540075f3a49d745f5a21104dab93841c5f763435 | [
"C",
"Makefile"
] | 2 | Makefile | oskariot/SO-Pracownia1 | e33ecfe697dd935cb88da6f08919c35e2b5a7ee5 | 18d7295b180950a38a979bbcc197e6b69624425f |
refs/heads/master | <repo_name>insane-dreamer/retrospectiva<file_sep>/extensions/agile_pm/lib/goals_controller.rb
#--
# Copyright (C) 2009 <NAME>
# Please read LICENSE document for more information.
#++
class GoalsController < ProjectAreaController
retrospectiva_extension('agile_pm')
menu_item :goals do |i|
i.label = N_('Goals')
i.rank = 300
i.path = lambda do |project|
project_goals_path(project)
end
end
require_permissions :goals,
:view => ['home', 'index', 'show'],
:create => ['new', 'create'],
:update => ['edit', 'update'],
:delete => ['destroy']
before_filter :find_milestone, :except => [:home]
before_filter :find_goal_associations, :only => [:new, :edit]
before_filter :find_goal, :only => [:show, :edit, :update, :destroy]
helper_method :sprint_location
def home
@milestone = Project.current.milestones.in_order_of_relevance.first
if @milestone.present?
redirect_to project_milestone_goals_path(Project.current, @milestone)
else
render :action => 'no_milestones'
end
end
def index
@milestones = Project.current.milestones.in_default_order.all
@current_sprint = @milestone.sprints.in_order_of_relevance.first
@goals = @milestone.goals.group_by(&:sprint)
respond_to do |format|
format.html
format.xml { render :xml => @goals.values.flatten }
end
end
def show
respond_to do |format|
format.html # show.html.erb
format.js # show.js.rjs
format.xml { render :xml => @goal }
end
end
def new
@goal = @milestone.goals.new(:sprint_id => params[:sprint_id], :requester_id => User.current.id)
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @goal }
end
end
def create
@goal = @milestone.goals.new(params[:goal])
respond_to do |format|
if @goal.save
flash[:notice] = _('Goal was successfully created.')
format.html { redirect_to sprint_location }
format.xml { render :xml => @goal, :status => :created, :location => sprint_location }
else
format.html { find_goal_associations; render :action => "new" }
format.xml { render :xml => @goal.errors, :status => :unprocessable_entity }
end
end
end
def edit
end
def update
respond_to do |format|
if @goal.update_attributes(params[:goal])
flash[:notice] = _('Goal was successfully updated.')
format.html { redirect_to sprint_location }
format.xml { head :ok }
else
format.html { find_goal_associations; render :action => "edit" }
format.xml { render :xml => @goal.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@goal.destroy
flash[:notice] = _('Goal was successfully deleted.')
respond_to do |format|
format.html { redirect_to project_milestone_goals_path(Project.current, @milestone) }
format.xml { head :ok }
end
end
private
def sprint_location
hash = @goal.sprint ? @goal.sprint.title.parameterize : 'unassigned'
project_milestone_goals_path(Project.current, @milestone, :anchor => hash )
end
def find_milestone
@milestone = Project.current.milestones.find params[:milestone_id],
:include => [:sprints, :goals],
:order => 'goals.priority_id DESC, goals.title'
end
def find_goal_associations
@sprints = @milestone.sprints.all(:order => 'starts_on, finishes_on')
@users = Project.current.users.with_permission(:goals, :view)
end
def find_goal
@goal = @milestone.goals.find(params[:id], :include => [:sprint])
end
end
<file_sep>/extensions/agile_pm/spec/models/goal_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Goal do
fixtures :milestones, :projects, :users, :goals, :sprints
it 'should belong to milestone' do
goals(:must_have).should belong_to(:milestone)
end
it 'should belong to sprint' do
goals(:must_have).should belong_to(:sprint)
end
it 'should belong to requester' do
goals(:must_have).should belong_to(:requester)
end
it 'should validate presence of title' do
goals(:must_have).should validate_presence_of(:title)
end
it 'should validate presence of milestone' do
goals(:must_have).should validate_association_of(:milestone)
end
it 'should validate presence of priority' do
goals(:must_have).priority_id = 50
goals(:must_have).should have(1).error_on(:priority_id)
end
it 'should ensure that sprint and milestone are matching' do
goals(:must_have).milestone = milestones(:completed)
goals(:must_have).should have(1).error_on(:sprint_id)
end
describe 'on create' do
before do
User.stub!(:current).and_return(users(:worker))
end
def new_goal(options = {})
@goal ||= Goal.new(options)
end
it 'should assign the currently logged-in user as requester' do
new_goal.valid?
new_goal.requester.should == users(:worker)
end
it 'should allow to have explicit requesters' do
new_goal( :requester_id => users(:creator).id )
new_goal.valid?
new_goal.requester.should == users(:creator)
end
end
end
<file_sep>/extensions/agile_pm/models/goal.rb
#--
# Copyright (C) 2009 <NAME>
# Please read LICENSE document for more information.
#++
class Goal < ActiveRecord::Base
belongs_to :milestone
belongs_to :sprint
belongs_to :requester, :class_name => 'User'
Priority = Struct.new(:id, :name)
cattr_reader :priorities
@@priorities = [
Priority.new(1, N_("Won't have")),
Priority.new(2, N_("Could have")),
Priority.new(3, N_("Should have")),
Priority.new(4, N_("Must have"))
].freeze
validates_presence_of :title
validates_association_of :milestone
validates_inclusion_of :priority_id, :in => priorities.map(&:id)
attr_accessible :title, :description, :sprint_id, :priority_id, :requester_id
def priority
priorities[priority_id - 1]
end
protected
def before_validation_on_create
self.requester_id ||= User.current.id unless User.current.public?
true
end
def validate
if sprint and milestone and sprint.milestone != milestone
errors.add :sprint_id, :invalid
end
errors.empty?
end
end
<file_sep>/extensions/agile_pm/ext_info.rb
#--
# Copyright (C) 2009 <NAME>
# Please read LICENSE document for more information.
#++
RetroAM.permission_map do |map|
permitted_and_non_public = lambda { |project, user, has_permission, *records|
has_permission and not user.public?
}
map.resource :goals, :label => N_('Goals') do |stories|
stories.permission :view, :label => N_('View')
stories.permission :create, :label => N_('Create')
stories.permission :update, :label => N_('Update')
stories.permission :delete, :label => N_('Delete')
end
map.resource :sprints, :label => N_('Sprints') do |sprints|
sprints.permission :create, :label => N_('Create')
sprints.permission :update, :label => N_('Update')
sprints.permission :delete, :label => N_('Delete')
end
map.resource :stories, :label => N_('Stories') do |stories|
stories.permission :view, :label => N_('View')
stories.permission :stories, :label => N_('Create'), &permitted_and_non_public
stories.permission :update, :label => N_('Update'), &permitted_and_non_public
stories.permission :delete, :label => N_('Delete')
stories.permission :modify, :label => N_('Modify'), &permitted_and_non_public
end
end
<file_sep>/lib/retrospectiva/task_manager/parser.rb
module Retrospectiva
class TaskManager
class Parser
attr_accessor :last_comment, :tasks, :files
def initialize
@last_comment = ''
@tasks = []
@files = Dir["#{RAILS_ROOT}/extensions/**/tasks/**/ext_retro_tasks.rake"] +
Dir["#{RAILS_ROOT}/lib/tasks/**/core_retro_tasks.rake"]
@files.each do |file|
instance_eval(File.read(file))
end
@tasks = @tasks.sort_by(&:name)
end
def namespace(name = nil, &block)
yield if name == :retro
end
def task(*args)
key = if args.first.is_a?(Hash)
args.first.keys.first
else
args.first
end
entry = Task.find_or_create_by_name(key.to_s)
entry.description = last_comment
self.tasks << entry
end
def desc(comment = '')
self.last_comment = comment
end
end
end
end
<file_sep>/extensions/retro_wiki/lib/wiki_engine_extensions.rb
module WikiEngine
class << self
def parse_wiki_word_link(match_data, &block)
engine = select_engine(engine)
engine.blank? ? match_data[0] : supported_engines[engine].parse_wiki_word_link(match_data, &block)
end
def wiki_word_pattern(engine = nil)
engine = select_engine(engine)
engine.blank? ? %r{} : supported_engines[engine].wiki_word_pattern
end
end
class AbstractEngine
WIKI_WORD_PATTERN = /
\[\[
(?:(F|I)[|:])?
(\\?\w[ \w-]+)
(?:[|:]([A-Za-z].+?))?
(?:[|:](\d+(?:x|\W*\#215\W?)\d+))?
\]\]
/x.freeze unless const_defined?(:WIKI_WORD_PATTERN)
def wiki_word_pattern
WIKI_WORD_PATTERN
end
def parse_wiki_word_link(match_data, &block)
prefix, page, title, size = extract_wiki_word_parts(match_data)
page = page.to_s.gsub(/ +/, ' ').strip
title = title.blank? ? page : title.strip
size = size ? size.sub(/\W+215\W/, 'x') : nil
page.starts_with?('\\') ? match_data[0].sub(/\\/, '') : yield(prefix, page, title, size)
end
def extract_wiki_word_parts(match_data)
match_data[-4..-1]
end
end
end
<file_sep>/extensions/agile_pm/models/story.rb
class Story < ActiveRecord::Base
belongs_to :sprint
belongs_to :goal
belongs_to :creator, :class_name => 'User', :foreign_key => 'created_by'
belongs_to :assigned, :class_name => 'User', :foreign_key => 'assigned_to'
has_many :progress_updates,
:class_name => 'StoryProgressUpdate',
:order => 'story_progress_updates.created_on'
has_many :events,
:class_name => 'StoryEvent',
:order => 'story_events.created_at'
has_many :status_updates,
:class_name => 'StoryStatusUpdate',
:order => 'story_events.created_at'
has_many :comments,
:class_name => 'StoryComment',
:order => 'story_events.created_at'
has_many :revisions,
:class_name => 'StoryRevision',
:order => 'story_events.created_at'
validates_length_of :title, :in => 1..160
validates_length_of :description, :maximum => 5000, :allow_nil => true
validates_association_of :sprint, :creator
validates_numericality_of :estimated_hours,
:integer_only => true,
:greater_than_or_equal_to => 0
validates_numericality_of :revised_hours,
:integer_only => true,
:greater_than_or_equal_to => 0
attr_accessible :title, :description, :estimated_hours, :goal_id
named_scope :active,
:conditions => ['started_at IS NOT NULL AND completed_at IS NULL AND assigned_to IS NOT NULL']
named_scope :pending,
:conditions => ['started_at IS NULL OR assigned_to IS NULL']
named_scope :completed,
:conditions => ['completed_at IS NOT NULL']
named_scope :in_default_order,
:include => [:goal],
:order => "CASE goals.priority_id WHEN NULL THEN 0 ELSE goals.priority_id END DESC, stories.created_at"
def percent_completed
progress_updates.last ? progress_updates.last.percent_completed : 0
end
def started?
started_at.present?
end
def pending?
not started? or not assigned?
end
def orphanned?
started? and not assigned?
end
def completed?
completed_at.present?
end
def assigned?
assigned.present?
end
def in_progress?
started? and assigned? and not completed?
end
alias_method :active?, :in_progress?
def assigned_to?(user)
assigned == user
end
def accept!(user = User.current)
self.assigned = user
self.started_at ||= Time.zone.now
end
def complete!(user = User.current)
self.assigned = user
self.completed_at = Time.zone.now
end
def reopen!(user = User.current)
self.assigned = user
self.completed_at = nil
end
def remaining_hours(date)
revised_hours * (100 - progress_index[date]) / 100.0
end
def progress_index
@progress_index ||= ProgressIndex.new(progress_updates)
end
def status_on(date)
if started_at.nil? or date < started_at.to_date
:pending
elsif completed_at.present? and date > completed_at.to_date
:completed
else
:active
end
end
protected
class ProgressIndex < ActiveSupport::OrderedHash
def initialize(progress_updates)
super()
progress_updates.each do |update|
self[update.created_on] = update.percent_completed
end
end
protected
def default(key)
return 0 unless key.is_a?(Date)
next_key = keys.sort.select {|i| i < key }.last
next_key.nil? ? 0 : self[next_key]
end
end
def before_validation_on_create
self.created_by = User.current.public? ? nil : User.current.id
self.revised_hours = self.estimated_hours
true
end
def before_validation_on_update
self.revised_hours = self.revised_hours.to_i < 0 ? 0 : self.revised_hours.to_i
true
end
def before_update
if completed_at_changed? and completed?
if percent_completed < 100
progress_updates.update_or_create(Time.zone.today, 100)
end
status_updates.record! :completed, assigned
elsif completed_at_changed? and not completed?
status_updates.record! :re_opened, assigned
end
if assigned_to_changed?
status_updates.record! :accepted, assigned
end
if revised_hours_changed?
revisions.create :hours => revised_hours
end
true
end
end
<file_sep>/extensions/agile_pm/spec/controllers/goals_controller_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe GoalsController do
it_should_behave_like EveryProjectAreaController
before do
@milestone = mock_model(Milestone)
@milestones = [@milestone]
@milestones.stub!(:in_default_order).and_return(@milestones)
@milestones.stub!(:in_order_of_relevance).and_return(@milestones)
@milestones.stub!(:all).and_return(@milestones)
@milestones.stub!(:find).with('1', :include=>[:sprints, :goals], :order=>"goals.priority_id DESC, goals.title").and_return(@milestone)
@sprint = mock_model(Sprint, :title => 'Sprint 1')
@sprints = [@sprint]
@sprints.stub!(:in_order_of_relevance).and_return(@sprints)
@sprints.stub!(:all).and_return(@sprints)
@goal = mock_model(Goal, :sprint => @sprint)
@goals = [@goal]
@goals.stub!(:find).with('37', :include => [:sprint]).and_return(@goal)
@user = mock_model(User)
@users = [@user]
@users.stub!(:with_permission).and_return(@users)
@milestone.stub!(:sprints).and_return(@sprints)
@milestone.stub!(:goals).and_return(@goals)
@project = permit_access_with_current_project! :milestones => @milestones, :users => @users, :name => 'Retrospectiva'
end
class << self
def it_assigns_the_milestone(method = :do_get)
it "assigns milestone as @milestone" do
@milestones.should_receive(:find).with('1', :include=>[:sprints, :goals], :order=>"goals.priority_id DESC, goals.title").and_return(@milestone)
send(method)
assigns[:milestone].should == @milestone
end
end
end
describe "GET home" do
def do_get
get :home, :project_id => 'retro'
end
it "assigns current milestone as @milestone" do
@milestones.should_receive(:in_order_of_relevance).and_return(@milestones)
do_get
assigns[:milestone].should == @milestone
end
it "redirects to milestone if found" do
@milestones.stub!(:in_order_of_relevance).and_return(@milestones)
do_get
response.should redirect_to(project_milestone_goals_path(Project.current, @milestone))
end
it "show no-milestone page if not milestone is found" do
@milestones.stub!(:in_order_of_relevance).and_return([])
do_get
response.should render_template(:no_milestones)
end
end
describe "GET index" do
def do_get
get :index, :project_id => 'retro', :milestone_id => '1'
end
it_assigns_the_milestone
it "assigns all milestones as @milestones" do
@milestones.should_receive(:in_default_order).and_return(@milestones)
do_get
assigns[:milestones].should == @milestones
end
it "assigns current sprint as @current_sprint" do
do_get
assigns[:current_sprint].should == @sprint
end
it "assigns all goals indexed as @goals" do
do_get
assigns[:goals].should == { @sprint => [@goal] }
end
end
describe "GET show" do
def do_get
get :show, :project_id => 'retro', :milestone_id => '1', :id => '37'
end
it_assigns_the_milestone
it "assigns the requested goal as @goal" do
@goals.should_receive(:find).with("37", {:include=>[:sprint]}).and_return(@goal)
do_get
assigns[:goal].should equal(@goal)
end
end
describe "GET new" do
before do
@new_goal = stub_model(Goal)
@goals.stub!(:new).and_return(@new_goal)
end
def do_get
get :new, :project_id => 'retro', :milestone_id => '1', :sprint_id => '37'
end
it_assigns_the_milestone
it "assigns a new goal as @goal" do
@goals.should_receive(:new).with(:requester_id=>0, :sprint_id=>'37').and_return(@new_goal)
do_get
assigns[:goal].should equal(@new_goal)
end
end
describe "GET edit" do
def do_get
get :edit, :project_id => 'retro', :milestone_id => '1', :id => '37'
end
it_assigns_the_milestone
it "assigns the requested goal as @goal" do
@goals.should_receive(:find).with("37", {:include=>[:sprint]}).and_return(@goal)
do_get
assigns[:goal].should equal(@goal)
end
end
describe "POST create" do
def do_post
post :create, :project_id => 'retro', :milestone_id => '1', :goal => {:these => 'params'}
end
describe "with valid params" do
before do
@goal.stub!(:save).and_return(true)
end
it "assigns a newly created goal as @goal" do
@goals.stub!(:new).with({'these' => 'params'}).and_return(@goal)
do_post
assigns[:goal].should equal(@goal)
end
it "redirects to the created goal" do
@goals.stub!(:new).and_return(@goal)
do_post
response.should redirect_to(project_milestone_goals_path(@project, @milestone, :anchor => 'sprint-1'))
end
end
describe "with invalid params" do
before do
@goal.stub!(:save).and_return(false)
end
it "assigns a newly created but unsaved goal as @goal" do
@goals.stub!(:new).with({'these' => 'params'}).and_return(@goal)
do_post
assigns[:goal].should equal(@goal)
end
it "re-renders the 'new' template" do
@goals.stub!(:new).and_return(@goal)
do_post
response.should render_template('new')
end
end
end
describe "PUT update" do
before do
@goal.stub!(:update_attributes).and_return(true)
end
def do_put
put :update, :project_id => 'retro', :milestone_id => '1', :id => "37", :goal => {:these => 'params'}
end
describe "with valid params" do
it "assigns the requested goal as @goal" do
@goals.should_receive(:find).with("37", {:include=>[:sprint]}).and_return(@goal)
do_put
assigns[:goal].should equal(@goal)
end
it "updates the requested goal and redirect" do
@goals.stub!(:find).and_return(@goal)
@goal.should_receive(:update_attributes).with({'these' => 'params'}).and_return(true)
do_put
response.should redirect_to(project_milestone_goals_path(@project, @milestone, :anchor => 'sprint-1'))
end
end
describe "with invalid params" do
it "assigns the requested goal as @goal" do
@goals.should_receive(:find).with("37", {:include=>[:sprint]}).and_return(@goal)
do_put
assigns[:goal].should equal(@goal)
end
it "re-renders the 'edit' template" do
@goals.stub!(:find).and_return(@goal)
@goal.should_receive(:update_attributes).with({'these' => 'params'}).and_return(false)
do_put
response.should render_template('edit')
end
end
end
describe "DELETE destroy" do
def do_delete
delete :destroy, :project_id => 'retro', :milestone_id => '1', :id => '37'
end
it "destroys the requested goal" do
@goals.should_receive(:find).with("37", {:include=>[:sprint]}).and_return(@goal)
@goal.should_receive(:destroy)
do_delete
end
it "redirects to the goals list" do
@goal.stub!(:destroy)
do_delete
response.should redirect_to(project_milestone_goals_path(@project, @milestone))
end
end
end
| f2bf6d5bd882cd1fae9a6aef547494d9be91f17b | [
"Ruby"
] | 8 | Ruby | insane-dreamer/retrospectiva | 37846005dd5e56c8dcfb4cd306b62b030b34486f | 2ea3a82a9ce6d16e06c92528bc346cfb37ee0fa6 |
refs/heads/main | <repo_name>jafarov01/Matrix-Multiplication<file_sep>/matrixMultiplication.cpp
/*
* Integer Matrix Multiplication Program
* Copyright <NAME>
* 10/29/2021
*/
#include <iostream>
#include <vector>
using namespace std;
/*function prototypes*/
bool fill(vector<vector<int>>& A, vector<vector<int>>& B);
vector<vector<int>> multiplication(vector<vector<int>> A, vector<vector<int>> B);
int main()
{
vector<vector<int>> A; //matrix A
vector<vector<int>> B; //matrix B
vector<vector<int>> result; //result of multiplication
bool resultFillFunction;
//function call for input
do
{
resultFillFunction = fill(A, B);
} while (!resultFillFunction);
//performing the multiplication
result = multiplication(A, B);
//printing the result
cout << "\n\n-----------------\nResult of the multiplication: \n\n";
for (int i = 0; i < result.size(); i++)
{
for (int j = 0; j < result[0].size(); j++)
{
cout << result[i][j] << " ";
}
cout << endl;
}
cout << "\n-----------------\n";
return (0);
}
bool fill(vector<vector<int>>& A, vector<vector<int>>& B)
{
int rowA, columnA; //row and column sizes for matrix A
int rowB, columnB; //row and column sizes for matrix B
int input;
cout << "Matrix A: " << endl;
cout << "--> Row: ";
cin >> rowA;
cout << "--> Column: ";
cin >> columnA;
cout << endl << "Matrix B:" << endl;
cout << "--> Row: ";
cin >> rowB;
cout << "--> Column: ";
cin >> columnB;
if (columnA != rowB)
{
cout << "\ncolumnA and rowB must be the same size!\n\n";
cout << "------------------\n\n";
return 0;
}
cout << "\n-------------\n\n";
for (int i = 0; i < rowA; i++)
{
vector<int> tmp; //temporary vector to push back into the actual vector
for (int j = 0; j < columnA; j++)
{
cout << "A(" << i << ", " << j << "): ";
cin >> input;
tmp.push_back(input);
}
A.push_back(tmp);
tmp.clear(); //clearing the vector tmp
}
cout << "\n-------------\n\n";
for (int i = 0; i < rowB; i++)
{
vector<int> tmp; //temporary vector to push back into the actual vector
for (int j = 0; j < columnB; j++)
{
cout << "B(" << i << ", " << j << "): ";
cin >> input;
tmp.push_back(input);
}
B.push_back(tmp);
tmp.clear(); //clearing the vector tmp
}
return 1;
}
vector<vector<int>> multiplication(vector<vector<int>> A, vector<vector<int>> B)
{
vector<vector<int>> result;
int sum = 0;
for (int rowA = 0; rowA < A.size(); rowA++)
{
vector<int> tmp;
for (int colB= 0; colB < B[0].size(); colB++)
{
for (int colArowB = 0; colArowB < A[0].size(); colArowB++)
{
sum += A[rowA][colArowB] * B[colArowB][colB];
}
tmp.push_back(sum);
sum = 0;
}
result.push_back(tmp);
tmp.clear();
}
return result;
}
<file_sep>/README.md
# Matrix-Multiplication
Integer Matrix Multiplication Program in C++
| b5d496c8ff62416c34216db97d377127965d4558 | [
"Markdown",
"C++"
] | 2 | C++ | jafarov01/Matrix-Multiplication | b1090f9a5b5f00bf5a573eb3963f74d68eef219c | 6fa7120e63888a2ab625675423a5909d35b99cf7 |
refs/heads/master | <repo_name>SanjinKurelic/MeetingInfoWPF<file_sep>/MeetingInfoWPF/Service/SelectedDateService.cs
using MeetingInfoWPF.Model;
using MeetingInfoWPF.ViewModel;
using System;
namespace MeetingInfoWPF.Service
{
class SelectedDateService
{
private static SelectedDateVM selectedDateVM;
public static SelectedDateVM GetSelectedDateVM()
{
if (selectedDateVM == null)
{
selectedDateVM = new SelectedDateVM(new SelectedDate
{
CurrentDate = DateTime.Now
});
}
return selectedDateVM;
}
}
}
<file_sep>/MeetingInfoWPF/ViewModel/MeetingVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MeetingInfoWPF.ViewModel
{
class MeetingVM
{
public int MeetingId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int RowIndex { get; set; }
public int ColumnIndex { get; set; }
}
}
<file_sep>/MeetingInfoWPF/View/Components/WeekPlaner.xaml.cs
using MeetingInfoDatabase.Models;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using MeetingInfoWPF.ViewModel;
using MeetingInfoWPF.View.Forms;
namespace MeetingInfoWPF.View.Components
{
public partial class WeekPlaner : UserControl
{
private const int HOUR_PADDING = 8;
private const int DAY_PADDING = 1;
public static readonly DependencyProperty CurrentDateDependency = DependencyProperty.Register("CurrentDate", typeof(DateTime), typeof(WeekPlaner),
new FrameworkPropertyMetadata(DateTime.Now, new PropertyChangedCallback(OnCurrentDateChange)));
private DateTime _currentTime = DateTime.Now;
public WeekPlaner()
{
InitializeComponent();
}
private int GetRowIndex(DateTime date)
{
return date.TimeOfDay.Hours - HOUR_PADDING;
}
private int GetColumnIndex(DateTime date)
{
return (int)date.DayOfWeek - DAY_PADDING;
}
private void RefillMeetings()
{
ObservableCollection<MeetingVM> meetings = new ObservableCollection<MeetingVM>();
foreach(Meeting meeting in App.Repository.GetMeetingsTable().GetMeetings(CurrentDate))
{
meetings.Add(new MeetingVM()
{
Title = meeting.Title,
Description = meeting.Description,
RowIndex = GetRowIndex(meeting.Date),
ColumnIndex = GetColumnIndex(meeting.Date),
MeetingId = meeting.IDMeeting
});
}
weekList.ItemsSource = meetings;
}
public DateTime CurrentDate {
get { return _currentTime; }
set { _currentTime = (DateTime)GetValue(CurrentDateDependency); RefillMeetings(); }
}
private static void OnCurrentDateChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((WeekPlaner)d).CurrentDate = (DateTime)e.NewValue;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
RefillMeetings();
}
private void EditMenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem menuItem = sender as MenuItem;
if(menuItem == null)
{
return;
}
StackPanel meeting = menuItem.CommandTarget as StackPanel;
if(meeting == null)
{
return;
}
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Meeting = App.Repository.GetMeetingsTable().GetMeeting((int)meeting.Tag);
meetingInfo.MeetingType = MeetingInfo.TYPE.EDIT_MEETING;
if(meetingInfo.ShowDialog() == true)
{
if(App.Repository.GetMeetingsTable().ChangeMeeting(meetingInfo.Meeting))
{
RefillMeetings();
MessageBox.Show(Properties.Resources.SuccessDescription, Properties.Resources.SuccessTitle, MessageBoxButton.OK);
} else
{
MessageBox.Show(Properties.Resources.ErrorDescription, Properties.Resources.ErrorTitle, MessageBoxButton.OK);
}
}
}
private void RemoveMenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem menuItem = sender as MenuItem;
if (menuItem == null)
{
return;
}
StackPanel meeting = menuItem.CommandTarget as StackPanel;
if (meeting == null)
{
return;
}
if (MessageBox.Show(Properties.Resources.ConfirmDescription, Properties.Resources.ConfirmTitle, MessageBoxButton.OK) == MessageBoxResult.OK)
{
if(App.Repository.GetMeetingsTable().RemoveMeeting((int)meeting.Tag))
{
RefillMeetings();
} else
{
MessageBox.Show(Properties.Resources.ErrorDescription, Properties.Resources.ErrorTitle, MessageBoxButton.OK);
}
}
}
private void ContentItem_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
StackPanel item = sender as StackPanel;
if(item == null)
{
return;
}
int meetingId = (int)item.Tag;
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Meeting = App.Repository.GetMeetingsTable().GetMeeting(meetingId);
meetingInfo.MeetingType = MeetingInfo.TYPE.VIEW_MEETING;
meetingInfo.ShowDialog();
}
}
}
<file_sep>/MeetingInfoWPF/ViewModel/MeetingInfoVM.cs
using MeetingInfoDatabase.Models;
using System.ComponentModel;
namespace MeetingInfoWPF.ViewModel
{
class MeetingInfoVM : INotifyPropertyChanged
{
private Meeting _meeting;
private Client _client;
public Meeting Meeting {
get { return _meeting; }
set {
_meeting = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Meeting"));
}
}
public Client Client {
get { return _client; }
set {
_client = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Client"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
<file_sep>/README.md
# Meeting Info
Meeting Info is the program for scheduling meetings. The main part of the program is a calendar with ability to add, update or remove meeting with a specific client. The program is written in C# using Windows Presentation Foundation (WPF) technology for Microsoft Windows operating system. This project is also available in several other technologies:
- [Windows Forms](https://github.com/SanjinKurelic/MeetingInfoWinForms)
- WPF (current one)
- [Web Forms](https://github.com/SanjinKurelic/MeetingInfoWebForms)
- [ASP. NET MVC](https://github.com/SanjinKurelic/MeetingInfoMVC)
## Getting started
### Prerequisites
For running the project you need to have the following items:
- Visual Studio 2017 or newer
- SQL Server 2017 or newer
- .NET Framework 4.6.1 or newer
- *MeetingInfoDatabase*
**Notice:** Project might run on the older .NET Framework or using older Visual Studio/SQL Server version, with or without additional tweaks.
### Installig
Install Visual Studio - include the .NET Framework and Windows Presentation Foundation (WPF) library. Download the *MeetingInfoDatabase* NuGet package from *MeetingInfoDatabase* project (**NuGet package is located in "packed" folder**):
https://github.com/SanjinKurelic/MeetingInfoDatabase
From the same repository, download file **Database.sql**. Install SQL Server and create **"sa"** user with the following values:
database username: **sa**<br>
database password: **SQL**
**Note:** It is discouraged to use **"sa"** account for application-database connection, so it is preferable to create the new user for this project. If you create different user, you need to change connection strings in the project configuration file:
```
MeetingInfoWPF > MeetingInfoWPF > App.config
```
**Run Database.sql script and create required database tables on SQL Server.**
Open Visual Studio and clone this repository to your computer. Open NuGet shell and install the *MeetingInfoDatabase* package by using the following command:
```
Install-Package MeetingInfoDatabase -Source <path_to_package>
```
**Before running the project install fonts located in "fonts" directory.**
### Running
When you run the project, you should be presented with the following screen.

The main screen shows all the meetings for a current week. By selecting year, month and week in the upper left corner, the user can view his or her meetings for a given week. By right clicking on the meeting, the user can edit or remove selected meeting. If the user double clicks the meeting, he or she will be presented with a window with more information about the meeting.

In the upper right corner of the main screen there are three buttons: *"new meeting"* button, *"print"* button and *"change language"* button. By clicking on the *"new meeting"* button, dialog box will open and ask the user information about the meeting: date, time, title, description, place and the meeting client. The program offers list of available clients who are stored in the database. **All fields are required and the user can't have 2 meetings on the same day**.

Middle button on the upper right corner is the *"print"* button, which allow the user to print the meetings of a current week (as shown on below image).

There are 2 available languages for this project: English and Croatian. The user can change language by clicking the *"change language"* button (the globe icon).
## Licence
See the LICENSE file. For every question write to <EMAIL>
<file_sep>/MeetingInfoWPF/View/Forms/MeetingWindow.xaml.cs
using MeetingInfoDatabase.Models;
using MeetingInfoWPF.Service;
using MeetingInfoWPF.ViewModel;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
namespace MeetingInfoWPF.View.Forms
{
public partial class MainWindow : Window
{
private SelectedDateVM SelectedDate;
private List<CultureInfo> languagesList;
public MainWindow()
{
languagesList = new List<CultureInfo>();
languagesList.Add(new CultureInfo("hr"));
languagesList.Add(new CultureInfo("en"));
// Center Window
WindowStartupLocation = WindowStartupLocation.CenterScreen;
// Set language
CultureInfo currentLanguage = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName);
System.Threading.Thread.CurrentThread.CurrentUICulture = currentLanguage;
System.Threading.Thread.CurrentThread.CurrentCulture = currentLanguage;
// Initialize components
InitializeComponent();
}
private void Button_Year_Up_Click(object sender, RoutedEventArgs e)
{
SelectedDate.DateYear++;
}
private void Button_Year_Down_Click(object sender, RoutedEventArgs e)
{
SelectedDate.DateYear--;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SelectedDate = SelectedDateService.GetSelectedDateVM();
DataContext = SelectedDate;
}
private void Month_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedDate.DateMonth = currentMonth.SelectedIndex;
}
private void Add_Meeting_Click(object sender, RoutedEventArgs e)
{
MeetingInfo meeting = new MeetingInfo();
meeting.MeetingType = MeetingInfo.TYPE.ADD_MEETING;
Meeting m = new Meeting();
m.Date = SelectedDate.CurrentDate;
meeting.Meeting = m;
if (meeting.ShowDialog() == true)
{
if (App.Repository.GetMeetingsTable().AddMeeting(meeting.Meeting))
{
SelectedDate.CurrentDate = meeting.Meeting.Date;
MessageBox.Show(Properties.Resources.SuccessDescription, Properties.Resources.SuccessTitle, MessageBoxButton.OK);
}
else
{
MessageBox.Show(Properties.Resources.ErrorDescription, Properties.Resources.ErrorTitle, MessageBoxButton.OK);
}
}
}
private void Print_Click(object sender, RoutedEventArgs e)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
printDialog.PrintVisual(weekPlaner, Title);
}
}
private void ChangeLanguage()
{
CultureInfo currentLanguage = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName);
CultureInfo newLanguage = languagesList.Find(language => language.TwoLetterISOLanguageName != currentLanguage.TwoLetterISOLanguageName);
System.Threading.Thread.CurrentThread.CurrentUICulture = newLanguage;
System.Threading.Thread.CurrentThread.CurrentCulture = newLanguage;
MainWindow mainWindow = new MainWindow();
Close();
mainWindow.Show();
}
private void Language_Click(object sender, RoutedEventArgs e)
{
ChangeLanguage();
}
}
}
<file_sep>/MeetingInfoWPF/View/Forms/MeetingInfo.xaml.cs
using MeetingInfoDatabase.Models;
using MeetingInfoWPF.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MeetingInfoWPF;
namespace MeetingInfoWPF.View.Forms
{
/// <summary>
/// Interaction logic for MeetingInfo.xaml
/// </summary>
public partial class MeetingInfo : Window
{
private MeetingInfoVM _infoVM;
private List<Client> _clients;
public enum TYPE { ADD_MEETING, EDIT_MEETING, VIEW_MEETING };
public TYPE MeetingType { get; set; } = TYPE.VIEW_MEETING;
public Meeting Meeting {
get { return _infoVM.Meeting; }
set {
_infoVM.Meeting = value;
clients.SelectedIndex = value.ClientID - 1;
}
}
public MeetingInfo()
{
InitializeComponent();
_infoVM = new MeetingInfoVM();
_clients = App.Repository.GetClientTable().GetClients();
// Center Window
WindowStartupLocation = WindowStartupLocation.CenterScreen;
DataContext = _infoVM;
clients.SelectedItem = _clients[0];
}
private void ShowButtons()
{
switch (MeetingType)
{
case TYPE.ADD_MEETING:
case TYPE.EDIT_MEETING:
btnClose.Visibility = Visibility.Collapsed;
break;
case TYPE.VIEW_MEETING:
btnSave.Visibility = Visibility.Collapsed;
btnCancel.Visibility = Visibility.Collapsed;
DisableInputFields();
break;
}
}
private void DisableInputFields()
{
UIElementCollection elements = ((Panel)Content).Children;
IEnumerable<Control> elementList = elements.Cast<FrameworkElement>().ToList().OfType<Control>();
foreach(Control control in elementList)
{
if(control is TextBox || control is ComboBox || control is DatePicker)
{
control.IsEnabled = false;
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
clients.ItemsSource = _clients;
ShowButtons();
}
private void clients_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_infoVM.Client = (Client)clients.SelectedItem;
_infoVM.Meeting.ClientID = _infoVM.Client.IDClient;
}
private bool RequiredFieldsEmpty()
{
return
string.IsNullOrWhiteSpace(_infoVM.Meeting.Title) ||
string.IsNullOrWhiteSpace(_infoVM.Meeting.Place) ||
string.IsNullOrWhiteSpace(_infoVM.Meeting.Description);
}
private bool IsDateReserved()
{
foreach(Meeting meeting in App.Repository.GetMeetingsTable().GetMeetings(_infoVM.Meeting.Date))
{
if (_infoVM.Meeting.Date == meeting.Date && _infoVM.Meeting.IDMeeting != meeting.IDMeeting)
{
return true;
}
}
return false;
}
private void Cancel_Button_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
private void Save_Button_Click(object sender, RoutedEventArgs e)
{
if(RequiredFieldsEmpty())
{
MessageBox.Show(Properties.Resources.RequiredFields, Properties.Resources.ErrorTitle, MessageBoxButton.OK);
return;
}
if(IsDateReserved())
{
MessageBox.Show(Properties.Resources.DateReserved, Properties.Resources.ErrorTitle, MessageBoxButton.OK);
return;
}
DialogResult = true;
Close();
}
private void hour_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox hours = sender as ComboBox;
if(hours == null || hours.SelectedValue == null)
{
return;
}
_infoVM.Meeting.Date = new DateTime(_infoVM.Meeting.Date.Year, _infoVM.Meeting.Date.Month, _infoVM.Meeting.Date.Day, int.Parse(hours.SelectedValue.ToString()), 0, 0);
}
}
}<file_sep>/MeetingInfoWPF/View/Components/CustomCalendar.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
namespace MeetingInfoWPF.View.Components
{
public partial class CustomCalendar : UserControl
{
public static readonly DependencyProperty SelectedDateDependency = DependencyProperty.Register("SelectedDate", typeof(DateTime), typeof(CustomCalendar),
new FrameworkPropertyMetadata(DateTime.Now, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnSelectedDateChange)));
private bool dateLock = false;
private void SelectWeek()
{
dateLock = true;
DateTime firstDay = SelectedDate.AddDays(DayOfWeek.Monday - SelectedDate.DayOfWeek);
calendar.SelectedDates.Clear();
for (int i = 0; i <= 6; i++)
{
calendar.SelectedDates.Add(firstDay.AddDays(i));
}
dateLock = false;
}
public DateTime SelectedDate {
get {
return (DateTime)GetValue(SelectedDateDependency);
}
set {
calendar.SelectedDate = value;
calendar.DisplayDate = value;
SelectWeek();
SetValue(SelectedDateDependency, value);
}
}
public CustomCalendar()
{
InitializeComponent();
}
private static void OnSelectedDateChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((CustomCalendar)d).SelectedDate = (DateTime)e.NewValue;
}
private void calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
if (dateLock)
{
return;
}
SelectedDate = calendar.SelectedDates[0];
}
}
}
<file_sep>/MeetingInfoWPF/App.xaml.cs
using MeetingInfoDatabase;
using System.Configuration;
using System.Windows;
namespace MeetingInfoWPF
{
public partial class App : Application
{
public static Repository Repository { get; private set; }
private static readonly string cs = ConfigurationManager.ConnectionStrings["cs"].ConnectionString;
public App()
{
Repository = new Repository(cs, MeetingInfoDatabase.DAO.DatabaseType.SqlHelper);
}
}
}
<file_sep>/MeetingInfoWPF/Model/SelectedDate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MeetingInfoWPF.Model
{
class SelectedDate
{
public DateTime CurrentDate { get; set; }
}
}
<file_sep>/MeetingInfoWPF/ViewModel/SelectedDateVM.cs
using MeetingInfoWPF.Model;
using System;
using System.ComponentModel;
namespace MeetingInfoWPF.ViewModel
{
class SelectedDateVM : INotifyPropertyChanged
{
private SelectedDate selectedDate;
public event PropertyChangedEventHandler PropertyChanged;
public SelectedDateVM(SelectedDate selectedDate)
{
this.selectedDate = selectedDate;
}
private DateTime GetDateTime(int year, int month)
{
//return new DateTime(year, month, 1);
DateTime dateTime = new DateTime(year, month, 1);
int daysToAdd = ((int)DayOfWeek.Monday - (int)dateTime.DayOfWeek + 7) % 7;
return dateTime.AddDays(daysToAdd);
}
public int DateYear {
get { return selectedDate.CurrentDate.Year; }
set {
if(selectedDate.CurrentDate.Year != value)
{
selectedDate.CurrentDate = GetDateTime(value, selectedDate.CurrentDate.Month);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(String.Empty));
}
}
}
public int DateMonth {
get { return selectedDate.CurrentDate.Month; }
set {
if (selectedDate.CurrentDate.Month != value)
{
selectedDate.CurrentDate = GetDateTime(selectedDate.CurrentDate.Year, value);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(String.Empty));
}
}
}
public DateTime CurrentDate {
get { return selectedDate.CurrentDate; }
set {
selectedDate.CurrentDate = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(String.Empty));
}
}
}
}
| 631d6af5271656399f795fdfff72abbe0349aa2b | [
"Markdown",
"C#"
] | 11 | C# | SanjinKurelic/MeetingInfoWPF | be4d20d8b34e673317bbeae54cf45d53a287bde0 | 04c24fec7a9377e1130353c50be418d173f7e60f |
refs/heads/master | <file_sep>import tensorflow as tf
from tensorflow.keras.losses import Loss, KLD, Reduction
class PacmanLoss(Loss):
def __init__(self, reduction=Reduction.NONE, name=None):
super().__init__(reduction=reduction, name=name)
def call(self, y_true, y_pred):
y_pred = ops.convert_to_tensor(y_pred)
y_true = math_ops.cast(y_true, y_pred.dtype)
return KLD(y_true, y_pred)
| 462a939e4c2b0b799f5e4bee16d3ce04514440e7 | [
"Python"
] | 1 | Python | ashwindharne/dummy-lossfunction-repo | ecf43be3e558955e107f795dbc235f187d323ee9 | d19a7e2be5b71f978d88101d849896de8ffa4c89 |
refs/heads/master | <file_sep>const vm = new Vue ({
el: '#app',
data: {
firstName: 'a',
lastName: 'b',
fullName2: 'a b'
},
computed: {
fullName1 () {
return this.firstName + ' ' + this.lastName
},
fullName3: {
get () {
// 計算並返回當前屬性的值
return this.firstName + ' ' + this.lastName
},
set (value) {
// 監視當前屬性值的變化
// 回傳當前的值 並更新
const names = value.split(' ')
this.firstName = value[0]
this.lastName = value[1]
}
}
},
watch: {
firstName: function (value) {
this.fullName2 = value + ' ' + this.lastName
}
}
})
vm.$watch('lastName', function (value) {
this.fullName2 = this.firstName + ' ' + value
})<file_sep>const vm = new Vue ({
el: '#app',
data: {
a: 'aClass',
isA: true,
isB: false,
activeColor: 'red',
fontSize: 20
},
methods: {
update () {
this.a = 'bClass',
this.isA = false,
this.isB = true,
this.activeColor = 'green',
this.fontSize = 40
}
}
})<file_sep>new Vue ({
el: '#app',
data () {
return {
username: '',
pwd: '',
sex:'女',
likes: ['basketball'],
allCities: [{id: 1, name: '台北'}, {id: 2, name: '新北市'}, {id: 3, name: '桃園'}],
cityId: '3',
desc: ''
}
},
methods: {
handlerSubmit () {
console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.desc)
}
}
})<file_sep>const vm = new Vue ({
el: '#app',
data: {
persons: [
{name: 'Tom', age: 18},
{name: 'Ben', age: 17},
{name: 'Alice', age: 16}
]
},
methods: {
deleteP (index) {
// 刪除 persons 中的 index
this.persons.splice(index, 1)
},
updateP (index, newP) {
this.persons.splice(index, 1, newP)
}
}
})<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>遍厲</title>
</head>
<body>
<div id="app">
<h2>測試 : v-for 遍厲陣列</h2>
<ul>
<li v-for="(p, index) in persons" :key="index">
{{ index }}-----{{ p.name }}----{{ p.age }}
----<button @click="deleteP(index)">刪除</button>
----<button @click="updateP(index, {name: 'Alex', age: 30})">更新</button>
</li>
</ul>
<h2>測試 : v-for 遍厲物件</h2>
<ul>
<li v-for="(value, key) in persons[1]" :key="key">
{{ value }}----{{ key }}
</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script src="./index.js"></script>
</body>
</html><file_sep>const vm = new Vue ({
el: '#app',
data: {
msg: 'I will Back!',
imgUrl: 'https://book.vue.tw/assets/img/1-1-vue-logo.402955e1.png'
},
methods: {
test () {
alert('good')
},
test2 (content) {
alert(content)
}
}
})<file_sep>new Vue ({
el: '#app',
data: {
test1 () {
alert('hello')
},
test2 (content) {
alert(content)
},
test3 (event) {
alert(event.target.innerHTML)
},
test4 (number, event) {
alert(number + '----' + event.target.innerHTML)
},
test5 () {
alert('out')
},
test6 () {
alert('inner')
},
test7 () {
alert('click')
},
test8 (event) {
alert(event.target.value)
},
test9 (event) {
alert(event.target.value)
}
}
}) | ca9d9c0f065a7bc706e3498b2ea0ce4587ffc5eb | [
"JavaScript",
"HTML"
] | 7 | JavaScript | ben7152000/vue | c116b1bbd1a7517c880630778e015091dcb44ffb | 29808ed57a2b27ef403860cd96ba152829a3222b |
refs/heads/master | <file_sep>import numpy as np
def bubbleSort(arr):
n = len(arr)
for i in range (n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
array_size = np.random.randint(10,100,1) #Generates a random integer between 10 and 30 which is the size of array
print("The size of the random array is " + str(array_size))
random_array = np.random.randint(1,10000, array_size) #generates a random array of size (array_size) with values between 1 and 1000
print("The unsorted random array is ")
print(random_array)
print("The sorted random array is:")
bubbleSort(random_array)
for i in range(len(random_array)):
print (random_array[i], end = " < ") | b33a2476b3550e6ca0d1a6a2ed0ffcfee25c4794 | [
"Python"
] | 1 | Python | ishantd/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | 39b3037094a0c19301a794a6dac6012ee7bc4888 | 75e9386fecbf692f7ccea1299461fc941cf7e969 |
refs/heads/master | <file_sep>const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "!";
client.on('ready', () => {
console.log(`----------------`);
console.log(`Desert Bot- Script By : EX Clan`);
console.log(`----------------`);
console.log(`ON ${client.guilds.size} Servers ' Script By : EX Clan ' `);
console.log(`----------------`);
console.log(`Logged in as ${client.user.tag}!`);
client.user.setGame(`${prefix}help`,"http://twitch.tv/Death Shop")
client.user.setStatus("dnd")
});
client.on('message', message => {
if (message.author.bot) return;
if (message.content === prefix + "help") {
message.author.send(`
:robot: *** Bot orders | اوامر بوت *** :robot:
----------------------------------
:mega: ${prefix}**bc --> 『 برودكاست الكل 』**
:mega: ${prefix}**bco --> 『 برودكاست وان الاين 』**
:mega: ${prefix}**bcs --> 『 يرودكاست كرسال عادى 』**
:mega: ${prefix}**bca --> 『 برودكاست الى رتب معين 』**
:mega: ${prefix}**bce --> 『 برودكاست متعداد بركشن 』**
:mega: ${prefix}**inv --> 『 دعوه بوت 』**
:mega: ${prefix}**Sup --> 『 دعم الفنى الى بوت 』**
:mega: ${prefix}**bot --> 『 معلومات بوت 』**`);
}
});
const adminprefix = "!";
const devs = ['564414567946387487']
client.on('message', message => {
var argresult = message.content.split(` `).slice(1).join(' ');
if (!devs.includes(message.author.id)) return;
if (message.content.startsWith(adminprefix + 'x')) {
client.user.setGame(argresult);
message.channel.sendMessage(`**__${argresult}__تـم تـغـيـر بـلانـيـق الـى🔵**`)
} else
if (message.content.startsWith(adminprefix + 'xx')) {
client.user.setUsername(argresult).then
message.channel.sendMessage(`**__${argresult}__تـم تـغـيـر اســم الـى**📝`)
return message.reply("**لايـمـكـن تـغـيـر اسـم الان نـتـظـار سـاعـتـان**:stopwatch: ");
} else
if (message.content.startsWith(adminprefix + 'xxx')) {
client.user.setAvatar(argresult);
message.channel.sendMessage(`**__${argresult}__تــم تــغـيــر صــور الـى 📸**`);
} else
if (message.content.startsWith(adminprefix + 'xxxx')) {
client.user.setGame(argresult, "https://www.twitch.tv/idk");
message.channel.sendMessage(`**__${argresult}__ تــم تـغــيــر حــالـه الــى 🔴**`)
}
});
client.on("message", async message => {
var command = message.content.split(" ")[0];
command = command.slice(prefix.length);
if(!message.channel.guild) return;
var args = message.content.split(" ").slice(1).join(" ");
if(command == "bc") {
if(!message.member.hasPermission("ADMINISTRATOR")) {
return message.channel.send("**للأسف لا تمتلك صلاحية `ADMINISTRATOR`**");
}
if(!args) {
return message.reply(":pencil2: | **يجب عليك كتابة كلمة او جملة لإرسال البرودكاست ...**");
}
message.channel.send(`هل متاكيد من البرودكاست من رسال بردكاست خاص بك ..؟
\nمحتوى الرسال: \`${args}\``).then(m => {
m.react("✅")
.then(() => m.react("❌"));
let yesFilter = (reaction, user) => reaction.emoji.name == "✅" && user.id == message.author.id;
let noFiler = (reaction, user) => reaction.emoji.name == "❌" && user.id == message.author.id;
let yes = m.createReactionCollector(yesFilter);
let no = m.createReactionCollector(noFiler);
yes.on("collect", v => {
m.delete();
message.channel.send(`:ok_hand: | **تم رسال بروكاست** ${message.guild.memberCount} Members`).then(msg => msg.delete(5000));
message.guild.members.forEach(member => {
let bc = new Discord.RichEmbed()
.setColor("RANDOM")
.setThumbnail(message.author.avatarURL)
.setTitle("")
.addField(":triangular_flag_on_post: | **سيرفر**", message.guild.name)
.addField(":incoming_envelope: | **مرسل**", message.author.username)
.addField(":e_mail: | **رسالة**", args);
member.sendEmbed(bc);
});
});
no.on("collect", v => {
m.delete();
message.channel.send(":x: | **تم الغاء برودكاست ...**").then(msg => msg.delete(3000));
});
});
}
if(command == "bco") {
if(!message.member.hasPermission("ADMINISTRATOR")) {
return message.channel.send(":x: | **للأسف لا تمتلك صلاحية `ADMINISTRATOR` ..**");
}
if(!args) {
return message.reply(":pencil2: | **يجب عليك كتابة كلمة او جملة لإرسال البرودكاست ...**");
}
message.channel.send(`**هل أنت متأكد من إرسالك البرودكاست؟\nمحتوى البرودكاست: \`${args}\`**`).then(m => {
m.react("✅")
.then(() => m.react("❌"));
let yesFilter = (reaction, user) => reaction.emoji.name == "✅" && user.id == message.author.id;
let noFiler = (reaction, user) => reaction.emoji.name == "❌" && user.id == message.author.id;
let yes = m.createReactionCollector(yesFilter);
let no = m.createReactionCollector(noFiler);
yes.on("collect", v => {
m.delete();
message.channel.send(`:ok_hand: | **تم رسال بروكاست** ${message.guild.members.filter(r => r.presence.status !== "offline").size} Members`).then(msg => msg.delete(5000));
message.guild.members.filter(r => r.presence.status !== "offline").forEach(member => {
let bco = new Discord.RichEmbed()
.setColor("RANDOM")
.setThumbnail(message.author.avatarURL)
.setTitle("")
.addField(":triangular_flag_on_post: | **سيرفر** : ", message.guild.name)
.addField(":incoming_envelope: | **مرسل** : ", message.author.username)
.addField(":e_mail: | **رسالة** : ", args);
member.sendEmbed(bco);
});
});
no.on("collect", v => {
m.delete();
message.channel.send(":x: | **تم الغاء برودكاست...**").then(msg => msg.delete(3000));
});
});
}
});
client.on("message", message => {
var prefix = "!";
if (message.author.id === client.user.id) return;
if (message.guild) {
let embed = new Discord.RichEmbed()
let args = message.content.split(' ').slice(1).join(' ');
if(message.content.split(' ')[0] == prefix + 'bcs') {
if (!args[1]) {
message.channel.send(":pencil2: | ** رجاء اكتب رسال البرودكاست ... **");
return;
}
message.guild.members.forEach(m => {
if(!message.member.hasPermission('ADMINISTRATOR')) return;
m.send(args);
});
const AziRo = new Discord.RichEmbed()
.setAuthor(message.author.username, message.author.avatarURL)
.setTitle(':outbox_tray: | جاري ارسال رسالتك')
.addBlankField(true)
.addField(':busts_in_silhouette: | عدد الاعضاء المرسل لهم', message.guild.memberCount , true)
.addField(':e_mail: | الرسالة ', args)
.setColor('RANDOM')
message.channel.sendEmbed(AziRo);
}
} else {
return;
}
});
client.on('message' , message => {
if(message.author.bot) return;
if(message.content.startsWith(prefix + "bca")) {
if (!message.member.hasPermission("ADMINISTRATOR")) return;
let args = message.content.split(" ").slice(2);
var codes = args.join(' ')
if(!codes) {
message.channel.send("** قم بكتابة الرسالة 。。。 :pencil2:** | `!rolebc role message`")
return;
}
var role = message.mentions.roles.first();
if(!role) {
message.reply(":x: | **لا يوجد رتب بهذا اسم**")
return;
}
message.guild.members.filter(m => m.roles.get(role.id)).forEach(n => {
n.send(`${codes}`)
})
message.channel.send(`:white_check_mark: | **لقد تم ارسال هذه الرسالة الى ** ${message.guild.members.filter(m => m.roles.get(role.id)).size}** عضو**:busts_in_silhouette:`)
}
});
client.on('message', message => {
if(message.author.bot) return;
if(message.channel.type === 'dm') return;
if(message.content.startsWith(prefix + 'bce')) {
let filter = m => m.author.id === message.author.id;
let recembed = new Discord.RichEmbed()
.setTitle(`${client.user.username}`)
.setDescription(`
⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰
🎖 | يرسل البرودكاست إلى دور محدد دون تضمين
🏅 | يرسل البرودكاست إلى دور محدد باستخدام التضمين
📭 | يرسل البرودكاست لجميع الأعضاء مع تضمين
📧 | يرسل البرودكاست لجميع الأعضاء دون تضمين
🔵 | يرسل البرودكاست للأعضاء عبر الإنترنت فقط دون تضمين
🔷 | يرسل البرودكاست للأعضاء عبر الإنترنت فقط مع تضمين
❌ | لإلغاء العملية
⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰⧱⧰`)
message.channel.sendEmbed(recembed).then(msg => {
msg.react('🎖')
.then(() => msg.react('🏅'))
.then(() => msg.react('📭'))
.then(() => msg.react('📧'))
.then(() => msg.react('🔵'))
.then(() => msg.react('🔷'))
.then(() => msg.react('❌'))
let embedmsgFilter = (reaction, user) => reaction.emoji.name === '📭' && user.id === message.author.id;
let normalmsgFilter = (reaction, user) => reaction.emoji.name === '📧' && user.id === message.author.id;
let cancelFilter = (reaction, user) => reaction.emoji.name === '❌' && user.id === message.author.id;
let onlyroleFilter = (reaction, user) => reaction.emoji.name === '🎖' && user.id === message.author.id;8
let onlineonlyFilter = (reaction, user) => reaction.emoji.name === '🔵' && user.id === message.author.id;8
let embedonlineonlyFilter = (reaction, user) => reaction.emoji.name === '🔷' && user.id === message.author.id;8
let embedonlyroleFilter = (reaction, user) => reaction.emoji.name === '🏅' && user.id === message.author.id;8
let embedmsg = msg.createReactionCollector(embedmsgFilter, { time: 0 });
let normalmsg = msg.createReactionCollector(normalmsgFilter, { time: 0 });
let onlyrole = msg.createReactionCollector(onlyroleFilter, { time: 0 });
let embedonlyrole = msg.createReactionCollector(embedonlyroleFilter, { time: 0 });
let onlineonly = msg.createReactionCollector(onlineonlyFilter, { time: 0 });
let embedonlineonly = msg.createReactionCollector(embedonlineonlyFilter, { time: 0 });
let cancel = msg.createReactionCollector(cancelFilter, { time: 0 });
embedonlineonly.on('collect', r => {
let msge;
message.channel.send(':pencil: **| يرجى الكتابة الآن رسالة لإرسال :pencil2: **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
msge = collected.first().content;
msg.edit(':shield: **| هل انت متاكيد من رسال البرودكاست ? [نعم و لا] الى موافق **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
if(collected.first().content === 'نعم') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.presence.status === 'online').forEach(m => {
var bc = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle(`:mega: | **برودكاست جديد**`)
.addField('🔰 **سيرفر** 🔰', message.guild.name)
.addField('🚩 **مرسل** 🚩', message.author.username)
.addField('📜 **رسالة** 📜', `${msge}`)
.setThumbnail('https://a.top4top.net/p_1008gqyyd1.png')
.setFooter(client.user.username, client.user.avatarURL);
m.send({ embed: bc })
m.send(`${m}`)
})
}})
if(collected.first().content === 'لا') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.presence.status === 'online').forEach(m => {
var bc = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle(`:mega: | **برودكاست جديد**`)
.addField('🔰 **سيرفر** 🔰', message.guild.name)
.addField('🚩 **مرسل** 🚩', message.author.username)
.addField('📜 **رسالة** 📜', `${msge}`)
.setThumbnail('https://a.top4top.net/p_1008gqyyd1.png')
.setFooter(client.user.username, client.user.avatarURL);
m.send({ embed: bc })
})
}
})
})
})
})
onlineonly.on('collect', r => {
let msge;
message.channel.send(':pencil: **| يرجى الكتابة الآن رسالة لإرسال :pencil2: **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
msge = collected.first().content;
msg.edit(':shield: **| هل انت متاكيد من رسال البرودكاست ? [نعم و لا] الى موافق **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
if(collected.first().content === 'نعم') {
message.channel.send(`**:white_check_mark: تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.presence.status === 'online').forEach(m => {
m.send(`${msge}`)
m.send(`${m}`)
})
}
if(collected.first().content === 'لا') {
message.channel.send(`**:white_check_mark: تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.presence.status === 'online').forEach(m => {
m.send(`${msge}`)
})}
})
})
})
})
})
embedmsg.on('collect', r => {
let msge;
message.channel.send(':pencil: **| يرجى الكتابة الآن رسالة لإرسال :pencil2: **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
msge = collected.first().content;
msg.edit(':shield: **| هل انت متاكيد من رسال البرودكاست ? [نعم و لا] الى موافق **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
if(collected.first().content === 'نعم') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.forEach(m => {
var bc = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle(`:mega: | **برودكاست جديد**`)
.addField('🔰** سيرفر **🔰', message.guild.name)
.addField('🚩 **مرسل** 🚩', message.author.username)
.addField('📜 **رسالة** 📜', `${msge}`)
.setThumbnail('https://a.top4top.net/p_1008gqyyd1.png')
.setFooter(client.user.username, client.user.avatarURL);
m.send({ embed: bc })
m.send(`${m}`)
})
}})
if(collected.first().content === 'لا') {
message.channel.send(`**:white_check_mark: تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.forEach(m => {
var bc = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle(`:mega: | **برودكاست جديد**`)
.addField('🔰** سيرفر **🔰', message.guild.name)
.addField('🚩 **مرسل** 🚩', message.author.username)
.addField('📜 **رسالة** 📜', `${msge}`)
.setThumbnail('https://a.top4top.net/p_1008gqyyd1.png')
.setFooter(client.user.username, client.user.avatarURL);
m.send({ embed: bc })
})
}
})
})
})
})
normalmsg.on('collect', r => {
let msge;
message.channel.send(':pencil: **| يرجى الكتابة الآن رسالة لإرسال :pencil2: **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
msge = collected.first().content;
msg.edit(':shield: **| هل انت متاكيد من رسال البرودكاست ? [نعم و لا] الى موافق **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
if(collected.first().content === 'نعم') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.forEach(m => {
m.send(`${msge}`)
m.send(`${m}`)
})
}
if(collected.first().content === 'لا') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.forEach(m => {
m.send(`${msge}`)
})}
})
})
})
})
})
onlyrole.on('collect', r => {
let msge;
let role;
message.channel.send(':pencil: **| يرجى الكتابة الآن رسالة لإرسال :pencil2: **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
msge = collected.first().content;
msg.edit(':pencil2: **| الان يرجاء اكتب اسم رتب**').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
role = collected.first().content;
let rolecheak = message.guild.roles.find('name', `${role}`)
msg.edit(':shield: **| هل انت متاكيد من رسال البرودكاست ? [نعم و لا] الى موافق **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
if(collected.first().content === 'نعم') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.roles.get(rolecheak.id)).forEach(m => {
m.send(`${msge}`)
m.send(`${m}`)
})
}
if(collected.first().content === 'لا') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.roles.get(rolecheak.id)).forEach(m => {
m.send(`${msge}`)
})}
})
})
})
})
})
})
});
embedonlyrole.on('collect', r => {
let msge;
let role;
message.channel.send(':pencil: **| يرجى الكتابة الآن رسالة لإرسال :pencil2: **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
msge = collected.first().content;
msg.edit(':pencil2: |** الان يرجاء كتب اسم رتب**').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
collected.first().delete();
role = collected.first().content;
let rolecheak = message.guild.roles.find('name', `${role}`)
msg.edit(':shield: **| هل انت متاكيد من رسال البرودكاست ? [نعم و لا] الى موافق **').then(msg => {
message.channel.awaitMessages(filter, {
max: 1,
time: 90000,
errors: ['time']
})
.then(collected => {
if(collected.first().content === 'نعم') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.roles.get(rolecheak.id)).forEach(m => {
var bc = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle(`:mega: | **برودكاست جديد**`)
.addField('**🔰 سيرفر 🔰**', message.guild.name)
.addField('**🚩 مرسل 🚩**', message.author.username)
.addField('**📜 رسالة 📜**', `${msge}`)
.setThumbnail('https://a.top4top.net/p_1008gqyyd1.png')
.setFooter(client.user.username, client.user.avatarURL);
m.send({ embed: bc })
m.send(`${m}`)
})
}
if(collected.first().content === 'لا') {
message.channel.send(`**:white_check_mark: | تم إرسال الرسالة الأعضاء :loudspeaker:**`);
message.guild.members.filter(m => m.roles.get(rolecheak.id)).forEach(m => {
var bc = new Discord.RichEmbed()
.setColor('RANDOM')
.setTitle(`:mega: | **برودكاست جديد**`)
.addField('**🔰 سيرفر 🔰**', message.guild.name)
.addField('**🚩 مرسل 🚩**', message.author.username)
.addField('**📜 رسالة 📜**', `${msge}`)
.setThumbnail('https://a.top4top.net/p_1008gqyyd1.png')
.setFooter(client.user.username, client.user.avatarURL);
m.send({ embed: bc })
})}
})
})
})
})
})
})
})
cancel.on('collect', r => {
let cancelembed = new Discord.RichEmbed()
.setTitle(':x: | **تم الإلغاء بنجاح**')
message.channel.sendEmbed(cancelembed)
embedmsg.stop();
normalmsg.stop();
onlyrole.stop();
embedonlyrole.stop();
embedonlineonly.stop()
onlineonly.stop()
cancel.stop();
})
})
}});
client.on("message",function(message) {
var prefix = "!";
if(message.content.startsWith(prefix + 'bot')) {
var uptime = client.uptime;
var days = 0;
var hours = 0;
var minutes = 0;
var seconds = 0;
var notCompleted = true;
while (notCompleted) {
if (uptime >= 8.64e+7) {
days++;
uptime -= 8.64e+7;
} else if (uptime >= 3.6e+6) {
hours++;
uptime -= 3.6e+6;
} else if (uptime >= 60000) {
minutes++;
uptime -= 60000;
} else if (uptime >= 1000) {
seconds++;
uptime -= 1000;
}
if (uptime < 1000) notCompleted = false;
}
var v1 = new Discord.RichEmbed()
v1.setTimestamp(new Date())
v1.setColor("#6a109d")
v1.setDescription('***__ انتظر .. جاري الحصول علي البيانات __***')
v1.setFooter("# | Super Broadcast |")
var heroo = new Discord.RichEmbed()
.setColor('#6a109d')
.setTimestamp(new Date())
.setThumbnail(client.user.avatarURL)
.setTitle('Super Broadcast')
.setURL('https://discordapp.com/api/oauth2/authorize?client_id=580916581702565889&permissions=8&scope=bot')
.setAuthor(client.user.username,client.user.avatarURL)
.addField("**البرفكس** :",`**[ ${prefix} ]**`,true)
.addField("**السيرفرات** :","**[ "+client.guilds.size+" ]**",true)
.addField("**القنوات** :","**[ "+client.channels.size+" ]**",true)
.addField("**المستخدمين** :","**[ "+client.users.size+" ]**",true)
.addField("**اسم البوت** : ","**[ "+client.user.username+" ]**",true)
.addField("**ايدي البوت **:","**[ "+client.user.id+" ]**",true)
.addField("**الحجم المستخدم** :",`**[ ${(process.memoryUsage().rss / 1048576).toFixed()}MB ]**`,true)
.addField("**موعد الاقلاع** :",`**[** **Days:** \`${days}\` **Hours:** \`${hours}\` **Minutes:** \`${minutes}\` **Seconds:** \`${seconds}\` **]**`,true)
.setFooter("Super Broadcast");
message.channel.send({embed:v1}).then(m => {
setTimeout(() => {
m.edit({embed:heroo});
},3000);
});
}
});
client.on('message', msg => {
if (msg.content === '!help') {
msg.reply(' | **تم رسال فى الخاص ...** :incoming_envelope:');
}
});
client.login(process.env.BOT_TOKEN);
<file_sep># Super-Broadcast
بوت برودكاست العام
| cae371541f8b297c9b52d392ef08d4df572ee3b3 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | qfraeswd/Super-Broadcast | 6aed96c52928c917fca3fc243c3d8298dc418110 | cdc64cf5ebaec324c8ef6181b0db5ff99bcf4aa2 |
refs/heads/master | <repo_name>minavadamee20/C-programs<file_sep>/README.md
# 223-Archive-repos
Old C# programs that are being backed up here
<file_sep>/assignment_0-1/Selectui.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class Selectui:Form{
//create controls
private Button draw= new Button();
private RadioButton square = new RadioButton();
private RadioButton circle = new RadioButton();
private ComboBox color = new ComboBox();
private Color c = Color.Yellow;
//set options
public Selectui(){
Text = "Select";
draw.Text="Draw";
color.Text= "Choose a color";
square.Text="Square";
circle.Text="Circle";
//set Size
Size = new Size(500,250);
//set Location
int v = 20;
draw.Location = new Point(20,30);
square.Location = new Point(v += 10 + draw.Width,30);
circle.Location = new Point (v += 10 + square.Width,30);
color.Location = new Point (v += 10 + circle.Width, 30);
//add items to combo ComboBox
color.Items.Add("Red");
color.Items.Add("Green");
color.Items.Add("Blue");
//add controls to Form
Controls.Add(draw);
Controls.Add(square);
Controls.Add(circle);
Controls.Add(color);
//Register event handler
draw.Click += new EventHandler(Draw_Click);
}
//Display chosen shape and selected Color
protected override void OnPaint(PaintEventArgs e){
Graphics g = e.Graphics;
Brush brush = new SolidBrush(c);
if(square.Checked){g.FillRectangle(brush, 100,100,100,100);}
else{g.FillEllipse(brush, 100,100,100,100);}
g.FillEllipse(brush, 100,100,100,100);
base.OnPaint(e);
}
//Handle button Click
protected void Draw_Click(object sender, EventArgs e){
if(color.SelectedItem.ToString() == "Red")
c = Color.Red;
else if(color.SelectedItem.ToString() == "Green")
c = Color.Green;
else
c = Color.Blue;
Invalidate();
}
}
<file_sep>/assignment_2/algorithm.cs
using System;
using System.Drawing;
using System.Timers;
public class Clock_Algorithms{
public static int set_display(int mess_count, ref System.Timers.Timer mess_clock, ref Brush painting_tool, int t1, int t2, int t3){
switch(mess_count){
case 0: mess_clock.Interval = t1;
painting_tool = Brushes.Red;
break;
case 1: mess_clock.Interval = (int)t2;
painting_tool = Brushes.Yellow;
break;
case 2: mess_clock.Interval = (int)t3;
painting_tool = Brushes.Green;
break;
}//end of switch statement
return (mess_count+1)%3;
}//end of set_display
}//end of Clock_Algorithms
<file_sep>/assignment_7/SineCurve.cs
public class Sinecurve
{ private double absolute_value_of_derivative_squared;
private double absolute_value_of_derivative;
public void get_next_coordinates(double amp, double coef, double delta, ref double dot, out double x, out double y)
{absolute_value_of_derivative_squared = 1+ amp*amp * coef*coef * System.Math.Cos(coef*dot)*System.Math.Cos(coef*dot);
absolute_value_of_derivative = System.Math.Sqrt(absolute_value_of_derivative_squared);
dot = dot + delta/absolute_value_of_derivative;
x = dot;
y = amp*System.Math.Sin(coef*dot);
}//End of get_next_coordinates
}//End of class Sinecurve
<file_sep>/assignment_0-1/main.cs
using System;
using System.Windows.Forms;
public class selectmain{
static void Main(){
System.Console.WriteLine("This is Assignment 0");
Selectui userface = new Selectui();
Application.Run(userface);
System.Console.WriteLine("I hope you enjoyed this");
}
}
<file_sep>/assignment_2/run.sh
echo First remove old binary files
rm *.dll
rm* exe
echo view the list of source files
ls -l
echo compile the algorithm.cs to create the file algorithm.dll
mcs -target:library -r:System.Drawing.dll -out:algorithm.dll algorithm.cs
echo compile Uifile and then link algorithm.cs to UiFile.cs
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -r:algorithm.dll -out:Uifile.dll Uifile.cs
#more stuff will go here as we make more cs files ^^^^
echo Compile the Run.sh and link the pervious created dll files to create an executable file
mcs -r:System.Windows.Forms -r:Uifile.dll -out:Application2.exe main.cs
echo View the list of the files in the current folder
ls -l
echo Run the Assignment2 program
./Application2.exe
echo [THE SCRIPT HAS ENDED]
<file_sep>/final_223/run.sh
echo First remove old binary files
rm* .dll
rm *.exe
echo view the list of source files
ls -l
echo compile the uifile.cs to create the file uifile.dll
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms -out:uifile.dll uifile.cs
#add more stuff here if needed
echo compiles the run.sh and link the previous created dll files to create an executeable file
mcs -r:System.Windows.Forms -r:System.Drawing.dll -r:uifile.dll -out:final.exe main.cs
echo view the list of the files in the folder
ls -l
echo Run the Assignment6 program
./final.exe
echo [THE SCRIPT HAS NOW ENDED... PROGRAM SHUTTING DOWN]
<file_sep>/final_223/uifile.cs
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
public class uifile:Form{
private Button go_button = new Button();
private Button pause_button = new Button();
private Button exit_button = new Button();
private const int form_height = 900;
private const int form_width = 1200;
private const int bottomPanel_height = 75;
private int bottomPanel_Location;
//private Pen pen_tool = new Pen(Color.Red, 1);//color, size = 1 pixels wide
private Pen tail_pen = new Pen(Color.White, 1);
private SolidBrush brushes = new SolidBrush(Color.MistyRose);
private SolidBrush star_brushes = new SolidBrush(Color.White);
private SolidBrush moon_brush = new SolidBrush(Color.Silver);
private SolidBrush grass_brush = new SolidBrush(Color.SeaGreen);
private Rectangle bottompanel = new Rectangle(0,form_height- bottomPanel_height, form_width, bottomPanel_height);
private Rectangle grassRectangle = new Rectangle(0, form_height-bottomPanel_height-grass_height, form_width, grass_height);
//mathematical constants and others that are needed to run the function
private const double scale_factor = 100; //this is 100 pixels, will be needed to most likely seperate the tic marks on the x and y axis
private const double origin = 40.0; //the origin is located 40 pixels away from the left side of the user interace
private const double refresh_rate = 88.8; //frequency in Hertz, how many times per second is the display area repainted. so 888 times per second
private const double dot_update_rate = 55.5; //frequence measured in Herz, how many times per second is the coordinate's of the dot being updated
private const double time_converter = 1000.0; //number of miliseconds per second
private const int origin_center_y = form_height/2;
private static System.Timers.Timer ball_refresh_clock = new System.Timers.Timer();
private const double ball_refresh_clock_rate = 43.5; //the ball will be updated 43.5 per second, meaning it will be repained 43.5 times per second
private static System.Timers.Timer monitor_refresh_clock = new System.Timers.Timer();
private const double monitor_refresh_clock_rate = 23.3; //measured in Hz. will refresh 23.3 times per second
private const double radius_tic = 2.0; //radius of the presumed tic marks that reprsent where certain numbers are on the axis.
//declare these const values later..like maybe at the origin and then move them according to the function that we end up choosing?
private const double ball_center_initial_coordinate_x = form_width;
private const double ball_center_initial_coordinate_y = 0;
private double ball_center_coordinate_x;
private double ball_center_coordinate_y;
// private double ball_center_coordinate_x_original;
// private double ball_center_coordinate_y_original;
// private double x_coordinate_rounded;
// private double y_coordinate_rounded;
private int first_iteration;
private const double linear_speed = 44.5; //moving 44.5 pixels per second
private double delta = .005;
// private Point grass_left;
// private Point grass_right;
private const int grass_height= 175; //the grass height is 75 pixels
private int grass_location;
private int state=0;
private bool tail_state = true;
private Point tail_begin;
private Point tail_end;
public uifile(){
BackColor = Color.DarkSlateGray;
Size = new Size(form_width, form_height);
ball_center_coordinate_x = ball_center_initial_coordinate_x;
ball_center_coordinate_y = ball_center_initial_coordinate_y;
tail_end = new Point((int)ball_center_initial_coordinate_x, 0);
monitor_refresh_clock.Enabled = false;
monitor_refresh_clock.Elapsed += new ElapsedEventHandler(update_display);
ball_refresh_clock.Enabled = false;
ball_refresh_clock.Elapsed += new ElapsedEventHandler(update_ball_position); //everytime this tics, we are taken to the function update+update_ball_position
bottomPanel_Location = form_height - bottomPanel_height;
grass_location = bottomPanel_Location - grass_height;
int width_measuring_tool = 0;
int height_measuring_tool = bottomPanel_Location + 2;
go_button.Location = new Point(width_measuring_tool += 5, height_measuring_tool);
go_button.BackColor = Color.Pink;
go_button.Text = "Go";
pause_button.Location = new Point(width_measuring_tool += 5 + go_button.Width, height_measuring_tool);
pause_button.BackColor = Color.Pink;
pause_button.Text = "Pause";
exit_button.Location = new Point( form_width - 15 - exit_button.Width, height_measuring_tool);
exit_button.BackColor = Color.Pink;
exit_button.Text = "Exit";
go_button.Click += new EventHandler(go_click);
pause_button.Click += new EventHandler(pause_resume_click);
exit_button.Click += new EventHandler(exit_click);
Controls.Add(go_button);
Controls.Add(pause_button);
Controls.Add(exit_button);
}//end of public uifile function
protected void go_click(Object sender, EventArgs e){ //every time this functoin (ball_refresh_clock) tics, we will be directed to the function update_ball_position;
start_graphics(monitor_refresh_clock_rate);
start_ball_motion(ball_refresh_clock_rate);
state =1;
}
protected void pause_resume_click(Object sender, EventArgs e){
switch(state){
case 1:
pause_button.Text = "Resume";
ball_refresh_clock.Enabled = false;
monitor_refresh_clock.Enabled = false;
state =2;
break;
case 2:
pause_button.Text = "Pause";
ball_refresh_clock.Enabled = true;
monitor_refresh_clock.Enabled = true;
state =1;
break;
}//end of switch statement
}
protected void exit_click(Object sender, EventArgs e){
System.Console.WriteLine("Now exiting program.....");
Close();
}
protected void update_ball_position(System.Object sender, ElapsedEventArgs e){
//first_iteration +=1;
ball_center_coordinate_x -= delta;
ball_center_coordinate_y += delta;
tail_begin = new Point((int)ball_center_coordinate_x+6, (int)ball_center_coordinate_y);
if(ball_center_coordinate_y+7 > grass_location){
tail_state = false;
}
if(!tail_state){
delta = .005;
ball_center_coordinate_x = ball_center_initial_coordinate_x;
ball_center_coordinate_y = ball_center_initial_coordinate_y;
tail_state = true;
}
delta += .004;
}
protected override void OnPaint(PaintEventArgs ee){
Graphics g = ee.Graphics;
g.FillRectangle(brushes, bottompanel);
g.FillRectangle(grass_brush, grassRectangle);
g.FillEllipse(moon_brush, (float)form_width/15, (float)form_height/12, 120,120);
if(tail_state){
g.FillEllipse(star_brushes, (float)ball_center_coordinate_x, (float)ball_center_coordinate_y, 7,7);
g.DrawLine(tail_pen, tail_begin, tail_end);
}
base.OnPaint(ee);
}
protected void start_graphics(double monitor_refresh_clock_rate) {
//stuff: don't forget to add arg
double actual_refresh_rate = 1.0;
double elapsed_time_between_tics;
if(monitor_refresh_clock_rate > actual_refresh_rate){
actual_refresh_rate = monitor_refresh_clock_rate;
}
elapsed_time_between_tics = 1000.0/actual_refresh_rate;
monitor_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_tics);
monitor_refresh_clock.Enabled = true;
}
protected void start_ball_motion(double update_rate){
//stuff: don't forget to add arg
double elapsed_time_between_ball_moves;
if(update_rate < 1.0) {update_rate = 1.0;}
elapsed_time_between_ball_moves = 1000.0/update_rate;
ball_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_ball_moves);
ball_refresh_clock.Enabled = true;
}
protected void update_display(System.Object sender, ElapsedEventArgs e){
Invalidate();
if(!ball_refresh_clock.Enabled){
monitor_refresh_clock.Enabled = false;
System.Console.WriteLine("The graphical interface has stopped refreshing. you may not exit the program");
}
}
}//end of public class uifile:Form
<file_sep>/assignment_0/Selectui.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class Select : Form{
//create controls
private Button draw= new Button();
private RadioButton square = new RadioButton();
private RadioButton circle= new RadioButton();
private ComboBox color = new ComboBox();
private Color c = Color.Yellow;
//set options
public Selet(){
Text = "Select";
draw.Text="Draw";
color.Text= "Choose a color";
square.Text="Square";
circle.Text="Circle";
//set Size
Size=new.Size(500,250);
//set Location
int v = 20;
draw.Location = new Point(20,30);
square.Location=new Point(v+=10 + draw.Width,30);
circle.Location=new Point (v+=10+ square.Width,30);
color.Location=new Point(v += 10 + cicle.Width, 30);
//add items to combo ComboBox
color.Items.Add("Red");
color.Items.Add("Green");
color.Items.Add("Blue");
//add controls to Form
Controls.Add(draw);
Controls.Add(square);
Controls.Add(circle);
Controls.Add(color);
//Register event handler
draw.Click += new EventHandler(Draw_Click);
}
//Display chosen shape and selected Color
protected override void OnPaint(PaintEventArgs e){
Graphics g = e.Graphics;
Brush brush = new SolidBrush(c);
if (square.Checked)
g.FillRectange(brush,100,100,100,100);
else
g.Fillellipse(brush, 100,100,100,100);
base.OnPaint( e );
}
//Handle button Click
protected void Draw_Clik(Object sender, EventArgs e){
if(color.SelectedItem.ToString()=="Red")
c= Color.Red;
else if(Color.SelectedItem.ToString() == "Green")
c=Color.Green;
else c = Color.Blue;
Invalidate();
}
static void Main(){
Application.Run(new Slect());
}
}
}
<file_sep>/assignment_1/algorithm.cs
using System;
using System.Drawing;
public class CircleAlgorithms{
public static System.Drawing.Rectangle
getcircleinfo(int graphareawidth, int graphareaheight, int radius){
Point corner = new Point(graphareawidth/2 -radius, graphareaheight/2 - radius); //the concept is we find the center of the graphical area of our field.
Size lenwide = new Size(2*radius, 2* radius);
Rectangle rect = new Rectangle(corner, lenwide);
return rect;
}//end of class
}
<file_sep>/assignment_3.1/Uifile.cs
//****************************************************************************************************************************
//Program name: "Ninety Degree Turn". This programs accepts the coordinates of two points from the user, draws a straight *
//line segment connecting them, and ball travels from the beginning end point to the terminal end point. *
//Copyright (C) 2018 <NAME> *
//This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License *
//version 3 as published by the Free Software Foundation. *
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
//warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
//A copy of the GNU General Public License v3 is available here: <https://www.gnu.org/licenses/>. *
//****************************************************************************************************************************
//Ruler:=1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1=========2=========3**
//Author: <NAME>
//Mail: <EMAIL>
//Program name: Ninety Degree Turn
//Programming language: C Sharp
//Date development of program began: 2018-Oct-18
//Date of last update: 2018-Oct-18
//Purpose: This programs demonstrate how an animated ball can turn in a 90 degree angle and still maintain constant speed.
//Files in project: ninety-degree-main.cs, straight-line-travel-user-interface.cs, straight-line-travel-algorithms.cs, r.sh
//This file's name: ninety-degree-ui.cs
//This file purpose: This module (file) defines the layout of the user interface
//Date last modified: 2018-Oct-19
//Known issues: None that the author is aware
//To compile straight-line-travel-user-interface.cs:
// mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -r:straight-functions.dll -out:straight-line.dll straight-line-travel-user-interface.cs
//
//Hardcopy of source files: For printing 132 horizontal columns are needed to avoid line wrap in portrait orientation.
//Suggestion: As user of this program feel free to experiment especially by changing the values of delta (distance traveled
//between tics) and animation_clock_speed. Make these changes in the source code itself. Try to find the best combination
//of numbers that makes a smooth moving ball (no jerkiness).
//Convention: The short name 'x' denotes the x-coordinate of the upper left corner of the ball.
// The short name 'y' denotes the y-coordinate of the upper left corner of the ball.
// This program does not reference the ball by the coordinates of the center of the ball.
//An old fashioned technique used with double and float numbers is used in this program.
//Sometimes we don't require that two doubles be perfectly equal to each other -- sometimes just being close is good enough.
//Suppose a and b are two doubles. In this program a and b are considered equal if the absolute value of (a-b) is very very close to zero.
//In this program you will see: System.Math.Abs(y+radius-p0y)<0.5. That means y+radius is almost equal to p0y.
//Now you know what such statements mean.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Timers;
public class Uifile : Form
{ private const int maximum_form_width = 1920; //A graphical area of size 1920x1080 has standard aspect ratio 16:9.
private const int maximum_form_height = 1080; //Valid x-coordinates: 0-1919; valid y-coordinates: 0-1079.
private const int minimum_form_width = 640;
private const int minimum_form_height = 360;
Size maxframesize = new Size(maximum_form_width,maximum_form_height);
Size minframesize = new Size(minimum_form_width,minimum_form_height);
//Declare more constants
private const int top_panel_height = 50; //Measured in pixels
private const int bottom_panel_height = 110; //Measured in pixels
private const double delta = 8.972; //Animation speed: distance traveled during each tic of the animation clock.
private const double animation_clock_speed = 45.7; //Hz; how many times per second the coordinates of the ball are updated
private const double refresh_clock_speed = 24.0; //Hz; how many times per second the UI is re-painted
private const double line_segment_width = 2.0; //Width measured in pixels
private const double radius = 6.8; //Radius measured in pixels
private const double millisec_per_sec = 1000.0; //Number of milliseconds per second.
private const double animation_interval = millisec_per_sec/animation_clock_speed; //Units are milliseconds
private const double refresh_clock_interval = millisec_per_sec/refresh_clock_speed; //Units are milliseconds
//Declare variables related to points on the rectangular path.
//P0 = (p0x,p0y) is the starting point.
//P1 = (p1x,p1y) is where the first 90 degree turn occurs.
//P2 = (p2x,p2y) is where the second 90 degree turn occurs.
//P3 = (p3x,p3y) is the stopping point.
private int p0x;
private int p0y;
private int p1x;
private int p1y;
private int p2x;
private int p2y;
private int p3x;
private int p3y;
private Point start_point; //This point will be constructed inside the interface constructor
private Point upper_left_corner_point; //Ditto
private Point lower_left_corner_point; //Ditto
private Point end_point; //Ditto
//Declare variables related to user interface layout.
private Pen schaffer = new Pen(Color.Purple,1);
private Pen bic = new Pen(Color.Red,(int)System.Math.Round(line_segment_width));
private const String welcome_message = "This is a demonstration of turning a sharp 90 degrees";
//The next statement shows how to change font size.
private System.Drawing.Font welcome_style = new System.Drawing.Font("TimesNewRoman",24,FontStyle.Regular);
private Brush welcome_paint_brush = new SolidBrush(System.Drawing.Color.Black);
private Point welcome_location; //Will be initialized in the constructor.
//Declare values that support constructing the interface
private int form_width;
private int form_height;
//The next two variables are coordinates of the upper left corner of the ball.
private double x; //This is x-coordinate of the upper left corner of the ball.
private double y; //This is y-coordinate of the upper left corner of the ball.
private Button go_and_pause_button = new Button();
private Button quit_button = new Button();
private bool clocks_are_stopped = true;
//Declare clocks
private static System.Timers.Timer user_interface_refresh_clock = new System.Timers.Timer();
private static System.Timers.Timer ball_update_clock = new System.Timers.Timer();
//Define the constructor of this class.
public Uifile()
{ //Set the size of the form (window) holding the graphic area: begin with a moderate size half-way between
//maximum and minimum.
form_width = (maximum_form_width+minimum_form_width)/2;
form_height = (maximum_form_height+minimum_form_width)/2;
Size = new Size(form_width,form_height);
//Set the limits regarding how much the user may re-size the window.
MaximumSize = maxframesize;
MinimumSize = minframesize;
//Set the title of this user interface.
Text = "Ninety Degree Turn";
//Give feedback to the programmer.
System.Console.WriteLine("Form_width = {0}, Form_height = {1}.", Width, Height);
//Set the initial background color of this form.
BackColor = Color.MistyRose;
//Set the four key points in the path of the moving ball.
p0x = Width-90; p0y = top_panel_height+70;
start_point = new Point(p0x,p0y); //Starting point
p1x = 80; p1y = p0y;
upper_left_corner_point = new Point(p1x,p1y); //First corner to turn 90 degrees
p2x = p1x; p2y = top_panel_height+Height/2;
lower_left_corner_point = new Point(p2x,p2y); //Second corner to turn 90 degrees
p3x = Width/2; p3y = p2y;
end_point = new Point(p0x,p3y); //Ending point
//Initialize the ball at the starting point: subtract ball's radius so that (x,y) is the upper corner of the ball.
x = (double)p0x-radius;
y = (double)p0y-radius;
//The size (Width and Height) of the form may change during run-time because a user may use the mouse to re-size the form.
//"Width" and "Height" are attributes of this UI called Ninety_degree_turn_interface. They may be used in a read mode as
//ordinary variables. If the user re-sizes the form by say use of the mouse then "Width" and "Height" will be updated
//internally with new values.
// start_Y_coordinate.BackColor = Color.Cyan;
// end_Y_coordinate.BackColor = Color.SeaGreen;
//Configure the go_and_pause button
go_and_pause_button.Size = new Size(60,30);
go_and_pause_button.Text = "Go";
go_and_pause_button.Location = new Point(100,form_height-80);
go_and_pause_button.BackColor = Color.LightPink;
go_and_pause_button.Click += new EventHandler(Go_stop);
//Configure the quit button
quit_button.Size = new Size(60,30);
quit_button.Text = "Quit";
quit_button.Location = new Point(Width-100,Height-80); //Width and Height are attributes of this UI.
quit_button.BackColor = Color.LightPink;
quit_button.Click += new EventHandler(Close_window);
//Prepare the refresh clock. A button will start this clock ticking.
user_interface_refresh_clock.Enabled = false; //Initially this clock is stopped.
user_interface_refresh_clock.Elapsed += new ElapsedEventHandler(Refresh_user_interface);
//Prepare the ball clock. A button will start this clock ticking.
ball_update_clock.Enabled = false;
ball_update_clock.Elapsed += new ElapsedEventHandler(Update_ball_coordinates);
//Add controls (labels, buttons, textboxes, etc) to the form so that the user can see them.
Controls.Add(go_and_pause_button);
Controls.Add(quit_button);
//Prepare for the welcome message.
welcome_location = new Point(Width/2-340,8);
//Use extra memory to make a smooth animation.
DoubleBuffered = true;
}//End of constructor of class Ninety_degree_turn_interface
//===============================================================
protected override void OnPaint(PaintEventArgs a)
{ Graphics displayarea = a.Graphics;
//Next paint a green horizontal strip across the top of the ui.
displayarea.FillRectangle(Brushes.PaleGreen,0,0,Width,top_panel_height); //Gittleman book, p. 302
//Next draw a black horizontal line separating the green title strip from the white graphic area.
displayarea.DrawLine(schaffer,0,top_panel_height,Width,top_panel_height);
displayarea.FillRectangle(Brushes.Thistle,0,form_height-bottom_panel_height,Width,bottom_panel_height);
displayarea.DrawLine(schaffer,0,form_height-bottom_panel_height,Width,form_height-bottom_panel_height);
//The next statement draws a line segment with end points start_point and upper_left_corner_point.
displayarea.DrawLine(bic,start_point,upper_left_corner_point);
//The next statement draws a line segment with end points upper_left_corner_point and lower_left_corner_point.
displayarea.DrawLine(bic,upper_left_corner_point,lower_left_corner_point);
//The next statement draws a line segment with end points lower_left_corner_point and ending_point.
displayarea.DrawLine(bic,lower_left_corner_point,end_point);
displayarea.DrawLine(bic, end_point, start_point);
//Display the title in larger than normal font.
displayarea.DrawString(welcome_message,welcome_style,welcome_paint_brush,welcome_location);
//The next statement outputs the ball using the ball's current coordinates.
displayarea.FillEllipse (Brushes.Blue,
(int)System.Math.Round(x),
(int)System.Math.Round(y),
(int)System.Math.Round(2.0*radius),
(int)System.Math.Round(2.0*radius));
base.OnPaint(a);
}
protected void Refresh_user_interface(System.Object sender, ElapsedEventArgs even) //See Footnote #2
{Invalidate();
}//End of event handler Refresh_user_interface
//====================================================================================================
//This next function computes and updates coordinates. How did the author know how to update the x and y coordinates of the ball.
//Answer: Draw lots of diagrams of lines with a ball on top of the line. It required a lot of diagrams to get the right
//to update the coordinates especially on the corners.
protected void Update_ball_coordinates(System.Object sender, ElapsedEventArgs even)
{//This function is called each time the ball_update_clock makes one tic. That clock is often called the animation clock.
if(System.Math.Abs(y+radius-p0y)<0.5) //Test if the ball is on the top horizontal line segment.
{if(System.Math.Abs(x+radius-(double)p1x)>delta) //Test if there is room to move forward
{//If condition is true then move the ball by amount delta to the left.
x -= delta;
}
else
{//If condition is false make the ball move around the corner and start traveling down.
y = (double)p1y+(delta-(x+radius-(double)p1x));
x = (double)p1x-radius;
}
}//End of if
else if(System.Math.Abs(x+radius-(double)p1x)<0.5) //If this is true then the ball is on the line segment from upper_left_corner_point to lower_left_corner_point
{if(System.Math.Abs((double)p2y-(y+radius))>delta)
{//If condition is true then move the ball by amount delta downward.
y = y+delta;
}
else
{//If condition is false then move the ball around the corner and begin traveling right.
x = (double)p2x+(delta-((double)p2y-(y+radius)));
y = (double)p2y-radius;
}//End of most recent else
}
else if(System.Math.Abs(y+radius-(double)p2y)<0.5) //If this is true then the ball is on the lower line segment traveling to the right.
{if(System.Math.Abs((double)p3x-(x+radius))>delta)
{//If the condition is true then move the ball right by the amount delta
x = x + delta;
}
else
{//If the condition is false then distance between the ball and the destination point (p3x,p3y) is less than delta. Make one last move and stop.
x = (double)p3x;
y = (double)p3y-radius;
user_interface_refresh_clock.Enabled = false;
ball_update_clock.Enabled = false;
go_and_pause_button.Text = "Done";
go_and_pause_button.Enabled = false;
System.Console.WriteLine("The program has finished. You may close the window.");
}//End of else part
}//End of nested ifs
}//End of method Update_ball_coordinates
//============================================================
protected void Go_stop(System.Object sender, EventArgs even)
{if(clocks_are_stopped)
{//Start the refresh clock running.
user_interface_refresh_clock.Enabled = true;
//Start the animation clock running.
ball_update_clock.Enabled = true;
//Change the message on the button
go_and_pause_button.Text = "Pause";
}
else
{//Stop the refresh clock.
user_interface_refresh_clock.Enabled = false;
//Stop the animation clock running.
ball_update_clock.Enabled = false;
//Change the message on the button
go_and_pause_button.Text = "Go";
}
//Toggle the variable clocks_are_stopped to be its negative
clocks_are_stopped = !clocks_are_stopped;
}//End of event handler Go_stop
//==============================================================
protected void Close_window(System.Object sender, EventArgs even)
{System.Console.WriteLine("This program will close its window and end execution.");
Close();
}//End of event handler Go_stop
}//End of class Straight_line_form
<file_sep>/assignment_6/uifile.cs
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
public class uifile:Form{
private Button go_button = new Button();
private Button pause_button = new Button();
private Button exit_button = new Button();
private const int form_height = 900;
private const int form_width = 1200;
private const int bottomPanel_height = 75;
private int bottomPanel_Location;
private Pen pen_tool = new Pen(Color.Red, 1);//color, size = 1 pixels wide
private SolidBrush brushes = new SolidBrush(Color.MistyRose);
private Rectangle bottompanel = new Rectangle(0,form_height- bottomPanel_height, form_width, bottomPanel_height);
private Font font_style = new System.Drawing.Font("Times New Roman", 11, FontStyle.Regular);
//mathematical constants and others that are needed to run the function
private const double scale_factor = 100; //this is 100 pixels, will be needed to most likely seperate the tic marks on the x and y axis
private const double origin = 40.0; //the origin is located 40 pixels away from the left side of the user interace
private const double refresh_rate = 88.8; //frequency in Hertz, how many times per second is the display area repainted. so 888 times per second
private const double dot_update_rate = 55.5; //frequence measured in Herz, how many times per second is the coordinate's of the dot being updated
private const double time_converter = 1000.0; //number of miliseconds per second
//private const double delta = 0.015; //this number is free to be changed. smaller delta, smoother anmiation but slower animation, big delta, faster motion but jerky animation.
//private Point origin_center = new Point(form_width/2, form_height/2); //we assign the point to be at th center of the UI screen
private const int origin_center_x = form_width/2;
private const int origin_center_y = form_height/2;
private Point origin_center_x_point_left = new Point(0, form_height/2);
private Point origin_center_x_point_right = new Point(form_width, form_height/2);
private Point origin_center_y_point_top = new Point(form_width/2, 0);
private Point origin_center_y_point_bottom = new Point(form_width/2, form_height);
private String x_coordinate_string = "";
private String y_coordinate_string = "";
private static System.Timers.Timer ball_refresh_clock = new System.Timers.Timer();
private const double ball_refresh_clock_rate = 43.5; //the ball will be updated 43.5 per second, meaning it will be repained 43.5 times per second
private static System.Timers.Timer monitor_refresh_clock = new System.Timers.Timer();
private const double monitor_refresh_clock_rate = 23.3; //measured in Hz. will refresh 23.3 times per second
private const double radius_tic = 2.0; //radius of the presumed tic marks that reprsent where certain numbers are on the axis.
//declare these const values later..like maybe at the origin and then move them according to the function that we end up choosing?
private const double ball_center_initial_coordinate_x = form_width/2;
private const double ball_center_initial_coordinate_y = form_height/2;
private double ball_center_coordinate_x;
private double ball_center_coordinate_y;
private double ball_center_coordinate_x_original;
private double ball_center_coordinate_y_original;
private double x_coordinate_rounded;
private double y_coordinate_rounded;
private int first_iteration;
private const double linear_speed = 44.5; //moving 44.5 pixels per second
//ball direction variables
private double delta = .15;
private System.Drawing.Graphics pointer_to_surface;
private System.Drawing.Bitmap bitmap_pointer;
public uifile(){
BackColor = Color.PowderBlue;
Size = new Size(form_width, form_height);
bitmap_pointer = new Bitmap(form_width, form_height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
pointer_to_surface = Graphics.FromImage(bitmap_pointer);
initialize_bitmap();
// ball_center_coordinate_x = ball_center_initial_coordinate_x;
// ball_center_coordinate_y = ball_center_initial_coordinate_y;
monitor_refresh_clock.Enabled = false;
monitor_refresh_clock.Elapsed += new ElapsedEventHandler(update_display);
ball_refresh_clock.Enabled = false;
ball_refresh_clock.Elapsed += new ElapsedEventHandler(update_ball_position); //everytime this tics, we are taken to the function update+update_ball_position
bottomPanel_Location = form_height - bottomPanel_height;
// bottomPanel_Location_LeftPoint = new Point(0,bottomPanel_Location);
// bottomPanel_Location_RightPoint = new Point(form_width, bottomPanel_Location);
int width_measuring_tool = 0;
int height_measuring_tool = bottomPanel_Location + 2;
go_button.Location = new Point(width_measuring_tool += 5, height_measuring_tool);
go_button.BackColor = Color.Pink;
go_button.Text = "Go";
pause_button.Location = new Point(width_measuring_tool += 5 + go_button.Width, height_measuring_tool);
pause_button.BackColor = Color.Pink;
pause_button.Text = "Pause";
exit_button.Location = new Point( form_width - 15 - exit_button.Width, height_measuring_tool);
exit_button.BackColor = Color.Pink;
exit_button.Text = "Exit";
go_button.Click += new EventHandler(go_click);
pause_button.Click += new EventHandler(pause_resume_click);
exit_button.Click += new EventHandler(exit_click);
Controls.Add(go_button);
Controls.Add(pause_button);
Controls.Add(exit_button);
}//end of public uifile function
protected void initialize_bitmap(){
pointer_to_surface.Clear(System.Drawing.Color.White);
brushes.Color = Color.MistyRose;
pointer_to_surface.FillRectangle(brushes, bottompanel);
System.Console.WriteLine("this has been called on");
//drawing the x and y axis, without tic marks
pen_tool.Color = Color.Black;
pointer_to_surface.DrawLine(pen_tool, origin_center_x_point_left, origin_center_x_point_right);
pointer_to_surface.DrawLine(pen_tool, origin_center_y_point_top, origin_center_y_point_bottom);
/*as for making the tic marks, let's just make a for loop, where a certain variable holds an invisible dot that moves along the x axis and makes a tic mark at ever [n] amounts of pixels
and after it reaches the half way point, the labels become positive or negative, whichever way the dot is going originally*/
brushes.Color = Color.Red;
int tic_mark_number = -15;
for(int x = 0; x < form_width; x += 40){ //for every 40 pixels, we will add a dot and a label for the x-axis
x_coordinate_string = tic_mark_number.ToString();
pointer_to_surface.FillEllipse(brushes, x, origin_center_y-2, 4, 6);
pointer_to_surface.DrawString(x_coordinate_string, font_style,brushes, x , origin_center_y + 3);
tic_mark_number += 1;
}
tic_mark_number = -11;
for(int y =0; y < form_height; y+= 40){ //for every 40 pixels we add a dot and a label for the y-axis
y_coordinate_string = tic_mark_number.ToString();
pointer_to_surface.FillEllipse(brushes, origin_center_x-2, y, 4, 6);
pointer_to_surface.DrawString(y_coordinate_string, font_style, brushes, origin_center_x+3, y);
if(tic_mark_number == 9){break;}
tic_mark_number += 1;
}
}
protected void go_click(Object sender, EventArgs e){ //every time this functoin (ball_refresh_clock) tics, we will be directed to the function update_ball_position;
start_graphics(monitor_refresh_clock_rate);
start_ball_motion(ball_refresh_clock_rate);
}
protected void pause_resume_click(Object sender, EventArgs e){
pause_button.Text = "Resume";
}
protected void exit_click(Object sender, EventArgs e){
System.Console.WriteLine("Now exiting program.....");
Close();
}
protected void update_ball_position(System.Object sender, ElapsedEventArgs e){
first_iteration +=1;
ball_center_coordinate_x = (1+ System.Math.Cos(2*delta))*System.Math.Cos(delta);
ball_center_coordinate_y = (1+System.Math.Cos(2*delta))*System.Math.Sin(delta);
ball_center_coordinate_x *= 90;
ball_center_coordinate_x += form_width/2;
ball_center_coordinate_y *= 90;
ball_center_coordinate_y += form_height/2;
x_coordinate_rounded = System.Math.Round(ball_center_coordinate_x);
y_coordinate_rounded = System.Math.Round(ball_center_coordinate_y);
if(x_coordinate_rounded == ball_center_coordinate_x_original){
System.Console.WriteLine("The curve is repeating itself, nothing new will be outputted");
}
if(first_iteration == 1){
ball_center_coordinate_x_original = System.Math.Round(ball_center_coordinate_x);
ball_center_coordinate_y_original = System.Math.Round(ball_center_coordinate_y);
}
// System.Console.WriteLine("x-coordinate = " + ball_center_coordinate_x);
delta += .015;
brushes.Color = Color.HotPink;
pointer_to_surface.FillEllipse(brushes, (float)ball_center_coordinate_x, (float)ball_center_coordinate_y, 4,4);
}
protected override void OnPaint(PaintEventArgs ee){
Graphics g = ee.Graphics;
g.DrawImage(bitmap_pointer, 0,0,form_width,form_height);
base.OnPaint(ee);
}
protected void start_graphics(double monitor_refresh_clock_rate) {
//stuff: don't forget to add arg
double actual_refresh_rate = 1.0;
double elapsed_time_between_tics;
if(monitor_refresh_clock_rate > actual_refresh_rate){
actual_refresh_rate = monitor_refresh_clock_rate;
}
elapsed_time_between_tics = 1000.0/actual_refresh_rate;
monitor_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_tics);
monitor_refresh_clock.Enabled = true;
}
protected void start_ball_motion(double update_rate){
//stuff: don't forget to add arg
double elapsed_time_between_ball_moves;
if(update_rate < 1.0) {update_rate = 1.0;}
elapsed_time_between_ball_moves = 1000.0/update_rate;
ball_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_ball_moves);
ball_refresh_clock.Enabled = true;
}
protected void update_display(System.Object sender, ElapsedEventArgs e){
Invalidate();
if(!ball_refresh_clock.Enabled){
monitor_refresh_clock.Enabled = false;
System.Console.WriteLine("The graphical interface has stopped refreshing. you may not exit the program");
}
}
}//end of public class uifile:Form
<file_sep>/assignment_0/filebuild.sh
echo First remove old binary files
rm *.dll
rm *.exe
echo View the list of source files
ls -l
echo Compile Selectui.cs to create the file: Selectui.dll
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -out:Selectui.dll Selectui.cs
echo Compile main.cs and link the two previously created dll files to create an executable file.
mcs -r:System -r:System.Windows.Forms -r:Selectui.dll -out:Assignment.exe Main.cs
echo View the list of files in the current folder
ls -l
echo Run the Assignment 1 program.
./Assignment.exe
echo The script has terminated.
<file_sep>/assignment_1/UiFile.cs
/*========================================================================================================================================================================
NOTE:
In order to keep the circle sizes true to their original values of 200px,400px,600px I have extended the graphical graphareawidth and graphareaheight to
fit the the circles to 1400px wide and 1400px long. I can send in a different UiFile.cs that has smaller dimensions for the circle so they may appear for
smaller screens
==========================================================================================================================================================================*/
using System;
using System.Drawing;
using System.Windows.Forms;
public class UiFile:Form{
//add controls
//color add controls
private Button rfirst = new Button();
private Button gsecond = new Button();
private Button bthird = new Button();
//size add controls
private Button smallsize = new Button();
private Button mediumsize = new Button();
private Button bigsize = new Button();
//functionality add controls
private Button enterbutton = new Button();
private Button clearbutton = new Button();
private Button exitbutton = new Button();
//default colors
Color color200 = Color.Pink;
Color color400 = Color.Pink;
Color color600 = Color.Pink;
Color c = Color.Pink;
int radius = 200;
//`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~``
public UiFile(){
BackColor = Color.Pink;
//set the captions for the buttons
Text = "Assignment 1: Drawing Circles";
rfirst.Text = "Red";
gsecond.Text = "Green";
bthird.Text = "Blue";
smallsize.Text = "200 px";
mediumsize.Text = "400 px";
bigsize.Text = "600 px";
enterbutton.Text = "Enter";
clearbutton.Text = "Clear";
exitbutton.Text = "Exit";
//select the size of the Window
Size = new Size(1500,1500);
//set location of buttons
int b =1275;
rfirst.Location = new Point (50, b);
gsecond.Location = new Point (50, b += 5 + rfirst.Height);
bthird.Location = new Point (50, b += 5 + gsecond.Height); //385 + rfirst.Height + 5);
int q = 1275;
smallsize.Location = new Point(60+ rfirst.Width +10, q);
mediumsize.Location = new Point (60+ gsecond.Width+10, q += 5 + mediumsize.Height);
bigsize.Location = new Point (60+bthird.Width+10, q+= 5 + mediumsize.Height);
int z = 1275;
enterbutton.Location = new Point (150 + smallsize.Width + 20, z);
clearbutton.Location = new Point(150 + mediumsize.Width + 20, z += 5 + enterbutton.Height);
exitbutton.Location = new Point (150 + bigsize.Width+ 20, z += 5 + clearbutton.Height);
//add controls to the Form
Controls.Add(rfirst);
Controls.Add(gsecond);
Controls.Add(bthird);
Controls.Add(smallsize);
Controls.Add(mediumsize);
Controls.Add(bigsize);
Controls.Add(enterbutton);
Controls.Add(clearbutton);
Controls.Add(exitbutton);
//end of add controls to the form
//EventHandler
gsecond.Click += new EventHandler(Greenclick);
rfirst.Click += new EventHandler(RedClick);
bthird.Click += new EventHandler(BlueClick);
smallsize.Click += new EventHandler(smallClick);
mediumsize.Click += new EventHandler(mediumClick);
bigsize.Click += new EventHandler(largeClick);
exitbutton.Click += new EventHandler(exitClick);
//need to do
enterbutton.Click += new EventHandler(DrawFunction);
clearbutton.Click += new EventHandler(clearClick);
}//end of UiFile public
//set buttons for radius size
protected void smallClick(Object sender, EventArgs e){radius = 200;}
protected void mediumClick(Object sender, EventArgs e){radius = 400;}
protected void largeClick(Object sender, EventArgs e){radius = 600;}
//set buttons for color
protected void Greenclick(Object sender, EventArgs e){c=Color.Green;}
protected void BlueClick(Object sender, EventArgs e){c=Color.Blue;}
protected void RedClick(Object sender, EventArgs e){c= Color.Red;}
//switch case that handles which radius is clicked on and assigns the color
protected void DrawFunction(Object sender, EventArgs e){ //dummy parameters
switch(radius)
{
case 200:
color200=c;
break;
case 600:
color600=c;
break;
case 400:
color400=c;
break;
}
Invalidate(); //this calls the OnPaint function.
}
//draws onto the screen
protected override void OnPaint(PaintEventArgs anything){
Graphics area = anything.Graphics;
System.Drawing.Rectangle r = new System.Drawing.Rectangle();
//makes a copy of the class Graphics
Pen pen = new Pen(Brushes.Pink,3);
pen.Color = color200; //this gives us something to write with
r = CircleAlgorithms.getcircleinfo(1500,1260,200);
area.DrawEllipse(pen, r); //we're doubling to make the diameter
pen.Color = color400;
r = CircleAlgorithms.getcircleinfo(1500,1260,400);
area.DrawEllipse(pen, r);
pen.Color = color600;
r = CircleAlgorithms.getcircleinfo(1500,1260,600);
area.DrawEllipse(pen, r);
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.SkyBlue);
// Create rectangle.
Rectangle rect = new Rectangle(0, 1260, 1500, 1500);
// Fill rectangle to screen.
anything.Graphics.FillRectangle(blueBrush, rect);
//area.FillRectangle(pen, 0,360,1000,900);
base.OnPaint(anything);
}
protected void exitClick(Object sender, EventArgs e){
System.Console.WriteLine("This program will end execution.");
Close();
}
//handles switching the colors back to "clear" or in this case back to pink
protected void clearClick(Object sender, EventArgs e){
switch(radius){
case 200:
color200=Color.Pink;
break;
case 400:
color400=Color.Pink;
break;
case 600:
color600 = Color.Pink;
break;
}
Invalidate();
}
}//end of UiFile form
<file_sep>/assignment_4/main.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class selectmain{
static void Main(){
double speed = 81.9;
double v = 37.2;
double w = 21.8;
uifile userface = new uifile(speed,v,w);
Application.Run(userface);
}
}
<file_sep>/assignment_4/run.sh
echo First remove old binary files
rm *.dll
rm *exe
echo view the list of source files
ls -l
echo compile the uifile.cs to create the file uifile.dll
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms -out:uifile.dll uifile.cs
#more stuff here
echo compile the run.sh and link the pervious created dll files to create an executable file
mcs -r:System.Windows.Forms -r:System.Drawing.dll -r:uifile.dll -out:application4.exe main.cs
echo view the list of the files in the folder
ls -l
echo Run the Assingment4 program
./application4.exe
echo [THE SCRIPT HAS ENDED NOW]
<file_sep>/assignment_0/Main.cs
using System;
using System.window.Forms;
public class selectui.cs{
static void Main(){
system.Console.writeline("This is Assignment 0");
Selectui userface = new Selectui();
Application.Run(userface);
system.Console.writeline("I hope you enjoyed this");
}
}
<file_sep>/midterm_1/run.sh
echo First remove old binary files
rm *.dll
rm *.exe
echo View the list of source files
ls -l
echo "Compile the file ninety-degree-ui.cs:"
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -out:Uifile.dll Uifile.cs
echo "Compile and link ninety-degree-main.cs:"
mcs -r:System -r:System.Windows.Forms -r:Uifile.dll -out:starting.exe main.cs
echo "Run the program Ninety Degree Turn"
./starting.exe
echo "The bash script has terminated."
<file_sep>/assignment_4/uifile.cs
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
public class uifile:Form{
/*
((((((((((((((((((((((((((((((((((((((((((((((what needs to be done))))))))))))))))))))))))))))))))))))))))))))))
[x] = done
[] = not done
[] need to resize the bottom panel width to specifications
[] need to make TextBox for the appropiate labels and input values asked for
(((((((((((((((((((((((((((((((((((((((((((((((((((((((()(end)))))))))))))))))))))))))))))))))))))))))))))))))))))))*/
private Button newbutton = new Button();
private Button start = new Button();
private Button quit = new Button();
private Label pixelSpeed = new Label();
private Label directionDeg = new Label();
private Label xCoordinate = new Label();
private Label yCoordinate = new Label();
private Label CoordinateTitle = new Label();
private Label RefreshTitle = new Label();
private TextBox RefreshTitleInput = new TextBox(); //done
private Label xCoordinatebox = new Label();
//private TextBox xCoordinateInput = new TextBox();
private Label yCoordinatebox = new Label();
private TextBox yCoordinateInput = new TextBox();
private Label directionDegbox = new Label();
private TextBox directionDegInput = new TextBox();
private Brush brushes = new SolidBrush(System.Drawing.Color.Pink);
private Pen pens = new Pen (Color.SlateGray, 2);
private const int formheight = 900;
private const int formwidth = 850;
private const int bottomPanelHeight = 180;
private int bottomPanel_Location=0;
private const double ball_center_initial_coordinate_x = (double)formwidth*0.65;
private const double ball_center_initial_coordinate_y = (double)formheight/2.0+ 80;
private double ball_center_coordinate_x;
private double ball_center_coordinate_y;
private double ball_upper_left_x;
private double ball_upper_left_y;
private const double radius = 8.5;
private double ball_delta_x;
private double ball_delta_y;
private double ball_direction_x;
private double ball_direction_y;
private double ball_linear_speed_pix_per_sec;
private double ball_linear_speed_pix_per_tic;
private Point panelHeight;
private Point panelWidth;
//stuff
//data for motion ball
private static System.Timers.Timer ball_refresh_clock = new System.Timers.Timer();
private const double ball_refresh_clock_rate = 43.5; //measured in Hz
private static System.Timers.Timer monitor_refresh = new System.Timers.Timer();
private const double monitor_refresh_rate = 23.3; //will refresh 23.3 times per second
//next we need to make the corners of the square/rectangle which encapsulates the ball as it moves
public uifile(double speed, double v, double w){
//declarations
ball_linear_speed_pix_per_sec = speed;
ball_direction_x = v;
ball_direction_y = w;
ball_linear_speed_pix_per_tic = ball_linear_speed_pix_per_sec/ball_refresh_clock_rate;
double hyp_squared = ball_direction_x*ball_direction_x + ball_direction_y*ball_direction_y;
double hyp = System.Math.Sqrt(hyp_squared);
ball_delta_x = ball_linear_speed_pix_per_tic*ball_direction_x / hyp;
ball_delta_y = ball_linear_speed_pix_per_tic*ball_direction_y / hyp;
ball_center_coordinate_x = ball_center_initial_coordinate_x;
ball_center_coordinate_y = ball_center_initial_coordinate_y;
ball_refresh_clock.Enabled = false;
ball_refresh_clock.Elapsed += new ElapsedEventHandler(Update_ball_position);
monitor_refresh.Enabled = false;
monitor_refresh.Elapsed += new ElapsedEventHandler(Update_display);
Size = new Size(formwidth, formheight);
BackColor = Color.MistyRose;
bottomPanel_Location = formheight - bottomPanelHeight;
int a=0; //maybe need?
newbutton.Location = new Point(a += 10, bottomPanel_Location+20);
newbutton.BackColor = Color.LightPink;
newbutton.Text = "New";
start.Location = new Point ( a += newbutton.Width + 45, bottomPanel_Location+20);
start.BackColor = Color.LightPink;
start.Text = "Start";
quit.Location = new Point (a += start.Width + 45, bottomPanel_Location+20);
quit.BackColor = Color.LightPink;
quit.Text = "Quit";
int b = 0;
RefreshTitle.Location = new Point (b += 10, b += bottomPanel_Location + newbutton.Height + 30);
RefreshTitle.BackColor = Color.SeaShell;
RefreshTitle.Text = "Refresh rate (Hz)";
RefreshTitleInput.Location = new Point(10,b+ RefreshTitle.Height + 10);
RefreshTitleInput.BackColor = Color.SeaShell;
RefreshTitleInput.Text = "XX.XX";
int c=0;
pixelSpeed.Location = new Point(c += RefreshTitle.Width + 45, b);
pixelSpeed.BackColor = Color.SeaShell;
pixelSpeed.Text = "Speed (pixel/second)";
pixelSpeed.Size = new Size(pixelSpeed.Width + 20, pixelSpeed.Height);
directionDeg.Location = new Point(c+= pixelSpeed.Width + 45 , b);
directionDeg.BackColor = Color.SeaShell;
directionDeg.Text = "Direction (degrees)";
directionDeg.Size = new Size(directionDeg.Width + 10, directionDeg.Height);
int xcoordsize =0;
xCoordinate.Location = new Point (c+= directionDeg.Width + 50, b);
xCoordinate.BackColor = Color.SeaShell;
xCoordinate.Text = " X = ";
xCoordinate.Size = new Size(xcoordsize += xCoordinate.Width-60, xCoordinate.Height);
yCoordinate.Location = new Point (c, b+ xCoordinate.Height + 10);
yCoordinate.BackColor = Color.SeaShell;
yCoordinate.Text = " Y = ";
yCoordinate.Size = new Size(yCoordinate.Width -60, yCoordinate.Height);
xCoordinatebox.Location = new Point(c += xCoordinate.Width + 10, b);
xCoordinatebox.BackColor = Color.SeaShell;
xCoordinatebox.Text = "" + ball_center_coordinate_x;
xCoordinate.Size = new Size(xcoordsize, xCoordinatebox.Height);
yCoordinatebox.Location = new Point(c, b+yCoordinate.Height+ 10);
yCoordinatebox.BackColor = Color.SeaShell;
yCoordinatebox.Text = ""+ ball_center_coordinate_y;
yCoordinatebox.Size = new Size(xcoordsize, yCoordinate.Height);
panelHeight = new Point(0, bottomPanel_Location);
panelWidth = new Point (formwidth, bottomPanel_Location);
//adding the stuff to the controls
Controls.Add(newbutton);
Controls.Add(start);
Controls.Add(quit);
Controls.Add(RefreshTitle);
Controls.Add(RefreshTitleInput); //to do
Controls.Add(pixelSpeed);
Controls.Add(directionDeg);
Controls.Add(xCoordinate);
Controls.Add(yCoordinate);
Controls.Add(xCoordinatebox);
Controls.Add(yCoordinatebox);
quit.Click += new EventHandler(quit_click);
start.Click += new EventHandler(start_click);
//newbutton.Click += new EventHandler(newbutton_click);
//text box inputs will be done and reassigned in the newbutton button
//other stuff
}//end of class uifile
protected void quit_click(Object sender, EventArgs e){
Close();
}
protected override void OnPaint(PaintEventArgs ee){
Graphics g = ee.Graphics;
// g.DrawRectangle(pens, formwidth, bottomPanel_Location, formwidth, bottomPanelHeight);
g.DrawLine(pens, panelWidth, panelHeight);
g.DrawRectangle(pens, 0, bottomPanel_Location, formwidth, formheight);
g.FillRectangle(brushes, 0, bottomPanel_Location, formwidth, formheight);
ball_upper_left_x = ball_center_coordinate_x - radius;
ball_upper_left_y = ball_center_coordinate_y - radius;
g.FillEllipse(Brushes.Red, (int)ball_upper_left_x, (int)ball_upper_left_y, (float)(2.0*radius), (float)(2.0*radius));
base.OnPaint(ee);
}
protected void start_click(Object sender, EventArgs e){
start_graphics(monitor_refresh_rate);
start_ball_motion(ball_refresh_clock_rate);
start.Text = "pause";
}
protected void start_graphics(double monitor_rate){
double actual_refresh_rate = 1.0;
double elapsed_time_between_tics;
if(monitor_rate > actual_refresh_rate){
actual_refresh_rate = monitor_rate;
}
elapsed_time_between_tics = 1000.0/actual_refresh_rate;
monitor_refresh.Interval = (int)System.Math.Round(elapsed_time_between_tics);
monitor_refresh.Enabled = true;
}//end of start_graphics
protected void start_ball_motion(double update_rate){
double elapsed_time_between_ball_moves;
if(update_rate < 1.0) {update_rate = 1.0;}
elapsed_time_between_ball_moves = 1000.0/update_rate;
ball_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_ball_moves);
ball_refresh_clock.Enabled = true;
}//end of start_ball_motion
protected void Update_display(System.Object sender, ElapsedEventArgs evt){ //this is called after update ball position
Invalidate();
if(!ball_refresh_clock.Enabled){
monitor_refresh.Enabled = false;
System.Console.WriteLine("The graphical interface is no longer refreshing. You may now exit the program");
start.Text = "Start";
}//end of if statment
}//end of Update_display
protected void Update_ball_position(System.Object sender, ElapsedEventArgs evt){ //this is called first
ball_center_coordinate_x += ball_delta_x;
ball_center_coordinate_y -= ball_delta_y;
if((int)System.Math.Round(ball_center_coordinate_x + radius) >= formwidth)
{ball_delta_x = -ball_delta_x;}
if((int)System.Math.Round(ball_center_coordinate_x - radius) <= 0)
ball_delta_x = -ball_delta_x;
if((int)System.Math.Round(ball_center_coordinate_y + radius) <= 0)
ball_delta_y = -ball_delta_y;
if((int)System.Math.Round(ball_center_coordinate_y - radius) >= bottomPanel_Location)
ball_delta_y = -ball_delta_y;
xCoordinatebox.Text = "" + (double)System.Math.Round(ball_center_coordinate_x,2);
yCoordinatebox.Text = "" + (double)System.Math.Round(ball_center_coordinate_y,2);
}
}//end of public Form
<file_sep>/assignment_2/Uifile.cs
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
public class Uifile:Form{
//add controls
private Button start = new Button();
private RadioButton slow = new RadioButton();
private RadioButton medium = new RadioButton();
private RadioButton fast = new RadioButton();
private Button pause = new Button();
private Button exit = new Button();
private static System.Timers.Timer message_clock = new System.Timers.Timer();
private int message_counter = 0;
private int temp_count =0;
private int timeRed = 4000;
private int timeYellow = 3000;
private int timeGreen = 1000;
private Brush paint_brush = new SolidBrush(System.Drawing.Color.Gray);
//default values
int radiusLight = 50;
Color Graylight = Color.Gray;
public Uifile(){
BackColor = Color.Pink;
//add text to the buttons and title
Text = "Assignment 2: Making a clock";
start.Text = "Start";
slow.Text = "slow";
medium.Text= "medium";
fast.Text = "fast";
pause.Text = "Pause";
exit.Text = "Exit";
message_clock.Enabled = false;
message_clock.Elapsed += new ElapsedEventHandler(manage_messages);
message_clock.Interval = 5;
//message_clock.Enabled = true;
//adding button locations
Size = new Size(700,700);
int a = 500;
int x = 50;
start.Location = new Point(x,a);
pause.Location = new Point (x, a +start.Height+10);
slow.Location = new Point(x += 10 + start.Width, a);
medium.Location = new Point( x += 2 + slow.Width, a);
fast.Location = new Point (x += 2 + medium.Width, a);
exit.Location = new Point (x += 10+ fast.Width, a);
//add controls to Form
Controls.Add(start);
Controls.Add(slow);
Controls.Add(medium);
Controls.Add(fast);
Controls.Add(pause);
Controls.Add(exit);
//make the evenhandlers
//times.Click += new EventHandler(times_Click);
start.Click += new EventHandler(startClick);
pause.Click += new EventHandler(pauseClick);
exit.Click += new EventHandler(exitClick);
// slow.CheckedChanged += new EventHandler(Check_Changed);
// medium.CheckedChanged += new EventHandler(Check_Changed);
// fast.CheckedChanged += new EventHandler(Check_Changed);
}
//functions go here
protected void exitClick(Object sender, EventArgs e){
System.Console.WriteLine("This program will end execution now");
Close();
}
protected void startClick(Object sender, EventArgs e){
//do timer stuff
System.Console.WriteLine("the sytem has started");
message_clock.Enabled = true;
Invalidate();
}
protected void pauseClick(Object sender, EventArgs e){
//do pause timer stuff
System.Console.WriteLine("the system has paused. the message counter is:" + message_counter);
message_clock.Enabled = false;
}
protected void drawingstuff(PaintEventArgs e){
Graphics d = e.Graphics;
Pen pens = new Pen(Color.Black, 3);
d.DrawEllipse(pens, 250,10,150,150); //first circle
d.DrawEllipse(pens, 250, 170, 150,150); //second circle
d.DrawEllipse(pens, 250,330, 150,150); //third circle
if(message_clock.Enabled == false){
d.FillEllipse(paint_brush, 250, 11, 150, 150);
d.FillEllipse(paint_brush, 250, 171,150,150);
d.FillEllipse(paint_brush, 250, 330, 149, 149);
}
Invalidate();
}
protected override void OnPaint(PaintEventArgs e){
Graphics g = e.Graphics;
switch(message_counter){
case 1:
g.FillEllipse(paint_brush, 250, 11, 150, 150);
g.FillEllipse(paint_brush = Brushes.Gray, 250, 171,150,150);
g.FillEllipse(paint_brush = Brushes.Gray, 250, 330, 149, 149);
break;
case 2: g.FillEllipse(paint_brush, 250, 171,150,150);
g.FillEllipse(paint_brush = Brushes.Gray, 250, 11, 150, 150);
g.FillEllipse(paint_brush = Brushes.Gray, 250, 330, 149, 149);
break;
case 0: g.FillEllipse(paint_brush, 250, 330, 149, 149);
g.FillEllipse(paint_brush = Brushes.Gray, 250, 11, 150, 150);
g.FillEllipse(paint_brush = Brushes.Gray, 250, 171,150,150);
break;
}
base.OnPaint(e);
}
protected void manage_messages(System.Object sender, ElapsedEventArgs ea ){
System.Console.WriteLine("message_counter before calling the function:[ " + message_counter);
if(slow.Checked){
timeRed = 4000;
timeYellow = 1000;
timeGreen = 3000;
}
else if(medium.Checked){
timeRed = 2000;
timeYellow = 500;
timeGreen = 1500;
}
else if(fast.Checked){
timeRed = 1000;
timeYellow = 250;
timeGreen = 750;
}
message_counter = Clock_Algorithms.set_display(message_counter, ref message_clock, ref paint_brush, timeRed, timeYellow, timeGreen);
System.Console.WriteLine("message_counter after calling the function: [ " + message_counter);
Invalidate();
}
}//end of Ui Form
/* NOTE
when we have the following function:
protected override void OnPaint(PaintEventArgs e){
Graphics g = e.Graphics;
Pen pens = new Pen(Color.Black, 3);
//Ellipse circle1 = new Ellipse(pens, 250,10,150,150);
g.DrawEllipse(pens, 250,10,150,150);
g.FillEllipse(paint_brush, 250, 11, 150, 150);
g.DrawEllipse(pens, 250, 170, 150,150);
g.FillEllipse(paint_brush, 250, 171,150,150);
g.DrawEllipse(pens, 250,330, 150,150);
g.FillEllipse(paint_brush, 250, 330, 149, 149);
base.OnPaint(e);
}
the colors for each circle light up instead of just one circle lighting up at it's called time.
we need to make switch statements that come from message counter to handle the switch statements
*/
<file_sep>/assignment_7/Sinewave.cs
using System;
using System.Windows.Forms; //Needed for "Application" near the end of Main function.
public class Sinewave
{ public static void Main()
{ System.Console.WriteLine("The Sine Wave program has begun.");
Sineframe sineapp = new Sineframe();
Application.Run(sineapp);
System.Console.WriteLine("This Sine Wave program has ended. Bye.");
}//End of Main function
}//End of Sinewave class
<file_sep>/assignment_5/main.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class selectmain{
static void Main(){
uifile userface = new uifile();
Application.Run(userface);
}
}
<file_sep>/assignment_3/Uifile.cs
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
public class Uifile:Form{
private bool clocks_are_stopped = true;
//Declare clocks
private static System.Timers.Timer user_interface_refresh_clock = new System.Timers.Timer();
private static System.Timers.Timer ball_update_clock = new System.Timers.Timer();
private const int max_width = 900;
private const int max_height = 900;
private Button Go = new Button();
private Button Reset = new Button();
private Button Stop = new Button();
private Label speedBoxLabel = new Label();
private TextBox SpeedBox = new TextBox();
private double Hzspeed;
private Pen otherpen = new Pen(Color.Green, 2);
private Pen pens = new Pen(Color.HotPink,(int)System.Math.Round(line_width));
private const double radius = 7.5;
private const double line_width = 2.0;
private double x;
private double y;
private const double delta = 8.972;
private int p0x;
private int p0y;
private int p1x;
private int p1y;
private int p2x;
private int p2y;
private int p3x;
private int p3y;
private Point starting_point;
private Point upper_left;
private Point lower_left;
private Point end_point;
//end will = starting_point
public Uifile(){
starting_point = new Point(p1x += max_width-20, p1y += max_height -880);
BackColor = Color.MistyRose;
Text = "Assignment 3";
Go.Text = "Go";
Reset.Text = "Reset";
Stop. Text = "Stop";
Size = new Size (max_width, max_height); //size of the form or window
//Configure speedbox input box
//NOTE: need to make a rectangle that supplies more information about speedbox in ui
speedBoxLabel.Text = "Enter speed in Hz: ";
speedBoxLabel.Size = new Size(speedBoxLabel.Width + 10, speedBoxLabel.Height + 3);
speedBoxLabel.Location = new Point(110, max_height - 150);
speedBoxLabel.BackColor = Color.LightPink;
int a = 110 + speedBoxLabel.Width;
SpeedBox.Location = new Point (a += 5, max_height-150);
SpeedBox.BackColor = Color.Snow;
SpeedBox.Text = "enter here";
Go.Location = new Point(a += SpeedBox.Width + 20, max_height - 150);
Go.BackColor = Color.LightPink;
Reset.Location = new Point(a += Go.Width + 10, max_height - 150);
Reset.BackColor = Color.LightPink;
Stop.Location = new Point(a += Reset.Width + 10, max_height - 150);
Stop.BackColor = Color.LightPink;
AcceptButton = Go;
Controls.Add(SpeedBox);
Controls.Add(speedBoxLabel);
Controls.Add(Go);
Controls.Add(Reset);
Controls.Add(Stop);
Stop.Click += new EventHandler(stopclick);
Go.Click += new EventHandler(goclick);
p0x = max_width - 110;
p0y = max_height - 10;
starting_point = new Point (p0x, p0y);
}//end of public UI function
protected void stopclick(Object sender, EventArgs e){
System.Console.WriteLine("This program will now end execution");
Close();
}
protected void goclick(Object sender, EventArgs e){
Hzspeed = Double.Parse(SpeedBox.Text);
{if(clocks_are_stopped)
{//Start the refresh clock running.
user_interface_refresh_clock.Enabled = true;
//Start the animation clock running.
ball_update_clock.Enabled = true;
//Change the message on the button
Go.Text = "Pause";
}
else
{//Stop the refresh clock.
user_interface_refresh_clock.Enabled = false;
//Stop the animation clock running.
ball_update_clock.Enabled = false;
//Change the message on the button
Go.Text = "Go";
}
//Toggle the variable clocks_are_stopped to be its negative
clocks_are_stopped = !clocks_are_stopped;
}//End of event handler Go_stop
}
protected override void OnPaint(PaintEventArgs a){
Graphics displaystuff = a.Graphics;
//displaystuff.DrawLine(otherpen,0,top_panel_height,Width,top_panel_height);
displaystuff.FillRectangle(Brushes.Yellow,0,max_height-80,Width,80);
displaystuff.DrawLine(otherpen,0, max_height-180,max_width-10,max_height-180);
//The next statement draws a line segment with end points starting_point and upper_left.
displaystuff.DrawLine(pens,starting_point,upper_left);
//The next statement draws a line segment with end points upper_left and lower_left.
displaystuff.DrawLine(pens,upper_left,lower_left);
//The next statement draws a line segment with end points lower_left and ending_point.
displaystuff.DrawLine(pens,lower_left,end_point);
//Display the title in larger than normal font.
//The next statement outputs the ball using the ball's current coordinates.
displaystuff.FillEllipse (Brushes.Blue,
(int)System.Math.Round(x),
(int)System.Math.Round(y),
(int)System.Math.Round(2.0*radius),
(int)System.Math.Round(2.0*radius));
base.OnPaint(a);
}
protected void Update_ball_coordinates(System.Object sender, ElapsedEventArgs even)
{//This function is called each time the ball_update_clock makes one tic. That clock is often called the animation clock.
if(System.Math.Abs(y+radius-p0y)<0.5) //Test if the ball is on the top horizontal line segment.
{if(System.Math.Abs(x+radius-(double)p1x)>delta) //Test if there is room to move forward
{//If condition is true then move the ball by amount delta to the left.
x -= delta;
}
else
{//If condition is false make the ball move around the corner and start traveling down.
y = (double)p1y+(delta-(x+radius-(double)p1x));
x = (double)p1x-radius;
}
}//End of if
else if(System.Math.Abs(x+radius-(double)p1x)<0.5) //If this is true then the ball is on the line segment from upper_left to lower_left
{if(System.Math.Abs((double)p2y-(y+radius))>delta)
{//If condition is true then move the ball by amount delta downward.
y = y+delta;
}
else
{//If condition is false then move the ball around the corner and begin traveling right.
x = (double)p2x+(delta-((double)p2y-(y+radius)));
y = (double)p2y-radius;
}//End of most recent else
}
else if(System.Math.Abs(y+radius-(double)p2y)<0.5) //If this is true then the ball is on the lower line segment traveling to the right.
{if(System.Math.Abs((double)p3x-(x+radius))>delta)
{//If the condition is true then move the ball right by the amount delta
x = x + delta;
}
else
{//If the condition is false then distance between the ball and the destination point (p3x,p3y) is less than delta. Make one last move and stop.
x = (double)p3x;
y = (double)p3y-radius;
user_interface_refresh_clock.Enabled = false;
ball_update_clock.Enabled = false;
Go.Text = "Done";
Go.Enabled = false;
System.Console.WriteLine("The program has finished. You may close the window.");
}//End of else part
}//End of nested ifs
}//End of method Update_ball_coordinates
//============================================================
}//end of form
<file_sep>/assignment_3.1/run.sh
echo First remove old binary files
rm *.dll
rm* exe
echo view the list of source files
ls -l
echo compile the Uifile.cs to create the file Uifile.dll
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -out:Uifile.dll Uifile.cs
echo comile the run.sh and link the pervious created dll files to create an executable file
mcs -r:System.Windows.Forms -r:Uifile.dll -out:Application3.exe main.cs
echo View the list of the files in the current folder
ls -l
echo Run the Assignment3 program
./Application3.exe
echo [THE SCRIPT HAS NOW ENDED]
<file_sep>/assignment_0-1/filebuild.sh
echo First remove old binary files
rm *.dll
rm *.exe
echo View the list of source files
ls -l
echo Compile Selectui.cs to create the file: Selectui.dll
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -out:Selectui.dll Selectui.cs
echo Compile Driver.cs and link the previous created dll files to create an executable file.
mcs -r:System -r:System.Windows.Forms -r:Selectui.dll -out:App0.exe main.cs
echo View the list of files in the current folder
ls -l
echo Run the Assignment 1 program.
./App0.exe
echo The script has terminated.
<file_sep>/fibo/build.sh
echo First remove old binary files
rm *.dll
rm *.exe
echo View the list of source files
ls -l
echo Compile Fibonaccilogic.cs to create the file: Fibonaccilogic.dll
mcs -target:library -out:Fibonaccilogic.dll Fibonaccilogic.cs
echo Compile Fibuserinterface.cs to create the file: Fibuserinterface.dll
mcs -target:library -r:System.Drawing.dll -r:System.Windows.Forms.dll -r:Fibonaccilogic.dll -out:Fibuserinterface.dll Fibuserinterface.cs
echo Compile Fibonaccimain.cs and link the two previously created dll files to create an executable file.
mcs -r:System -r:System.Windows.Forms -r:Fibuserinterface.dll -out:Fibo.exe Fibonaccimain.cs
echo View the list of files in the current folder
ls -l
echo Run the Assignment 1 program.
./Fibo.exe
echo The script has terminated.
<file_sep>/assignment_1/driver.sh
echo First remove old binary files
rm *.dll
rm* exe
echo view the list of source files
ls -l
echo compile the algorithm.cs to create the file algorithm.dll
mcs -target:library -r:System.Drawing.dll -out:algorithm.dll algorithm.cs
echo compile UiFile.cs and then link algorithm.cs to UiFile.cs
mcs -target:library -r:algorithm.dll -r:System.Drawing.dll -r:System.Windows.Forms.dll -out:UiFile.dll UiFile.cs
#echo complile uifile.cs to create the file: uifile.dll
#mcs -target:library -r:System.Drawing.dll -r:algorithm.dll -r:System.Windows.Forms.dll -out:UiFile.dll UiFile.cs
echo Compile Driver.sh and link the previous created dll files to create an executable file
mcs -r:System -r:System.Windows.Forms -r:UiFile.dll -out:App1.exe main.cs
echo View the list of the files in the current folder
ls -l
echo Run the Assignment1 program
./App1.exe
echo The script has terminated
<file_sep>/assignment_5/uifile.cs
using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
public class uifile:Form{
private const int form_width = 1270;
private const int form_height = 930;
private const int bottomPanel_Location_height = 800;
private double earthLocation = System.Math.Round(form_height/2.5);
private Button start = new Button();
private Button pause = new Button();
private Button clear = new Button();
private Button exit = new Button();
private Pen pens = new Pen (Color.Black, 2);
private Brush writing_tool = new SolidBrush(System.Drawing.Color.Black);
private Font style_of_message = new System.Drawing.Font("Arial",16,FontStyle.Regular);
private Point pointWidth;
private Point pointHeight;
private Point bottomPanel_Location_point1;
private Point bottomPanel_Location_point2;
private Label apples_caught_label = new Label();
private Label success_ratio_label = new Label();
private Label apples_missed_label = new Label();
private Point apples_caught_text_location;
private Point success_ratio_text_location;
private Point apples_missed_text_location;
private double apples_intial_amount;
private double apples_so_far;
private double apples_caught=0;
private double apples_missed=0;
private double success_ratio =0.0;
private String apples_caught_string = "";
private String apples_missed_string = "";
private String success_ratio_string = "";
private static System.Timers.Timer ball_refresh_clock = new System.Timers.Timer();
private const double ball_refresh_clock_rate = 43.5;
private static System.Timers.Timer monitor_refresh_clock = new System.Timers.Timer();
private const double monitor_refresh_clock_rate = 23.3;
private double ball_linear_speed_pix_per_sec;
private double ball_linear_speed_pix_per_tic;
//private double speed;
private double ball_center_coordinate_x;
private double ball_center_coordinate_y;
//private double ball_direction_x;
private double ball_direction_y;
//private double ball_delta_x;
private double ball_delta_y;
private const double radius = 12.0;
private double ball_bottom_left_x;
private double ball_bottom_left_y;
private const double ball_center_initial_coordinate_x = (double)form_width*.5;
private const double ball_center_initial_coordinate_y = 0.0;
private bool ballvisible = true;
private bool ballcaught = false;
private double cursor_x =0.0;
private double cursor_y = 0.0;
private Random rng = new Random();
public uifile(){
apples_intial_amount = rng.Next(5,10);
System.Console.WriteLine("initial amount of apples: " + apples_intial_amount);
ball_linear_speed_pix_per_sec = 5;
//ball_direction_x = 0;
ball_direction_y = 13;
ball_linear_speed_pix_per_tic = ball_linear_speed_pix_per_sec/ball_refresh_clock_rate;
ball_delta_y = ball_linear_speed_pix_per_tic*ball_direction_y;
ball_center_coordinate_x = ball_center_initial_coordinate_x;
ball_center_coordinate_y = ball_center_initial_coordinate_y;
ball_refresh_clock.Enabled = false; //set to false to stop the clock from running as soon as the uifile function is called
ball_refresh_clock.Elapsed += new ElapsedEventHandler(update_ball_position); //every time the clock happens to tick, it calls Update_ball_position
monitor_refresh_clock.Enabled = false; //set to false to stop the clock from running as soon as the uifile function is called
monitor_refresh_clock.Elapsed += new ElapsedEventHandler(update_display); //every time the clock happens to tick it calls update_monitor
Size = new Size(form_width, form_height);
BackColor = Color.LightPink;
pointWidth = new Point(form_width, 0);
pointHeight = new Point(0, form_height);
bottomPanel_Location_point1 = new Point(0, bottomPanel_Location_height-55);
bottomPanel_Location_point2 = new Point(form_width,bottomPanel_Location_height-55);
int a=0;
int b=0;
start.Location = new Point(a+= 10, b+= bottomPanel_Location_height -10);
start.BackColor = Color.Salmon;
start.Text = "start";
clear.Location = new Point (a, b + start.Height + 10);
clear.BackColor = Color.Salmon;
clear.Text = "clear";
pause.Location = new Point(a += start.Width + 10, b);
pause.BackColor = Color.Salmon;
pause.Text = "pause";
a = form_width - 190;
exit.Location = new Point(a, b + pause.Height +10);
exit.BackColor = Color.Salmon;
exit.Text = "exit";
a = form_width - 190 - exit.Width - 10;
success_ratio_label.Location = new Point(a-= 45, b + pause.Height);
success_ratio_text_location = new Point(a + (apples_caught_label.Width/2), b+ pause.Height+success_ratio_label.Height);
success_ratio_label.Text = "Success ratio";
apples_caught_label.Location = new Point(a, b-=25);
apples_caught_text_location = new Point(a + (apples_caught_label.Width/2), b+apples_caught_label.Height);
apples_caught_label.Text = "Apples caught";
apples_missed_label.Location = new Point(a+= apples_caught_label.Width+ 10, b);
apples_missed_text_location = new Point(a + (apples_missed_label.Width/2), b+ apples_missed_label.Height);
apples_missed_label.Text = "Apples missed";
exit.Click += new EventHandler(quit_click);
start.Click += new EventHandler(start_click);
//add the buttons to the control
Controls.Add(start);
Controls.Add(pause);
Controls.Add(clear);
Controls.Add(exit);
Controls.Add(apples_caught_label);
Controls.Add(success_ratio_label);
Controls.Add(apples_missed_label);
}//end of uifile function
protected void start_click(Object sender, EventArgs e){
start_graphics(monitor_refresh_clock_rate);
start_ball_motion(ball_refresh_clock_rate);
start.Text = "pause";
}
protected void quit_click(Object sender, EventArgs e){
System.Console.WriteLine("now exiting program.....");
Close();
}
protected override void OnPaint(PaintEventArgs ee){
Graphics g = ee.Graphics;
ball_bottom_left_x = ball_center_coordinate_x - radius;
ball_bottom_left_y = ball_center_coordinate_y - radius;
g.DrawLine(pens, bottomPanel_Location_point1, bottomPanel_Location_point2);
apples_missed_string = apples_missed.ToString();
g.DrawString(apples_missed_string, style_of_message, writing_tool, apples_missed_text_location);
apples_caught_string = apples_caught.ToString();
g.DrawString(apples_caught_string,style_of_message,writing_tool,apples_caught_text_location);
success_ratio = apples_caught/apples_so_far;
System.Math.Round(success_ratio, 2);
success_ratio= success_ratio *100;
System.Math.Round(success_ratio, 2);
success_ratio_string = success_ratio.ToString();
g.DrawString(success_ratio_string, style_of_message, writing_tool, success_ratio_text_location);
if(ballvisible){
g.FillEllipse(Brushes.Red, (int)ball_bottom_left_x, (int)ball_bottom_left_y, (float)(2.0*radius), (float)(2.0*radius));
}//end of if statement
base.OnPaint(ee);
}//end of OnPaint
protected override void OnMouseDown(MouseEventArgs me){
cursor_y = me.Y;
cursor_x = me.X;
if(cursor_x < ball_center_coordinate_x + radius && cursor_y < ball_center_coordinate_y + radius){
ballvisible = false;
ballcaught = true;
apples_caught += 1;
apples_so_far += 1;
Invalidate();
}//end of if statement
}//end of OnMouseDown
protected void start_graphics(double monitor_rate){
double actual_refresh_rate = 1.0;
double elapsed_time_between_tics;
if(monitor_rate > actual_refresh_rate){
actual_refresh_rate = monitor_rate;
}
elapsed_time_between_tics = 1000.0/actual_refresh_rate;
monitor_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_tics);
monitor_refresh_clock.Enabled = true;
}//end of start_graphics
protected void start_ball_motion(double update_rate){
double elapsed_time_between_ball_moves;
if(update_rate < 1.0) {update_rate = 1.0;}
elapsed_time_between_ball_moves = 1000.0/update_rate;
ball_refresh_clock.Interval = (int)System.Math.Round(elapsed_time_between_ball_moves);
ball_refresh_clock.Enabled = true;
}//end of start_ball_motion
protected void update_display(System.Object sender, ElapsedEventArgs evt){ //this is called after update ball position
Invalidate();
if(!ball_refresh_clock.Enabled){
monitor_refresh_clock.Enabled = false;
System.Console.WriteLine("The graphical interface is no longer refreshing. You may now exit the program");
start.Text = "Start";
}//end of if statment
}//end of Update_display
protected void update_ball_position(System.Object sender, ElapsedEventArgs evt){ //this is called first
ball_center_coordinate_y += ball_delta_y; //this makes the balls move down the screen
if((int)System.Math.Round(ball_center_coordinate_y + radius) >= bottomPanel_Location_height){ //this statement is supposed to see when the ball reaches the bottomPanel_Location_height and when the ball reaches it, add it to apples_missed
//these statements may not be valid because we have to also make another condition that says if the ball has been clicked on before this condition is reached, it should not be considered as apples_missed
ballvisible = false;
ballcaught = false;
apples_missed += 1;
apples_so_far += 1;
Invalidate();
}
/*test case scenarios for now, delete later when we have multiple balls based off of the rng*/
if(apples_caught == 1){
monitor_refresh_clock.Enabled = false;
ball_refresh_clock.Enabled = false;
System.Console.WriteLine("the clock has stopped. you may exit the program now");
}
if(apples_missed == 1){
monitor_refresh_clock.Enabled = false;
ball_refresh_clock.Enabled = false;
System.Console.WriteLine("the clock has stopped. you may exit the program now");
}
//end of temp test case secnarios
}//end of update_ball_position
}//end of form class
| bd633c0747ecd43a6ca43221851aa7ccf5e94caf | [
"Markdown",
"C#",
"Shell"
] | 28 | Markdown | minavadamee20/C-programs | 468d072a5a163df1f4954bc1a9d0b9167d48ca74 | 8c04629b9382ba6979e3630010e9112d0ee7f663 |
refs/heads/master | <file_sep>module.exports = function(grunt){
pkg: grunt.file.readJSON('package.json'),
grunt.initConfig({
less: {
development: {
options: {
compress: true,
optimization: 2,
paths: ["assets/less"]
},
files: {
"assets/stylesheets/main.css": "assets/less/stv-bingo.less" // destination file and source file
}
}
},
csscomb: {
dist: {
options: {
config: '.csscomb.json'
},
files: {
'public/stylesheets/main.css': ['assets/stylesheets/main.css'],
}
}
},
clean: {
build: ["assets/javascripts/concat.js"]
},
concat: {
js: {
src: 'assets/javascripts/*.js',
dest: 'assets/javascripts/concat.js'
}
},
uglify: {
my_target: {
files: {
'public/javascripts/main.min.js': ['assets/javascripts/concat.js']
},
options: {
mangle: true,
compress: true
}
}
},
// Watches styles and specs for changes
watch: {
css: {
files: ['assets/less/**/*.less', 'assets/javascripts/**/*.js'],
tasks: ['less','clean','concat', 'uglify'],
options: { nospawn: true }
}
}
});
[
'grunt-contrib-watch',
'grunt-contrib-less',
'grunt-csscomb',
'grunt-contrib-concat',
'grunt-contrib-uglify',
'grunt-contrib-clean'
].forEach(function (task) {
grunt.loadNpmTasks(task);
});
grunt.registerTask('default', ['less','csscomb','clean','concat','uglify','watch']);
};<file_sep>$(function() {
var gameTableSource = $("#gamesTableTemplate").html(),
gameTableTemplate = Handlebars.compile(gameTableSource),
gameTableHtml = gameTableTemplate(gameTableData);
$('#gamesTable').html(gameTableHtml);
});
var gameTableData = [
{
icon: "icon-upcoming-games-1",
name: "Network IPP",
players: "33",
price: "0.10",
time: "00:10",
prize: "10.00",
link: "#NetworkIPP"
},
{
icon: "icon-upcoming-games-2",
name: "Network BOGOFF",
players: "7",
price: "0.50",
time: "00:54",
prize: "50",
link: "#NetworkBOGOFF"
},
{
icon: "icon-upcoming-games-3",
name: "Classic 75 Ball",
players: "11",
price: "0.12",
time: "01:32",
prize: "120.00",
link: "#Classic75Ball"
},
{
icon: "icon-upcoming-games-1",
name: "Daily Prebuy Room",
players: "12",
price: "1.00",
time: "05:04",
prize: "100.00",
link: "#DailyPrebuyRoom"
}
];
$(function() {
var gameSource = $("#gamesTemplate").html(),
gameTemplate = Handlebars.compile(gameSource),
gameHtml = gameTemplate(gameData);
$('#games').html(gameHtml);
});
var gameData = [
{
name: "<NAME>",
image: "../public/images/siberian-storm.png",
demo: "#siberianStormDemo",
playNow: "#siberianStormPlay",
info: "information"
},
{
name: "Cleopatra",
image: "../public/images/Cleopatra.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/Kitty-Glitter.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "Monopoly",
image: "../public/images/Monopoly.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME> the Forest",
image: "../public/images/Pixies-of-the-Forest.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/Da-Vinci's-Diamonds.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "Wild Wolf",
image: "../public/images/Wild-Wolf.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "1000 Pandas",
image: "../public/images/1000-Pandas.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
}
];
$(function() {
var winSource = $("#latestWinnersTemplate").html(),
winTemplate = Handlebars.compile(winSource),
winHtml = winTemplate(latestWinnersData);
$('#latestWinners').html(winHtml);
});
var latestWinnersData = [
{
name: "<NAME>",
location: "Edinburgh",
amount: 9
},
{
name: "<NAME>",
location: "Inverness",
amount: 11
},
{
name: "<NAME>",
location: "Glasgow",
amount: 10
},
{
name: "<NAME>",
location: "Aberdeen",
amount: 13
}
];
$(function() {
var navSource = $("#navigationTemplate").html(),
navTemplate = Handlebars.compile(navSource),
navHtml = navTemplate(navigationData);
$('#navigation').html(navHtml);
});
var navigationData = [
{
name: "Home",
link: "#"
},
{
name: "Bingo",
link: "#"
},
{
name: "Games",
link: "#"
},
{
name: "Promotions",
link: "#"
},
{
name: "Jackpots",
link: "#"
},
{
name: "Support",
link: "#"
},
{
name: "Registration",
link: "#"
}
];
$(function() {
var tabSource = $("#tabsTemplate").html(),
tabTemplate = Handlebars.compile(tabSource),
tabHtml = tabTemplate(tabData);
$('#tabs').html(tabHtml);
});
var tabData = [
{
name: "Featured",
link: "#featured",
icon: "icon-star",
active: true
},
{
name: "Slots",
link: "#slots",
icon: "icon-horseshoe",
active: false
},
{
name: "Instant wins",
link: "#instantWins",
icon: "icon-crown",
active: false
}
]<file_sep>$(function() {
var gameTableSource = $("#gamesTableTemplate").html(),
gameTableTemplate = Handlebars.compile(gameTableSource),
gameTableHtml = gameTableTemplate(gameTableData);
$('#gamesTable').html(gameTableHtml);
});
var gameTableData = [
{
icon: "icon-upcoming-games-1",
name: "Network IPP",
players: "33",
price: "0.10",
time: "00:10",
prize: "10.00",
link: "#NetworkIPP"
},
{
icon: "icon-upcoming-games-2",
name: "Network BOGOFF",
players: "7",
price: "0.50",
time: "00:54",
prize: "50",
link: "#NetworkBOGOFF"
},
{
icon: "icon-upcoming-games-3",
name: "Classic 75 Ball",
players: "11",
price: "0.12",
time: "01:32",
prize: "120.00",
link: "#Classic75Ball"
},
{
icon: "icon-upcoming-games-1",
name: "Daily Prebuy Room",
players: "12",
price: "1.00",
time: "05:04",
prize: "100.00",
link: "#DailyPrebuyRoom"
}
];<file_sep>$(function() {
var gameSource = $("#gamesTemplate").html(),
gameTemplate = Handlebars.compile(gameSource),
gameHtml = gameTemplate(gameData);
$('#games').html(gameHtml);
});
var gameData = [
{
name: "<NAME>",
image: "../public/images/siberian-storm.png",
demo: "#siberianStormDemo",
playNow: "#siberianStormPlay",
info: "information"
},
{
name: "Cleopatra",
image: "../public/images/Cleopatra.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/Kitty-Glitter.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "Monopoly",
image: "../public/images/Monopoly.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/Pixies-of-the-Forest.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/Da-Vinci's-Diamonds.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/Wild-Wolf.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
},
{
name: "<NAME>",
image: "../public/images/1000-Pandas.png",
demo: "testlink1",
playNow: "testlink2",
info: "information"
}
];<file_sep>#Bede Gameing Front end Developer test
## STV Bingo
### Getting started
After cloning repo run node package manager to install all dependencies.
npm install
Then run the grunt tasks to compile less to comb css and compress and concatenate javascripts.
grunt
Starting live-server (Localhost:8080)
npm install live-server && live-server
<file_sep>$(function() {
var tabSource = $("#tabsTemplate").html(),
tabTemplate = Handlebars.compile(tabSource),
tabHtml = tabTemplate(tabData);
$('#tabs').html(tabHtml);
});
var tabData = [
{
name: "Featured",
link: "#featured",
icon: "icon-star",
active: true
},
{
name: "Slots",
link: "#slots",
icon: "icon-horseshoe",
active: false
},
{
name: "Instant wins",
link: "#instantWins",
icon: "icon-crown",
active: false
}
] | b6d720b21420b47192f914c3865908d4488e7a30 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | csdcouk/bedegaming_frontend_test | 09d40b4df331f0048735e8f2077b4de5bbe7a42c | 2f4067c6d71b9e164dd9dd61bb88975fb19ef9c7 |
refs/heads/master | <file_sep>public class Professor extends Pessoa{
private String especialidade;
public Professor(String nome,String cpf,String rg, String e){
super(nome,cpf,rg);
especialidade = e;
}
public void setEspecialidade(String n)
{
especialidade = n;
}
public String getEspecialidade()
{
return especialidade;
}
public void apresentarDados()
{
super.apresentarDados();
System.out.printf(" Especialidade: %s\n", especialidade);
}
public String toString()
{
return super.toString()+"Especialização: "+especialidade+"\n";
}
public boolean equals(Object o)
{
if(o instanceof Professor){
if(super.equals(o) && especialidade.equals(((Professor) o). getEspecialidade()))
return true;
}
return false;
}
public void executarTarefa()
{
System.out.printf("Professor esta Ensinando");
}
}
<file_sep>import javax.swing.JDialog;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.Frame;
import java.util.List;
import javax.swing.JLabel;
public class DialogoProfessor extends JDialog{
private JTextField txtNome,txtCPF,txtRG,txtEspecialidade;
private JLabel lblNome,lblCPF,lblRG,lblEspecialidade;
private JButton btOK,btCancelar;
private boolean ok;
public Professor getProfessor(){
if(ok){
Professor p = new Professor(txtNome.getText(),txtCPF.getText(),txtRG.getText(),txtEspecialidade.getText());
return p;
}
else
return null;
}
public DialogoProfessor(Frame frame){
super(frame,true);
setLayout(new GridLayout (5,2));
txtNome = new JTextField();
txtCPF= new JTextField();
txtRG= new JTextField();
txtEspecialidade= new JTextField();
btOK = new JButton("OK");
btOK.addActionListener((e)->{
ok = true;
dispose();
});
btCancelar = new JButton("Cancelar");
btCancelar.addActionListener((e)->{
dispose();
});
lblNome = new JLabel("Nome: ");
lblCPF = new JLabel("CPF: ");
lblRG = new JLabel("RG: ");
lblEspecialidade = new JLabel("Especialidade: ");
add(lblNome);
add(txtNome);
add(lblCPF);
add(txtCPF);
add(lblRG);
add(txtRG);
add(lblEspecialidade);
add(txtEspecialidade);
add(btCancelar);
add(btOK);
setSize(300,300);
setVisible(true);
}
}
<file_sep>import javax.swing.JDialog;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.util.List;
public class JanelaEditProfessor extends JDialog{
private JTextField txtNome, txtEspecialidade, txtCPF, txtRG;
private JLabel lblNome,lblCPF,lblRG,lblEspecialidade;
private JButton btOK, btCancelar;
private boolean ok;
public void setAluno(String nome, String cpf, String rg, String especialidade){
Professor p = new Professor(nome, cpf, rg, especialidade);
}
public JanelaEditProfessor(Frame frame, Professor p){
super(frame,true);
setLayout(new GridLayout(6,2));
lblNome = new JLabel("Nome: ");
txtNome = new JTextField();
txtNome.setText(p.getNome());
lblEspecialidade = new JLabel("Especialidade: ");
txtEspecialidade = new JTextField();
txtEspecialidade.setText(p.getEspecialidade());
lblCPF = new JLabel("CPF: ");
txtCPF = new JTextField();
txtCPF.setText(p.getCpf());
lblRG = new JLabel("RG: ");
txtRG = new JTextField();
txtRG.setText(p.getRg());
btOK = new JButton("OK");
btCancelar = new JButton("Cancelar");
btCancelar.addActionListener((e)->{
dispose();
});
btOK.addActionListener((e)->{
p.setNome(txtNome.getText());
p.setEspecialidade(txtEspecialidade.getText());
p.setRg(txtRG.getText());
p.setCpf(txtCPF.getText());
dispose();
});
add(lblNome);
add(txtNome);
add(lblEspecialidade);
add(txtEspecialidade);
add(lblCPF);
add(txtCPF);
add(lblRG);
add(txtRG);
add(btCancelar);
add(btOK);
setSize(300,300);
setVisible(true);
}
}
<file_sep>import java.util.List;
import java.util.LinkedList;
public class Dados{
private static Dados instance;
public static Dados getInstance(){
if(instance==null){
instance = new Dados();
}
return instance;
}
private List<Aluno> lstAlunos;
private List<Professor> lstProfessor;
private List<Turma> lstTurma;
private Dados(){
lstAlunos = new LinkedList<>();
lstProfessor = new LinkedList<>();
lstTurma = new LinkedList<>();
}
public List<Aluno> getListAlunos(){
return lstAlunos;
}
public List<Professor> getListProfessor(){
return lstProfessor;
}
public List<Turma> getListTurma(){
return lstTurma;
}
public void removeAluno(Aluno a){
lstAlunos.remove(a);
}
public void removeProfessor(Professor p){
lstProfessor.remove(p);
}
public void removeTurma(Turma t){
lstTurma.remove(t);
}
}
<file_sep>import javax.swing.JDialog;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.util.List;
import javax.swing.JList;
import javax.swing.JPanel;
public class DialogoTurma extends JDialog{
private JTextField txtDataInicio, txtDataTermino, txtProfessor, txtAlunosTurma, txtAlunos;
private JLabel lblDataInicio,lblDataTermino,lblProfessor;
private JButton btOK, btCancelar, btAddProfessor, btSelecionarAlunos;
private Professor prof;
private boolean ok;
public Turma getTurma(){
if(ok){
System.out.printf("Nome professor: %s", prof.getNome());
Turma t = new Turma(txtDataInicio.getText(), txtDataTermino.getText(), prof);
return t;
}
else
return null;
}
public DialogoTurma(Frame frame){
super(frame,true);
setLayout(new GridLayout(4,2));
lblDataInicio = new JLabel("DataInicio: ");
txtDataInicio = new JTextField();
lblDataTermino = new JLabel("Data Termino: ");
txtDataTermino = new JTextField();
//lblProfessor = new JLabel("Professor: ");
btAddProfessor = new JButton("Selecionar Professor:");
txtProfessor = new JTextField();
btOK = new JButton("OK");
btCancelar = new JButton("Cancelar");
//btSelecionarAlunos = new JButton("Selecionar Alunos");
btAddProfessor.addActionListener((e)->{
JanelaListarProfessor d = new JanelaListarProfessor(frame);
prof = d.getProfessor();
txtProfessor.setText(prof.getNome());
});
btCancelar.addActionListener((e)->{
dispose();
});
btOK.addActionListener((e)->{
ok = true;
dispose();
});
add(lblDataInicio);
add(txtDataInicio);
add(lblDataTermino);
add(txtDataTermino);
//add(lblProfessor);
add(btAddProfessor);
add(txtProfessor);
txtProfessor.setEditable(false);
add(btCancelar);
add(btOK);
//add(btSelecionarAlunos);
setSize(350,300);
setVisible(true);
}
}
| 5c65fb721fbf504127135997bd597b21e1d265c2 | [
"Java"
] | 5 | Java | JessicaVicentini99/GerenciadorDeTurmasJava | 9331fa33135a544fdcf80660b59ca72c63f11bd7 | d36d526e1bc80a40aeec5b1bb2bdfad031e83778 |
refs/heads/master | <repo_name>qpleple/wordpress-theme-blank<file_sep>/README.md
This is the simplest blank them you can have. It contains 4 templates :
- `index.php`
- `header.php`
- `footer.php`
- `sidebar.php`
And 2 CSS files :
- `base.css` : that resets all default styling of CSS elements
- `style.css` : for your theme<file_sep>/sidebar.php
<div id="sidebar">
<ul>
<li <?php if (is_home()) { ?>class="current_page_item"<?php } ?>><a href="<?php bloginfo('url'); ?>">
<a href="<?php bloginfo('url'); ?>">Home</a>
</li>
<?php wp_list_pages('title_li=' ); ?>
</ul>
</div>
| 9949cc6c48cebb9bb7e3af4b1faa6aa58a17c9e4 | [
"Markdown",
"PHP"
] | 2 | Markdown | qpleple/wordpress-theme-blank | 5386887db241f2030221383b439114464fef3074 | c90714854e1398a1e33d35af4f8ea130ab6e57e8 |
refs/heads/master | <repo_name>wordpressecommerce/woocommerce-add-to-cart-metrics<file_sep>/README.md
# WooCommerce Add to Cart Metrics
Track add-to-cart metrics in a custom DB table when WooCommerce is active.
## Description
Track add-to-cart made on a store, by storing that metrics data in a custom DB table of the site.
## Installation
### Automated Installation
With WordPress 2.7 or above, you can simply go to Plugins > Add New in the WordPress Admin. Next, search for "WooCommerce Add to Cart Metrics" and click Install Now.
### Manual Installation
1. Upload the plugin file woocommerce-add-to-cart-metrics.zip to the ‘/wp-content/plugins/’ directory, or install the plugin through the WordPress plugins screen directly.
2. Activate the plugin through the ‘Plugins’ screen in WordPress.
## Changelog
**1.0.0**
* Initial release.
<file_sep>/uninstall.php
<?php
if( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) exit();
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS wc_metric_log" );
delete_option("lw_wc_metric_log");
?>
<file_sep>/woocommerce-add-to-cart-metrics.php
<?php
/**
* Plugin Name: WooCommerce Add to Cart Metrics
* Description: Track add-to-cart metrics in a custom DB table when WooCommerce is active.
* Version: 1.0.0
* Author: Liquid Web
* Author URI: https://www.liquidweb.com
* License: MIT
* License URI: https://opensource.org/licenses/MIT
* Text Domain: woocommerce-add-to-cart-metrics
* Domain Path: /languages
* WC requires at least: 3.0.0
* WC tested up to: 3.2.0
*/
// Event tracking
add_action( 'woocommerce_after_add_to_cart_button', 'log_add_to_cart' );
add_action( 'wp_footer', 'log_loop_add_to_cart' );
function log_add_to_cart() {
$this->log_wc( 'add-to-cart' );
}
function log_loop_add_to_cart() {
$this->log_wc( 'add-to-cart' );
}
register_activation_hook( __FILE__, 'wc_metrics_create_db' );
function wc_metrics_create_db() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'wc_metric_log';
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
date datetime DEFAULT CURRENT_TIMESTAMP,
views smallint(5) NOT NULL,
clicks smallint(5) NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
function get_db_version_option_key() {
return 'lw_wc_metric_log';
}
register_deactivation_hook( __FILE__, 'wc_metrics_remove_database' );
function wc_metrics_remove_database() {
global $wpdb;
$table_name = $wpdb->prefix . 'wc_metric_log';
$sql = "DROP TABLE IF EXISTS $table_name";
$wpdb->query($sql);
delete_option("lw_wc_metric_log");
}
<file_sep>/readme.txt
=== WooCommerce Add to Cart Metrics ===
Contributors: liquidweb, lukefiretoss
Tags: woocommerce, add, to, cart, logging, ecommerce
Requires at least: 4.6
Tested up to: 4.8.2
Requires PHP: 5.3
Stable tag: 1.0.0
License: MIT
License URI: https://opensource.org/licenses/MIT
Track add-to-cart made on a store, by storing that metrics data in a custom DB table of the site.
== Description ==
Track add-to-cart made on a store, by storing that metrics data in a custom DB table of the site.
== Frequently Asked Questions ==
= What does the plugin do? =
The plugin will create a custom DB table and store the add-to-cart metrics recorded in it. On deactivation the custom DB table will be deleted.
== Installation ==
1. Upload the `woocommerce-add-to-cart-metrics` directory into `wp-content/plugins/`
2. Activate the plugin through the "Plugins" menu in WordPress
== Changelog ==
= 1.0.0 =
* Initial public release.
| 4047b315b3db2678e664d97fb0229ff6c5355949 | [
"Markdown",
"Text",
"PHP"
] | 4 | Markdown | wordpressecommerce/woocommerce-add-to-cart-metrics | 850d39d9ff9189876ef26738460bb1a85ebf1bb8 | a913386387263b41d781be4bba77993c169fa356 |
refs/heads/master | <repo_name>charleshaa/rest-sensor<file_sep>/README.md
# rest-sensor
On peut utiliser Python-request:
[Python request](http://docs.python-requests.org/en/latest/)
<file_sep>/direct_client.py
import urllib2
import json
from pymongo import MongoClient
class Rest_Request(object):
"""docstring for Rest_Request"""
def __init__(self,server):
super(Rest_Request, self).__init__()
self.server = server
self.db = 0
def DB_connect(self):
if client:
return True
else:
return False
def Sensors_recense(self):
path = self.server+"/sensors"
req = urllib2.Request(path)
opener = urllib2.build_opener()
f = opener.open(req)
sensors = f.read()
return sensors
def Read_Line(self,text):
line = text.split('\n')
return line
def Request_data(self,id):
path = self.server+"/sensors/"+str(id)+"/all_measures"
req = urllib2.Request(path)
opener = urllib2.build_opener()
f = opener.open(req)
data = json.loads(f.read())
return data
client = Rest_Request("http://192.168.127.12:5001")
#client = Rest_Request("http://172.16.58.3:5000")
sensors = client.Sensors_recense()
line = client.Read_Line(sensors)
#connect = client.DB_connect()
client_db = MongoClient()
db = client_db.smarthepia
for i in range(0,len(line)-1):
num = line[i].split("=")
data = client.Request_data(num[0])
result = db.Sensors_data.insert_one(data)
# Insertion des donnees dans la base de donnees
cursor = db.Sensors_data.find()
for document in cursor:
print(document)
| 9a6296015c158162146b684695fdba3f7ade8af4 | [
"Markdown",
"Python"
] | 2 | Markdown | charleshaa/rest-sensor | 13c9ad7eac31cef626fc6bf25420aa30af5f740c | ee281886f1eb1d4603dc98c0b0e844fc8f17cb2f |
refs/heads/master | <repo_name>wbish/Craigslist-8X<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/AccountManagementVM.cs
using System;
using WB.Craigslist8X.Common;
using Windows.UI;
using Windows.UI.Xaml.Media;
namespace WB.Craigslist8X.ViewModel
{
public class PostingVM : BindableBase
{
public PostingStatus Status
{
get;
set;
}
public Brush StatusColor
{
get
{
switch (Status)
{
case PostingStatus.Active:
return new SolidColorBrush(Colors.LightGreen);
case PostingStatus.Deleted:
return new SolidColorBrush(Colors.Pink);
case PostingStatus.Expired:
return new SolidColorBrush(Color.FromArgb(0xff, 0xcc, 0x99, 0xff));
case PostingStatus.Flagged:
return new SolidColorBrush(Colors.Yellow);
default:
throw new ArgumentOutOfRangeException();
}
}
}
public string Title
{
get;
set;
}
public string Price
{
get;
set;
}
public long PostingId
{
get;
set;
}
public Uri Manage
{
get;
set;
}
public string City
{
get;
set;
}
public string Category
{
get;
set;
}
public DateTime Date
{
get;
set;
}
}
public enum PostingStatus
{
Active, // lightgreen
Deleted, // pink
Expired, // #cc99ff
Flagged, //
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/UserAccounts.cs
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Security;
using Windows.Security.Credentials;
using Windows.Security.Credentials.UI;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.Model
{
public class UserAccounts : BindableBase, IStorageBacked
{
#region Initialization
static UserAccounts()
{
_instanceLock = new object();
}
private UserAccounts()
{
this.Accounts = new ObservableCollection<PasswordCredential>();
this._listLock = new object();
this._vault = new PasswordVault();
this.Accounts.CollectionChanged += Accounts_CollectionChanged;
}
void Accounts_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.OnPropertyChanged("Accounts");
}
#endregion
#region Singleton
public static UserAccounts Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new UserAccounts();
return _instance;
}
}
}
static UserAccounts _instance;
static object _instanceLock;
#endregion
public async static Task<PasswordCredential> PromptForCreds(string message)
{
CredentialPickerOptions options = new CredentialPickerOptions();
options.Message = message;
options.Caption = "Craigslist 8X";
options.TargetName = "craigslist.org";
options.CallerSavesCredential = false;
options.CredentialSaveOption = CredentialSaveOption.Hidden;
options.AuthenticationProtocol = AuthenticationProtocol.Basic;
var result = await CredentialPicker.PickAsync(options);
if (!string.IsNullOrWhiteSpace(result.CredentialUserName) && !string.IsNullOrWhiteSpace(result.CredentialPassword))
return new PasswordCredential(CraigslistResource, result.CredentialUserName, result.CredentialPassword);
else
return null;
}
#region IStorageBacked
public async Task<bool> LoadAsync()
{
try
{
// We used to save usernames and passwords in a very unsafe way. Lets delete the old file.
StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(UserAccountsFileName);
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
catch (Exception)
{
// File no longer exists. Maybe we can get rid of this try/catch block some day
}
if (this._vault == null)
{
await Logger.AssertNotReached("Why is vault null?");
return false;
}
lock (this._listLock)
{
this.Accounts.Clear();
try
{
foreach (var cred in this._vault.FindAllByResource(CraigslistResource))
{
this.Accounts.Add(cred);
}
}
catch (Exception)
{
// Resource not found
}
}
return true;
}
#pragma warning disable 1998
public async Task<bool> SaveAsync()
{
return false;
}
#pragma warning restore 1998
#endregion
#region Methods
public void Add(PasswordCredential cred)
{
// Ensure the right resource is set
cred.Resource = CraigslistResource;
this.Remove(cred);
lock (_listLock)
{
this._accounts.Add(cred);
this._vault.Add(cred);
}
this.OnPropertyChanged("Accounts");
}
public void Remove(PasswordCredential cred)
{
lock (_listLock)
{
for (int i = 0; i < this._accounts.Count; ++i)
{
if (cred.UserName.Equals(this._accounts[i].UserName, StringComparison.CurrentCultureIgnoreCase))
{
this._accounts.RemoveAt(i);
--i;
this._vault.Remove(cred);
}
}
}
this.OnPropertyChanged("Accounts");
}
#endregion
#region Properties
public ObservableCollection<PasswordCredential> Accounts
{
get
{
return _accounts;
}
private set
{
this.SetProperty(ref this._accounts, value);
}
}
#endregion
#region Fields
ObservableCollection<PasswordCredential> _accounts;
object _listLock;
PasswordVault _vault;
#endregion
#region Constants
const string CraigslistResource = "http://www.craigslist.org";
//file = await ApplicationData.Current.RoamingFolder.GetFileAsync(UserAccountsFileName);
const string UserAccountsFileName = "UserAccounts.xml";
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/SavedQuery.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
namespace WB.Craigslist8X.Model
{
public class SavedQuery : BindableBase
{
public SavedQuery(Query query, string name)
{
this.Query = query;
this.Name = name;
this.TileId = Guid.NewGuid();
this.CacheDate = DateTime.MinValue;
this.RssNewDate = DateTime.MinValue;
}
public static string Serialize(SavedQuery query)
{
if (query == null)
return null;
return string.Format(@"<sq name=""{0}"" tile=""{1}"" url=""{3}"" time=""{4}"">{2}</sq>",
Uri.EscapeDataString(query.Name),
query.TileId,
Query.Serialize(query.Query),
Uri.EscapeDataString(query.Query.GetQueryUrl().AbsoluteUri),
query.CacheDate
);
}
public static SavedQuery Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml))
return null;
SavedQuery sq = null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement xe = doc.DocumentElement;
if (xe.NodeName == "sq")
{
sq = new SavedQuery(Query.Deserialize(xe.SelectSingleNode("q").GetXml()), Uri.UnescapeDataString(xe.GetAttribute("name")));
if (!string.IsNullOrEmpty(xe.GetAttribute("tile")))
{
sq.TileId = Guid.Parse(xe.GetAttribute("tile"));
}
if (!string.IsNullOrEmpty(xe.GetAttribute("url")))
{
sq.QueryUrl = new Uri(Uri.UnescapeDataString(xe.GetAttribute("url")));
}
if (!string.IsNullOrEmpty(xe.GetAttribute("time")))
{
sq.CacheDate = DateTime.Parse(xe.GetAttribute("time"));
}
}
return sq;
}
public Guid TileId
{
get;
private set;
}
public string Name
{
get;
private set;
}
public Query Query
{
get;
private set;
}
/// <summary>
/// In order to prevent loading our entire CraigslistApi which we are not able to from our background task binary,
/// we cache our target URL here.
/// </summary>
public Uri QueryUrl
{
get;
set;
}
/// <summary>
/// Cache the timestamp of the latest item we have looked at so that we now how many items are newer.
/// </summary>
public DateTime CacheDate
{
get
{
return this._cacheDate;
}
set
{
this.SetProperty(ref this._cacheDate, value);
}
}
/// <summary>
/// Number of new items since CacheDate
/// </summary>
public int Notifications
{
get
{
return this._notifications;
}
set
{
if (this.SetProperty(ref this._notifications, value))
{
try
{
if (value == 0)
{
BadgeUpdater updater = BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile(this.TileId.ToString());
updater.Clear();
}
else
{
XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", value.ToString());
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdater updater = BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile(this.TileId.ToString());
updater.Update(badge);
}
}
catch
{
// Tile does not exist
}
}
}
}
public DateTime RssNewDate
{
get;
set;
}
private int _notifications;
private DateTime _cacheDate;
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Controls/PostMapControl.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace WB.Craigslist8X.View
{
public sealed partial class PostMapControl : UserControl
{
public PostMapControl()
{
this.InitializeComponent();
}
public string GetPostData()
{
if (this.ShowMap.IsOn)
{
return string.Format("&wantamap=on&{0}={1}&{2}={3}&{4}={5}&{6}={7}&{8}={9}",
Uri.EscapeDataString(StreetField.Tag.ToString()),
Uri.EscapeDataString(StreetField.Text),
Uri.EscapeDataString(CrossStreetField.Tag.ToString()),
Uri.EscapeDataString(CrossStreetField.Text),
Uri.EscapeDataString(CityField.Tag.ToString()),
Uri.EscapeDataString(CityField.Text),
Uri.EscapeDataString(RegionField.Tag.ToString()),
Uri.EscapeDataString(RegionField.Text),
Uri.EscapeDataString(PostalField.Tag.ToString()),
Uri.EscapeDataString(PostalField.Text)
);
}
else
{
return string.Empty;
}
}
private void ShowMap_Toggled(object sender, RoutedEventArgs e)
{
if (this.ShowMap.IsOn)
this.MapGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
else
this.MapGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/Craigslist.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using WB.SDK.Logging;
using HtmlAgilityPack;
namespace WB.CraigslistApi
{
public class Craigslist : IDisposable
{
#region Constructor
static Craigslist()
{
_instanceLock = new object();
}
private Craigslist()
{
StorageFile file = ApplicationData.Current.TemporaryFolder.CreateFileAsync("CraigslistApi.log", CreationCollisionOption.OpenIfExists).AsTask().GetAwaiter().GetResult();
}
#endregion
#region IDisposable
bool _disposed;
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
}
_disposed = true;
}
}
#endregion
#region Singleton
public static Craigslist Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new Craigslist();
return _instance;
}
}
}
static Craigslist _instance;
static object _instanceLock;
#endregion
public async Task<CraigCityList> GetCities()
{
return await Task<CraigCityList>.Run(() => Geography.ScrapeLocations());
}
public async Task<CraigCityList> FindNearbyCities(CraigCityList cities, CraigCity city)
{
if (cities == null)
{
throw new CraigCityListNotCachedException();
}
CraigCityList list = await Task<CraigCityList>.Run(() => Geography.FindNearbyCities(cities, city));
return list;
}
public async Task<CraigCity> ResolveCity(CraigCityList cities)
{
if (cities == null)
{
throw new CraigCityListNotCachedException();
}
Uri location = await Task<Uri>.Run(() => Geography.ResolveLocation());
// Sometimes geo.craigslist.org is not able to resolve the location.
if (location == null)
return null;
CraigCity city = cities.GetCityByUri(location);
await Logger.AssertNotNull(city, "failed to find city by url");
return city;
}
public async Task<CategoryList> GetCategories()
{
return await Task<CategoryList>.Run(() => Categories.ScrapeCategories());
}
public async Task<Uri> GetPostUri(CraigCity city)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(city.Location))
{
if (response.IsSuccessStatusCode)
{
HtmlDocument html = new HtmlDocument();
html.LoadHtml(await response.Content.ReadAsStringAsync());
HtmlNode postLink = (from ul in html.DocumentNode.Descendants("ul").Where(x => x.Attributes["id"] != null && x.Attributes["id"].Value == "postlks")
from link in ul.Descendants("a").Where(x => x.Attributes["id"] != null && x.Attributes["id"].Value == "post")
select link).FirstOrDefault();
if (postLink != null)
{
return new Uri(postLink.Attributes["href"].Value);
}
}
else
{
Logger.LogMessage("CraigslistApi", "Unsuccessful status code '{0}' returned when sending request to Craigslist.", response.StatusCode);
}
return null;
}
}
public async Task<bool> Login(HttpClientHandler handler, HttpClient client, string user, string password)
{
const string LoginUrl = "https://accounts.craigslist.org/login";
try
{
using (HttpContent content = new StringContent(string.Format("inputEmailHandle={0}&inputPassword={1}", Uri.EscapeDataString(user), password)))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.DefaultRequestHeaders.ExpectContinue = false;
using (HttpResponseMessage response = await client.PostAsync(LoginUrl, content))
{
if (response.IsSuccessStatusCode)
{
CookieCollection cookies = handler.CookieContainer.GetCookies(response.RequestMessage.RequestUri);
foreach (Cookie c in cookies)
{
if (c.Name == "cl_session" && !string.IsNullOrEmpty(c.Value))
{
return true;
}
}
}
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
return false;
}
public async Task<bool> FlagPost(Post post, FlagCode code)
{
const string FlagUrl = "http://{0}/flag/?flagCode={1}&postingID={2}";
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(string.Format(FlagUrl, post.Url.Host, post.ID, code)))
{
if (response.IsSuccessStatusCode)
{
return true;
}
return false;
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
return false;
}
public async Task<bool> ValidateCreds(string user, string password)
{
try
{
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.UseCookies = true;
handler.CookieContainer = new CookieContainer();
using (HttpClient client = new HttpClient(handler, disposeHandler: true))
{
return await Login(handler, client, user, password);
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
return false;
}
#region Constants
internal const string GeoUrl = "http://geo.craigslist.org/";
internal const string SitesUrl = "http://www.craigslist.org/about/sites/";
internal const string CategoryUrl = "http://seattle.craigslist.org/";
internal const string SubAreasUrl = "http://www.craigslist.org/about/bulk_posting_interface";
#endregion
}
public class CraigCityListNotCachedException : Exception
{
public CraigCityListNotCachedException()
: base("Must call CacheCities() before calling this method")
{
}
}
public enum FlagCode : byte
{
Miscategorized = 16,
Prohibited = 28,
Spam = 15,
BestOf = 9,
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Interfaces/IPostList.cs
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.Craigslist8X.ViewModel;
namespace WB.Craigslist8X.View
{
interface IPostList
{
void SetSelection(PostVM post);
ObservableCollection<PostBase> PostItems
{
get;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/UpgradePanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Store;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class UpgradePanel : UserControl, IPanel
{
public UpgradePanel()
{
this.InitializeComponent();
}
#region IPanel
public async Task AttachContext(object context, IPanel parent)
{
await Logger.Assert(!App.IsPro, "PRO package has already been purchased!");
}
#endregion
private async void UpgradePro_Tapped(object sender, TappedRoutedEventArgs e)
{
if (App.IsPro)
{
await new MessageDialog("You have already purchased the PRO package.", "Craigslist 8X").ShowAsync();
return;
}
bool success = false;
try
{
#if DEBUG
await CurrentAppSimulator.RequestProductPurchaseAsync(App.Craigslist8XPRO, false);
#else
await CurrentApp.RequestProductPurchaseAsync(App.Craigslist8XPRO, false);
#endif
success = true;
}
catch (Exception ex)
{
Logger.LogException(ex);
}
if (!success)
{
await new MessageDialog("There was a problem trying to complete your purchase. Please try again.", "Craigslist 8X").ShowAsync();
return;
}
if (!App.IsPro)
{
await new MessageDialog("The Craigslist 8X PRO package purchase was not completed.", "Craigslist 8X").ShowAsync();
return;
}
else
{
MainPage.Instance.MainMenu.SetPurchasedPro();
await new MessageDialog("Thank you for supporting Craigslist 8X!", "Craigslist 8X").ShowAsync();
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/BackgroundTaskManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
namespace WB.Craigslist8X.Model
{
static class BackgroundTaskManager
{
public static async Task RegisterAccess()
{
Unregister();
try
{
var result = await BackgroundExecutionManager.RequestAccessAsync();
switch (result)
{
case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
RegisterLockScreenTask();
break;
case BackgroundAccessStatus.Denied:
case BackgroundAccessStatus.Unspecified:
default:
RegisterMaintenanceTask();
break;
}
}
catch
{
// If the user has already accepted lock screen access, an exception will be thrown. This is a bug in
// the API.
RegisterLockScreenTask();
}
}
static void Unregister()
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == MaintenanceTaskName || task.Value.Name == LockScreenTaskName)
task.Value.Unregister(true);
}
}
static void RegisterMaintenanceTask()
{
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = MaintenanceTaskName;
builder.TaskEntryPoint = TaskEntryPoint;
builder.SetTrigger(new MaintenanceTrigger(freshnessTime: 15, oneShot: false));
var condition = new SystemCondition(SystemConditionType.InternetAvailable);
builder.AddCondition(condition);
var x = builder.Register();
}
static void RegisterLockScreenTask()
{
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = LockScreenTaskName;
builder.TaskEntryPoint = TaskEntryPoint;
builder.SetTrigger(new TimeTrigger(freshnessTime: 15, oneShot: false));
var condition = new SystemCondition(SystemConditionType.InternetAvailable);
builder.AddCondition(condition);
var x = builder.Register();
}
const string LockScreenTaskName = "Lock Screen Search Agent Task";
const string MaintenanceTaskName = "Maintenance Search Agent Task";
const string TaskEntryPoint = "Craigslist8XTasks.SearchAgentTask";
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/ChooseCitiesPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Callisto.Controls;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
/// <summary>
/// A basic page that provides characteristics common to most applications.
/// </summary>
public sealed partial class ChooseCategoryPage : LayoutAwarePage
{
public ChooseCategoryPage()
{
this.InitializeComponent();
this._vm = new ChooseCitiesVM();
this.DataContext = this._vm;
this.SetContinentSelections();
}
private async void BackButton_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame frame = await App.EnsureNavigationFrame();
frame.Content = MainPage.Instance;
SettingsUI.ShowSearchSettings();
}
private void TitleButton_Tapped(object sender, TappedRoutedEventArgs e)
{
ContinentPicker cp = new ContinentPicker();
Flyout flyout = new Flyout();
flyout.Content = cp;
flyout.Placement = PlacementMode.Bottom;
flyout.PlacementTarget = this.titleButton;
flyout.IsOpen = true;
flyout.Closed += (a, b) =>
{
if (!string.IsNullOrEmpty(cp.Continent) && this._vm.Continent != cp.Continent)
{
this._blockRemove = true;
this.CitiesGrid.ScrollIntoView(this._vm.States.First().Cities.First());
this._vm.Continent = cp.Continent;
this.SetContinentSelections();
this._blockRemove = false;
}
};
}
private void CitiesGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems != null)
{
foreach (var c in e.AddedItems)
CityManager.Instance.AddSearchCity(c as CraigCity);
}
if (e.RemovedItems != null && !this._blockRemove)
{
foreach (var c in e.RemovedItems)
CityManager.Instance.RemoveSearchCity(c as CraigCity);
}
}
private void SetContinentSelections()
{
foreach (var c in CityManager.Instance.SearchCities.Where(x => x.Continent == this._vm.Continent))
{
this.CitiesGrid.SelectedItems.Add(c);
}
}
ChooseCitiesVM _vm;
bool _blockRemove;
}
}
<file_sep>/Win8/WB/WB.SDK/Logging/Logger.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls.Primitives;
namespace WB.SDK.Logging
{
public static class Logger
{
static Logger()
{
#if DEBUG
LogSessionStart();
_ignoredAsserts = new List<string>();
#endif
}
#if !DEBUG
#pragma warning disable 1998
#endif
public static async Task Assert(bool condition, string message, [CallerMemberName] string member = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
{
#if DEBUG
await AssertCore(condition, "Assert", message, member, filePath, lineNumber);
#endif
}
public static async Task AssertNotReached(string message, [CallerMemberName] string member = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
{
#if DEBUG
await AssertCore(false, "AssertNotReached", message, member, filePath, lineNumber);
#endif
}
public static async Task AssertNotNull(object obj, string message, [CallerMemberName] string member = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
{
#if DEBUG
await AssertCore(obj != null, "AssertNotNull", message, member, filePath, lineNumber);
#endif
}
public static async Task AssertNull(object obj, string message, [CallerMemberName] string member = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
{
#if DEBUG
await AssertCore(obj == null, "AssertNull", message, member, filePath, lineNumber);
#endif
}
public static async Task AssertValue<T>(T actual, T expected, string message, [CallerMemberName] string member = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0)
where T : IEquatable<T>
{
#if DEBUG
await AssertCore(actual.Equals(expected), "AssertValue", string.Format("Actual: {0}, Expected: {1}. {2}", actual, expected, message), member, filePath, lineNumber);
#endif
}
private static async Task AssertCore(bool condition, string category, string message, string member, string filePath, int lineNumber)
{
#if DEBUG
if (!condition)
{
if (!_ignoreAllAsserts)
{
string assert = string.Format("{0}{1}{2}{3}{4}", category, message, member, filePath, lineNumber);
if (!_ignoredAsserts.Contains(assert))
{
MessageDialog assertDialog = new MessageDialog(string.Format(AssertMessage, filePath, member, lineNumber, message), string.Format("{0} Failed", category));
assertDialog.Commands.Add(new UICommand() { Id = 0, Label = "Ignore" });
assertDialog.Commands.Add(new UICommand() { Id = 1, Label = "Always Ignore" });
//assertDialog.Commands.Add(new UICommand() { Id = 2, Label = "Ignore All Asserts" });
assertDialog.Commands.Add(new UICommand() { Id = 3, Label = "Debug" });
UICommand ret = await assertDialog.ShowAsync() as UICommand;
if ((int)ret.Id == 1)
{
_ignoredAsserts.Add(assert);
}
else if ((int)ret.Id == 2)
{
_ignoreAllAsserts = true;
}
else if ((int)ret.Id == 3)
{
if (Debugger.IsAttached)
Debugger.Break();
else
Debugger.Launch();
}
}
}
LogMessage(category, message);
}
#endif
}
#if !DEBUG
#pragma warning restore 1998
#endif
public static void LogMessage(string category, string format, params object[] args)
{
#if DEBUG
LogMessage(category, string.Format(format, args));
#endif
}
public static void LogMessage(string category, string message)
{
#if DEBUG
LogRecord(string.Format("{0}: {1}", category, message));
#endif
}
public static void LogException(Exception ex)
{
#if DEBUG
LogRecord(string.Format("{0}\nStackTrace:{1}", ex.Message, ex.StackTrace));
#endif
}
private static void LogSessionStart()
{
#if DEBUG
WriteLine(new string('=', 100));
WriteLine(string.Format("Started new session - {0}", DateTime.Now));
WriteLine(new string('=', 100));
WriteLine(string.Empty);
#endif
}
private static void LogRecord(string message)
{
#if DEBUG
WriteLine(string.Format("{0},{1}{2}",
DateTime.Now,
new string('+', _indentLevel),
message));
#endif
}
private static void WriteLine(string line)
{
#if DEBUG
Debug.WriteLine(line);
#endif
}
public static void IndentLog()
{
#if DEBUG
++_indentLevel;
#endif
}
public static void UnindentLog()
{
#if DEBUG
--_indentLevel;
#endif
}
#if DEBUG
static int _indentLevel;
static List<string> _ignoredAsserts;
static bool _ignoreAllAsserts;
#endif
#region Constants
private const string AssertMessage = @"Method: {1}
{0} @ Line [{2}]
Message:
{3}";
#endregion
}
public class LoggerGroup : IDisposable
{
public LoggerGroup(string name)
{
_name = name;
Logger.LogMessage("LogGroup", "Start '{0}'", _name);
Logger.IndentLog();
}
#region IDisposable
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
Logger.UnindentLog();
Logger.LogMessage("LogGroup", "End '{0}'", _name);
}
_disposed = true;
}
}
bool _disposed;
#endregion
string _name;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/PostAd.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WB.Craigslist8X.ViewModel
{
public class PostAd : PostBase
{
public override PostType Type
{
get { return PostType.Ad; }
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/FavoritedPostsPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.ViewModel;
namespace WB.Craigslist8X.View
{
public sealed partial class FavoritedPostsPanel : UserControl, IPanel, IPostList
{
public FavoritedPostsPanel()
{
this.InitializeComponent();
}
public async Task AttachContext(object context, IPanel parent)
{
this._vm = new FavoritePostsVM();
this.DataContext = this._vm;
SearchProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if (this._vm.PostItems.Count < 1)
{
NoItemsFound.Visibility = Windows.UI.Xaml.Visibility.Visible;
NoItemsFound.Text = NoItemsFoundText;
}
else
{
await this.SelectItem(this._vm.PostItems.First() as PostVM);
}
await this._vm.InitAsync();
}
public void SetSelection(PostVM post)
{
if (post != null)
{
if (this._selected != null)
{
this._selected.Selected = false;
}
this._selected = post;
this._selected.Selected = true;
this.SearchItemsList.ScrollIntoView(this._selected);
}
}
public ObservableCollection<PostBase> PostItems
{
get
{
if (this._vm == null)
return null;
return this._vm.PostItems;
}
}
private void SearchItemsList_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(SearchItemsList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
private async void SearchItem_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as PostVM != null)
{
await this.SelectItem((sender as FrameworkElement).DataContext as PostVM);
}
}
private async Task SelectItem(PostVM post)
{
if (post != null)
{
await MainPage.Instance.ExecuteViewPost(this as UIElement, post);
this.SetSelection(post);
}
}
private FavoritePostsVM _vm;
private PostVM _selected;
const string NoItemsFoundText = @"No posts have been favorited.
Next time you see a post you like, look for the heart button to mark it as a favorite.";
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using HtmlAgilityPack;
using WB.SDK;
using WB.SDK.Logging;
using WB.SDK.Parsing;
namespace WB.CraigslistApi
{
internal static class Categories
{
internal static async Task<CategoryList> ScrapeCategories()
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(new Uri(Craigslist.CategoryUrl)))
{
try
{
if (response.IsSuccessStatusCode)
{
CategoryList cl = new CategoryList();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(await response.Content.ReadAsStringAsync());
var nodes = (from h in doc.DocumentNode.Descendants("h4").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "ban") select h);
foreach (var node in nodes)
{
string root;
if (node.Name == "a")
{
root = Uri.UnescapeDataString(node.InnerText);
string name = string.Format("all {0}", root);
string href = Uri.UnescapeDataString(node.Attributes["href"].Value);
cl.Add(new Category(root, name, href));
}
else
{
root = Uri.EscapeDataString(node.InnerText);
}
if (node.NextSibling == null)
continue;
foreach (var cats in node.NextSibling.Descendants("a").Where(x => x.ParentNode.Name == "li"))
{
string name = Uri.UnescapeDataString(cats.InnerText);
string href = Uri.UnescapeDataString(cats.Attributes["href"].Value);
cl.Add(new Category(root, name, href));
}
}
AddSubAreas(cl);
return cl;
}
}
catch (Exception)
{
}
return null;
}
}
/// <summary>
/// TODO: Automate retrieving this
/// </summary>
/// <param name="categories"></param>
private static void AddSubAreas(CategoryList categories)
{
}
}
public class CategoryList
{
public CategoryList()
{
_categories = new List<Category>();
}
public void Add(Category item)
{
_categories.Add(item);
}
public IEnumerable<Category> GetCategories()
{
foreach (var cat in _categories)
yield return cat;
}
#region Fields
List<Category> _categories;
#endregion
}
public class Category : IComparable<Category>, IEquatable<Category>, ICloneable<Category>
{
#region Initialization
private Category()
{
}
public Category(string root, string name, string abbr)
{
this.Root = root;
this.Name = name;
this.Abbreviation = abbr.TrimEnd('/');
}
#endregion
public Category Clone()
{
return new Category(this.Root, this.Name, this.Abbreviation);
}
public bool Equals(Category o)
{
return o == null ? false : (this.CompareTo(o) == 0);
}
public int CompareTo(Category o)
{
int x;
x = this.Root.CompareTo(o.Root);
if (x != 0)
return x;
x = this.Abbreviation.CompareTo(o.Abbreviation);
if (x != 0)
return x;
return this.Name.CompareTo(o.Name);
}
public override string ToString()
{
return Category.Serialize(this);
}
#region Serialization
public static string Serialize(Category category)
{
string result = CsvParser.WriteLine(category.Root, category.Name, category.Abbreviation);
return result;
}
public static Category Deserialize(string line)
{
List<string> values = CsvParser.ReadLine(line);
Category category = new Category();
Logger.AssertValue(values.Count, 3, "Category field count");
category.Root = values[0];
category.Name = values[1];
category.Abbreviation = values[2];
return category;
}
#endregion
#region Properties
public string Root { get; private set; }
public string Name { get; private set; }
public string Abbreviation { get; private set; }
#endregion
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/SearchSettingsVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class SearchSettingsVM : INotifyPropertyChanged
{
public SearchSettingsVM()
{
CityManager.Instance.PropertyChanged += Craigslist8X_PropertyChanged;
}
void Craigslist8X_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SearchCities")
{
this.OnPropertyChanged("SearchCities");
this.OnPropertyChanged("RemoveCityEnabled");
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region Properties
public ReadOnlyObservableCollection<CraigCity> SearchCities
{
get
{
return CityManager.Instance.SearchCities;
}
}
public string SearchCategory
{
get
{
return string.Format("{0} > {1}",
CategoryManager.Instance.SearchCategory.Root,
CategoryManager.Instance.SearchCategory.Name);
}
}
public bool DetailedSearchResults
{
get
{
return Settings.Instance.DetailedSearchResults;
}
set
{
Settings.Instance.DetailedSearchResults = value;
}
}
public bool SearchTitlesOnly
{
get
{
return Settings.Instance.OnlySearchTitles;
}
set
{
Settings.Instance.OnlySearchTitles = value;
}
}
public bool PostsPicturesOnly
{
get
{
return Settings.Instance.OnlyShowPostsPictures;
}
set
{
Settings.Instance.OnlyShowPostsPictures = value;
}
}
public bool RemoveCityEnabled
{
get
{
return CityManager.Instance.SearchCities != null && CityManager.Instance.SearchCities.Count > 1;
}
}
#endregion
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/QueryBatch.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WB.CraigslistApi
{
public class QueryBatch
{
public QueryBatch(IEnumerable<Query> queries)
{
if (queries == null)
{
throw new ArgumentNullException("queries");
}
this._queries = queries.ToList();
}
public static QueryBatch BuildQueryBatch(IEnumerable<CraigCity> cities, Query template)
{
List<Query> queries = new List<Query>();
foreach (var city in cities)
{
Query q = template.Clone();
q.City = city;
queries.Add(q);
}
return new QueryBatch(queries);
}
public async Task<List<QueryResult>> Execute(CancellationToken token)
{
List<Task<QueryResult>> tasks = new List<Task<QueryResult>>(this._queries.Count);
for (int i = 0; i < this._queries.Count; ++i)
{
var q = this._queries[i];
tasks.Add(q.Execute(token));
}
await Task.WhenAll(tasks.ToArray());
List<QueryResult> qrs = new List<QueryResult>(tasks.Count);
foreach (var task in tasks)
{
QueryResult qr = await task;
if (qr == null)
return null;
qrs.Add(qr);
}
return qrs;
}
public List<Query> Queries
{
get
{
return this._queries;
}
}
List<Query> _queries;
}
}
<file_sep>/Win8/WB/WB.SDK/Logging/MonitoredScope.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WB.SDK.Logging
{
public class MonitoredScope : LoggerGroup
{
public MonitoredScope(string name)
: base(name)
{
this._start = TimeSpan.FromTicks(System.Diagnostics.Stopwatch.GetTimestamp());
this._name = name;
}
public MonitoredScope(string name, params object[] args)
: this(string.Format(name, args))
{
}
#region IDisposable
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
TimeSpan stop = TimeSpan.FromTicks(System.Diagnostics.Stopwatch.GetTimestamp());
Logger.LogMessage("MonitoredScope", "Finished {0} in {1} milliseconds", this._name, (stop - this._start).TotalMilliseconds);
}
_disposed = true;
}
base.Dispose(disposing);
}
bool _disposed;
string _name;
TimeSpan _start;
#endregion
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/RecentlySearched.cs
using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Streams;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.Model
{
public class RecentlySearched : BindableBase, IStorageBacked
{
#region Initialization
static RecentlySearched()
{
_instanceLock = new object();
}
private RecentlySearched()
{
this.Queries = new ObservableCollection<Query>();
this._listLock = new object();
this._fileLock = new AsyncLock();
}
#endregion
#region Singleton
public static RecentlySearched Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new RecentlySearched();
return _instance;
}
}
}
static RecentlySearched _instance;
static object _instanceLock;
#endregion
#region IStorageBacked
public async Task<bool> LoadAsync()
{
StorageFile file = null;
try
{
file = await ApplicationData.Current.RoamingFolder.GetFileAsync(RecentlySearchedFileName);
}
catch (System.IO.FileNotFoundException)
{
return false;
}
if (file != null)
{
Logger.LogMessage("RecentlySearched", "Loading RecentlySearched.xml");
try
{
string content = null;
using (await this._fileLock.LockAsync())
{
content = await file.LoadFileAsync();
}
if (string.IsNullOrEmpty(content))
return true;
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
XmlNodeList queries = doc.SelectNodes("/root/q");
lock (_listLock)
{
this.Queries.Clear();
foreach (var qn in queries)
{
Query q = Query.Deserialize(qn.GetXml());
this.Queries.Add(q);
}
}
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("RecentlySearched", "Failed to read RecentlySearched.xml");
Logger.LogException(ex);
}
}
return false;
}
public async Task<bool> SaveAsync()
{
Logger.LogMessage("RecentlySearched", "Saving RecentlySearched.xml");
if (!this.Dirty)
{
Logger.LogMessage("RecentlySearched", "No changes to persist to RecentlySearched.xml");
return false;
}
try
{
StringBuilder sb = new StringBuilder();
sb.Append("<root>");
lock (_listLock)
{
for (int i = 0; i < _queries.Count && i < SaveCount; ++i)
{
sb.AppendLine(Query.Serialize(_queries[i] as Query));
}
}
sb.Append("</root>");
using (await this._fileLock.LockAsync())
{
StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(RecentlySearchedFileName, CreationCollisionOption.ReplaceExisting);
await file.SaveFileAsync(sb.ToString());
}
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("RecentlySearched", "Failed to save RecentlySearched.xml");
Logger.LogException(ex);
}
return false;
}
private bool Dirty
{
get;
set;
}
private AsyncLock _fileLock;
#endregion
#region Methods
public void AddQuery(Query query)
{
if (!Settings.Instance.TrackRecentSearches)
return;
// Add to the top because it is the most recent
lock (_listLock)
{
_queries.Insert(0, query);
// It could be the case that we have searched for this item before. If that is the case, then
// just remove the old dupe from the list.
for (int i = 1; i < this.Queries.Count; ++i)
{
Query q = this.Queries[i] as Query;
if (query.Text == q.Text && query.Category.Equals(q.Category))
{
this.Queries.RemoveAt(i);
break;
}
}
}
this.Dirty = true;
}
#endregion
#region Properties
public ObservableCollection<Query> Queries
{
get
{
return _queries;
}
private set
{
this.SetProperty(ref this._queries, value);
}
}
#endregion
#region Fields
ObservableCollection<Query> _queries;
object _listLock;
#endregion
#region Constants
const string RecentlySearchedFileName = "RecentlySearched.xml";
const int SaveCount = 50;
#endregion
}
}<file_sep>/README.md
Craigslist 8X
=============
Craigslist 8X is a Craiglist client application originally written for Windows 8.
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Interfaces/IPanel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WB.Craigslist8X.View
{
public interface IPanel
{
Task AttachContext(object context, IPanel parent);
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/AccountManagementPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using Windows.Security.Credentials;
using Windows.System;
using WB.CraigslistApi;
using WB.SDK;
using WB.SDK.Logging;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using HtmlAgilityPack;
using WinRTXamlToolkit.Net;
namespace WB.Craigslist8X.View
{
public sealed partial class AccountManagementPanel : UserControl, IPanel
{
public AccountManagementPanel()
{
this.InitializeComponent();
}
public async Task AttachContext(object context, IPanel parent)
{
this._account = context as PasswordCredential;
this._parent = parent as UIElement;
this._handler = new HttpClientHandler();
this._handler.UseCookies = true;
this._handler.CookieContainer = new CookieContainer();
this._client = new HttpClient(this._handler, disposeHandler: true);
this.LoadingProgress.Visibility = Visibility.Visible;
this.PageTitle.Text = string.Format("home of {0}", this._account.UserName);
if (!WebHelper.IsConnectedToInternet())
{
await this.AbortAccountManagement("Could not detect network connectivity. Aborting account management.");
return;
}
// If we are using cached creds, we need to login first.
if (this._account != null)
{
this._account.RetrievePassword();
// User may have changed his password or something and invalidated his cached credentials.
if (!await Craigslist.Instance.Login(this._handler, this._client, this._account.UserName, this._account.Password))
{
await this.AbortAccountManagement(string.Format("Failed to login with '{0}'. Please verify your cached credentials. Aborting account management.", this._account.UserName));
return;
}
}
await this.ShowPostings();
}
public async Task RefreshPosts()
{
await ShowPostings();
}
private async Task ShowPostings()
{
this.LoadingProgress.Visibility = Visibility.Visible;
// Initiate the posting
HttpResponseMessage response = null;
try
{
response = await this._client.GetAsync(ShowPostingsUri);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
if (response == null || !response.IsSuccessStatusCode)
{
await this.AbortAccountManagement("Received bad response from craigslist.");
return;
}
else
{
await this.ParseResponse(response, false);
}
}
private async Task ParseResponse(HttpResponseMessage response, bool wentBack)
{
bool success = false;
try
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(await response.Content.ReadAsStringAsync());
var posts = (from table in doc.DocumentNode.Descendants("table").Where(x => x.Attributes["summary"] != null && x.Attributes["summary"].Value == "postings")
from rows in table.Descendants("tr").Where(x => x.Descendants("td").Any() && x.ParentNode == table)
select rows);
List<PostingVM> postings = new List<PostingVM>();
foreach (var post in posts)
{
var posting = new PostingVM();
var status = (from td in post.Descendants("td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "status") select td).First();
posting.Status = (PostingStatus)Enum.Parse(typeof(PostingStatus), Utilities.HtmlToText(status.InnerText).Trim());
var title = (from td in post.Descendants("td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "title") select td).First();
Regex titleRegex = new Regex(@"\s*(.*?)\s*-\s*(\$\d+)?\s*$");
Match m = titleRegex.Match(title.InnerText.Replace("\n", string.Empty).Trim());
posting.Title = m.Groups[1].Value.Trim();
if (m.Groups.Count == 3)
{
posting.Price = m.Groups[2].Value.Trim();
}
var small = (from td in post.Descendants("td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "areacat")
from sm in td.Descendants("small")
select sm).First();
var area = (from b in small.Descendants("b")
select b).First();
posting.City = area.InnerText.Trim();
area.Remove();
posting.Category = Utilities.HtmlToText(small.InnerText).Trim();
Regex dateRegex = new Regex(@".*(\d{4}-\d{2}-\d{2} \d{2}:\d{2})$");
var dates = (from td in post.Descendants("td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "dates") select td).First();
posting.Date = DateTime.Parse(dateRegex.Match(dates.InnerText.Trim()).Groups[1].Value);
var postingId = (from td in post.Descendants("td").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "postingID") select td).First();
posting.PostingId = long.Parse(postingId.InnerText.Trim());
posting.Manage = new Uri(string.Format("https://post.craigslist.org/manage/{0}", posting.PostingId));
postings.Add(posting);
}
PostingsGrid.ItemsSource = postings;
success = true;
}
catch (PostParseException ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogException(ex);
}
finally
{
this.LoadingProgress.Visibility = Visibility.Collapsed;
}
if (!success)
{
MessageDialog dlg = new MessageDialog(@"Sorry, we ran into an issue parsing the response from craigslist. Please notify the developer of this app so the issue may be investigated.
In the mean time, would you like to manage your account in the browser?");
dlg.Commands.Clear();
dlg.Commands.Add(new UICommand("Yes", null, true));
dlg.Commands.Add(new UICommand("No", null, false));
UICommand result = await dlg.ShowAsync() as UICommand;
if ((bool)result.Id)
{
await Launcher.LaunchUriAsync(response.RequestMessage.RequestUri);
}
}
}
private async Task AbortAccountManagement(string message)
{
this.LoadingProgress.Visibility = Visibility.Collapsed;
await new MessageDialog(message, "Craigslist 8X").ShowAsync();
MainPage.Instance.RemoveChildPanels(this._parent);
MainPage.Instance.PanelView.SnapToPanel(this._parent);
}
private async void Refresh_Tapped(object sender, TappedRoutedEventArgs e)
{
await this.ShowPostings();
}
private async void OpenInBrowser_Tapped(object sender, TappedRoutedEventArgs e)
{
await Launcher.LaunchUriAsync(ShowPostingsUri);
}
private async void Posting_Tapped(object sender, TappedRoutedEventArgs e)
{
var el = sender as FrameworkElement;
if (el == null)
return;
var posting = el.DataContext as PostingVM;
if (posting == null)
return;
var context = new ManagePostContext()
{
Posting = posting,
Handler = this._handler,
Client = this._client,
Account = this._account
};
await MainPage.Instance.ExecuteManagePost(this, context);
}
PasswordCredential _account;
HttpClient _client;
HttpClientHandler _handler;
UIElement _parent;
readonly Uri ShowPostingsUri = new Uri("https://accounts.craigslist.org/?show_tab=postings");
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/MainOptionsVM.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class MainOptionsVM : BindableBase
{
public MainOptionsVM()
{
this.SetSearchSettings();
CityManager.Instance.PropertyChanged += Model_PropertyChanged;
CategoryManager.Instance.PropertyChanged += Model_PropertyChanged;
SavedSearches.Instance.PropertyChanged += Model_PropertyChanged;
this.SearchNotifications = SavedSearches.Instance.Notifications.ToString();
this._showAds = !App.IsPro;
}
private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SearchCities")
{
this.SetSearchSettings();
}
else if (e.PropertyName == "SearchCategory")
{
this.SetSearchSettings();
}
else if (e.PropertyName == "Notifications")
{
this.SearchNotifications = SavedSearches.Instance.Notifications.ToString();
}
}
private void SetSearchSettings()
{
this.SearchSettings = string.Format("{0} @ {1}", Utility.GetSearchCategoryLabel(), Utility.GetSearchCityLabel());
}
public string SearchSettings
{
get
{
return this._searchSettings;
}
set
{
this.SetProperty(ref this._searchSettings, value);
}
}
public bool ShowAds
{
get
{
return this._showAds && !this.HideWebView;
}
set
{
this.SetProperty(ref this._showAds, value);
}
}
public bool HideWebView
{
get
{
return this._hideWebView;
}
set
{
if (this.SetProperty(ref this._hideWebView, value))
{
this.OnPropertyChanged("ShowAds");
}
}
}
public string SearchNotifications
{
get
{
return this._notifications == 0 ? string.Empty : this._notifications.ToString();
}
set
{
this.SetProperty(ref this._notifications, int.Parse(value));
}
}
private bool _hideWebView;
private bool _showAds;
private string _searchSettings;
private int _notifications;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/Common/PostGridItemStyleSelector.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class PostGridItemStyleSelector : StyleSelector
{
public Style SearchItemPostFull
{
get;
set;
}
public Style SearchItemPostSimple
{
get;
set;
}
protected override Style SelectStyleCore(object item, DependencyObject container)
{
if (Settings.Instance.DetailedSearchResults)
{
return SearchItemPostFull;
}
else
{
return SearchItemPostSimple;
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/PostVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media.Imaging;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.ViewModel
{
public class PostVM : PostBase
{
#region Initialization
public PostVM(QueryResultVM qr, Post post)
: this(post)
{
if (qr == null)
throw new ArgumentNullException("qr");
this._qr = qr;
}
public PostVM(Post post)
: base()
{
if (post == null)
throw new ArgumentNullException("post");
this._post = post;
this.IsLoading = true;
RecentlyViewed.Instance.PropertyChanged += RecentlyViewed_PropertyChanged;
}
#endregion
#region Methods
public async Task LoadDetailsAsync()
{
if (this._post.DetailStatus == Post.PostDetailStatus.Loaded || this._post.DetailStatus == Post.PostDetailStatus.Loading)
{
this.IsLoading = false;
return;
}
await this._post.LoadDetailsAsync();
this.OnPropertyChanged("DetailStatus");
if (this._post.DetailStatus == CraigslistApi.Post.PostDetailStatus.Loaded)
{
this.OnPropertyChanged("Email");
this.OnPropertyChanged("Phone");
this.OnPropertyChanged("Timestamp");
this.OnPropertyChanged("PostAge");
this.OnPropertyChanged("UserHtml");
this.OnPropertyChanged("ShortDescription");
this.OnPropertyChanged("Pictures");
this.OnPropertyChanged("Thumbnail");
}
this.IsLoading = false;
if (this.DetailsLoaded != null)
{
this.DetailsLoaded(this, this._post.DetailStatus);
}
}
#endregion
#region Events / Handlers
public event EventHandler<Post.PostDetailStatus> DetailsLoaded;
private void RecentlyViewed_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
this.OnPropertyChanged("Visited");
}
#endregion
#region Properties
public override PostBase.PostType Type
{
get { return PostType.Post; }
}
public Post Post
{
get
{
return _post;
}
}
public Post.PostDetailStatus DetailStatus
{
get
{
return _post.DetailStatus;
}
set
{
this._post.DetailStatus = value;
}
}
public bool IsLoading
{
get
{
return this._isLoading;
}
set
{
this.SetProperty(ref this._isLoading, value);
}
}
public bool Favorite
{
get
{
return FavoritePosts.Instance.Contains(this._post);
}
set
{
if (value)
{
FavoritePosts.Instance.AddPost(this._post);
}
else
{
FavoritePosts.Instance.RemovePost(this._post);
}
this.OnPropertyChanged("Favorite");
}
}
public bool Selected
{
get
{
return this._isSelected;
}
set
{
this.SetProperty(ref this._isSelected, value);
}
}
public QueryResultVM QueryResult
{
get
{
return _qr;
}
}
#endregion
#region Post Properties
public bool HasThumbnail
{
get
{
return _post.ThumbnailUri != null;
}
}
public Uri Thumbnail
{
get
{
return this._post.ThumbnailUri;
}
}
public bool HasImages
{
get
{
return this._post.HasImages;
}
}
public bool HasPictures
{
get
{
return this._post.HasPictures;
}
}
public bool HasMap
{
get
{
return this._post.HasMap;
}
}
public List<Uri> Pictures
{
get
{
return this._post.Pictures;
}
}
public string Title
{
get
{
return _post.Title;
}
}
public string ShortDate
{
get
{
return _post.ShortDate;
}
}
public string Location
{
get
{
return WB.SDK.Utilities.HtmlToText(_post.Location);
}
}
public string Price
{
get
{
if (_post.Price != 0)
return string.Format("{0:C}", _post.Price);
else
return null;
}
}
public string ShortDescription
{
get
{
return _post.PostText;
}
}
public string UserHtml
{
get
{
return _post.UserHtml;
}
}
public string Url
{
get
{
return this._post.Url == null ? null : this._post.Url.ToString();
}
}
public string Email
{
get
{
return this._post.Email;
}
}
public string Phone
{
get
{
return this._post.Phone;
}
}
public string Timestamp
{
get
{
if (this._post.Timestamp == DateTime.MinValue)
return string.Empty;
else
return _post.Timestamp.ToString();
}
}
public string PostAge
{
get
{
if (_post.DetailStatus != CraigslistApi.Post.PostDetailStatus.Loaded)
{
return this.ShortDate;
}
TimeSpan age = DateTime.Now - this._post.Timestamp;
if (this._post.Timestamp.Year == 1) // Means we didn't get anything
return this.ShortDate;
if ((int)age.TotalDays > 7)
return this._post.Timestamp.ToString("yyyy-MM-dd");
else if ((int)age.TotalDays > 0)
return string.Format("{0}d ago", (int)age.TotalDays);
else if ((int)age.TotalHours > 0)
return string.Format("{0}h ago", (int)age.TotalHours);
else
return string.Format("{0}m ago", (int)age.TotalMinutes);
}
}
public bool Visited
{
get
{
return RecentlyViewed.Instance.Contains(this.Post);
}
}
#endregion
#region Fields
QueryResultVM _qr;
Post _post;
bool _isLoading;
bool _isSelected;
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/SavedSearchesPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
namespace WB.Craigslist8X.View
{
public sealed partial class SavedSearchesPanel : UserControl, IPanel
{
public SavedSearchesPanel()
{
this.InitializeComponent();
}
public async Task AttachContext(object context, IPanel parent)
{
if (SavedSearches.Instance.Queries.Count == 0)
{
NoItemsMessage.Text = NoItemsFound;
}
else
{
this.SearchItemList.ItemsSource = new ObservableCollection<SavedSearchVM>(from x in SavedSearches.Instance.Queries select new SavedSearchVM(x));
}
string name = context as string;
if (!string.IsNullOrEmpty(name))
{
SavedQuery sq = SavedSearches.Instance.Get(name);
if (sq != null)
{
this.SetSelection(sq);
await MainPage.Instance.ExecuteSearchQuery(this, QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, sq.Query));
}
else
{
MessageDialog dlg = new MessageDialog(string.Format(@"Unable to find the saved query: ""{0}""", name), "Craigslist 8X");
await dlg.ShowAsync();
}
}
}
private void ListView_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(this.SearchItemList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
private async void SavedSearch_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as SavedSearchVM != null)
{
SavedSearchVM ssvm = (SavedSearchVM)container.DataContext;
this.SetSelection(ssvm.SavedQuery);
await MainPage.Instance.ExecuteSavedQuery(this, ssvm.SavedQuery);
}
}
private void SetSelection(SavedQuery sq)
{
if (this._selected != null)
{
this._selected.Selected = false;
}
if (sq != null)
{
IEnumerable<SavedSearchVM> items = this.SearchItemList.ItemsSource as IEnumerable<SavedSearchVM>;
var q = (from ssvm in items.Where(x => x.SavedQuery == sq) select ssvm).FirstOrDefault();
if (q != null)
{
q.Selected = true;
this._selected = q;
}
}
}
private void DeleteSearch_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as SavedSearchVM != null)
{
e.Handled = true;
SavedSearchVM ssvm = (SavedSearchVM)container.DataContext;
SavedSearches.Instance.Remove(ssvm.SavedQuery);
this.SearchItemList.ItemsSource = new ObservableCollection<SavedSearchVM>(from x in SavedSearches.Instance.Queries select new SavedSearchVM(x));
}
}
private async void PinSearch_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as SavedSearchVM != null)
{
e.Handled = true;
SavedSearchVM ssvm = (SavedSearchVM)container.DataContext;
SecondaryTile tile = new SecondaryTile(ssvm.SavedQuery.TileId.ToString(),
ssvm.Name,
ssvm.Name,
string.Format(@"<SavedQuery ID=""{0}"" Name=""{1}"" PinTime=""{2}"" />", ssvm.SavedQuery.TileId.ToString(), Uri.EscapeDataString(ssvm.Name), DateTime.Now),
TileOptions.ShowNameOnLogo|TileOptions.ShowNameOnWideLogo,
new Uri("ms-appx:///Resources/Logo.png"),
new Uri("ms-appx:///Resources/WideLogo.png"));
await tile.RequestCreateForSelectionAsync(Utilities.GetElementRect(sender as FrameworkElement), Windows.UI.Popups.Placement.Below);
}
}
private SavedSearchVM _selected;
const string NoItemsFound = @"No saved searches found.
Saved searches will run in the background and Craigslist 8X will notify when there are new ads matching your search.
Next time you want to save a search, look for the ellipses button in the search results pane and select Save Search.";
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/RecentlySearchedPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Notifications;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
namespace WB.Craigslist8X.View
{
public sealed partial class RecentlySearchedPanel : UserControl, IPanel
{
public RecentlySearchedPanel()
{
this.InitializeComponent();
}
public Task AttachContext(object context, IPanel parent)
{
if (!Settings.Instance.TrackRecentSearches)
{
NoItemsFound.Visibility = Windows.UI.Xaml.Visibility.Visible;
NoItemsFound.Text = RecentSearchesOff;
SearchProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
return null;
}
this.vm = new RecentlySearchedVM();
this.DataContext = this.vm;
SearchProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if (this.vm.RecentQueries.Count == 0)
{
SearchItemsList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
NoItemsFound.Visibility = Windows.UI.Xaml.Visibility.Visible;
NoItemsFound.Text = "No recent searches found.";
}
return null;
}
private void SearchItemsList_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(SearchItemsList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
private async void DeleteButton_Tapped(object sender, TappedRoutedEventArgs e)
{
RecentlySearched.Instance.Queries.Clear();
var template = ToastTemplateType.ToastText02;
var content = ToastNotificationManager.GetTemplateContent(template);
content.SelectSingleNode("/toast/visual/binding/text[@id='1']").InnerText = "Craigslist 8X";
content.SelectSingleNode("/toast/visual/binding/text[@id='2']").InnerText = "Successfully cleared recently searched.";
ToastNotification toast = new ToastNotification(content);
ToastNotificationManager.CreateToastNotifier().Show(toast);
await MainPage.Instance.ExecuteRecentlySearched(null);
}
private async void RecentQuery_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as RecentlySearchedQueryVM != null)
{
this.SetSelection(sender as Border);
RecentlySearchedQueryVM vm = (sender as FrameworkElement).DataContext as RecentlySearchedQueryVM;
Query template = new Query(CityManager.Instance.SearchCities.First(), vm.Query.Category, vm.Query.Text);
template.HasImage = Settings.Instance.OnlyShowPostsPictures;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
await MainPage.Instance.ExecuteSearchQuery(this, qb);
}
}
private void SetSelection(Border item)
{
if (this._selected != null)
{
this._selected.Background = new SolidColorBrush(Colors.Transparent);
}
this._selected = item;
if (item != null)
{
this._selected.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xDD, 0xDD, 0xDD));
}
}
RecentlySearchedVM vm;
Border _selected;
private const string RecentSearchesOff = "Tracking recent searches is disabled. Go to settings to reenable.";
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Flyouts/NewsContainer.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.View
{
public sealed partial class NewsContainer : UserControl, INotifyPropertyChanged
{
public NewsContainer()
{
this.InitializeComponent();
this.DataContext = this;
}
public void SetContext(List<NewsItem> items)
{
this.News = new System.Collections.ObjectModel.ObservableCollection<NewsItem>(items);
this.ItemsFlip.ItemsSource = this.News;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs("Filter"));
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
}
public ObservableCollection<NewsItem> News
{
get
{
return this._news;
}
set
{
this._news = value;
this.OnPropertyChanged("News");
}
}
ObservableCollection<NewsItem> _news;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/SavedSearchVM.cs
using System;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class SavedSearchVM : BindableBase
{
public SavedSearchVM(SavedQuery sq)
{
this._sq = sq;
this._sq.PropertyChanged += SavedQuery_PropertyChanged;
}
void SavedQuery_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Notifications")
{
this.OnPropertyChanged("Notifications");
}
}
public bool Selected
{
get
{
return this._selected;
}
set
{
this.SetProperty(ref this._selected, value);
}
}
public string Name
{
get
{
return this._sq.Name;
}
}
public string Notifications
{
get
{
return this._sq.Notifications == 0 ? string.Empty : this._sq.Notifications.ToString();
}
}
public SavedQuery SavedQuery
{
get
{
return this._sq;
}
}
SavedQuery _sq;
bool _selected;
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/ChooseCitiesVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.Common;
using WB.CraigslistApi;
namespace WB.Craigslist8X.ViewModel
{
public class ChooseCitiesVM : BindableBase
{
public ChooseCitiesVM()
{
if (CityManager.Instance.SearchCitiesDefined)
{
this.Continent = CityManager.Instance.SearchCities.First().Continent;
}
else
{
this.Continent = "US";
}
}
public string Continent
{
get
{
return this._continent;
}
set
{
if (this.SetProperty(ref this._continent, value))
{
if (this.States == null)
this.States = new ObservableCollection<CitiesByState>();
else
this.States.Clear();
if (CityManager.Instance.Cities != null)
{
foreach (var s in CityManager.Instance.Cities.Where(x => x.Continent == this.Continent).GroupBy(x => x.State).Select(x => x.First()))
{
CitiesByState state = new CitiesByState(s.State);
this.States.Add(state);
foreach (var c in CityManager.Instance.Cities.Where(x => x.State == s.State))
{
state.Cities.Add(c);
}
}
}
}
}
}
public ObservableCollection<CitiesByState> States
{
get
{
return this._states;
}
set
{
this.SetProperty(ref this._states, value);
}
}
ObservableCollection<CitiesByState> _states;
string _continent;
}
public class CitiesByState
{
public CitiesByState(string state)
{
this.State = state;
this.Cities = new ObservableCollection<CraigCity>();
}
public string State
{
get;
private set;
}
public ObservableCollection<CraigCity> Cities
{
get;
private set;
}
}
}
<file_sep>/Win8/WB/WB.SDK/Common.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Media.Animation;
using WB.SDK.Logging;
namespace WB.SDK
{
public static class Utilities
{
static Utilities()
{
HtmlToTextMap.Add("quot", '"');
HtmlToTextMap.Add("amp", '&');
HtmlToTextMap.Add("lt", '<');
HtmlToTextMap.Add("gt", '>');
HtmlToTextMap.Add("apos", '\'');
HtmlToTextMap.Add("nbsp", ' ');
}
public static T ExecuteRetryable<T>(Func<T> action, int retries)
{
if (retries < 1)
throw new ArgumentOutOfRangeException("retries", retries, "Retries must be at least 1.");
while (retries > 0)
{
--retries;
try
{
return action();
}
catch (Exception ex)
{
Logger.LogMessage("ExecuteRetryable", "ExecuteRetryable action threw an exception. Retries remaining: {0}", retries);
Logger.LogException(ex);
}
}
return default(T);
}
public static string HtmlToText(string html)
{
if (string.IsNullOrEmpty(html))
return string.Empty;
StringBuilder sb = new StringBuilder(html.Length);
int start = -1;
int parsed = 0;
for (int i = 0; i < html.Length; ++i)
{
if (html[i] == '&')
{
start = i;
}
else if (html[i] == ';' && start >= 0)
{
// Named HTML entities like ' ' do not have the pound sign like ' '
if (html[start + 1] == '#')
{
int estart = start + 2;
int length = i - estart;
if (length > 0)
{
int value = 0;
if (int.TryParse(html.Substring(estart, length), out value))
{
try
{
char c = Convert.ToChar(value);
sb.Append(html.Substring(parsed, start - parsed));
sb.Append(c);
parsed = i + 1;
}
catch (OverflowException)
{
}
}
}
}
else
{
int estart = start + 1;
int length = i - estart;
if (length > 0)
{
string entity = html.Substring(estart, length);
if (HtmlToTextMap.ContainsKey(entity))
{
sb.Append(html.Substring(parsed, start - parsed));
sb.Append(HtmlToTextMap[entity]);
parsed = i + 1;
}
}
}
}
}
// Check if something was actually parsed so we do not have to substring and then create to string builder
// string needlessly. Savings are minor, but measurable. (<5ms per 100 strings)
if (parsed > 0)
{
sb.Append(html.Substring(parsed, html.Length - parsed));
return sb.ToString();
}
else
{
return html;
}
}
readonly static private Dictionary<string, char> HtmlToTextMap = new Dictionary<string, char>();
public static async Task<StorageFile> GetPackagedFile(string folderName, string fileName)
{
StorageFolder installFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
if (folderName != null)
{
StorageFolder subFolder = await installFolder.GetFolderAsync(folderName);
return await subFolder.GetFileAsync(fileName);
}
else
{
return await installFolder.GetFileAsync(fileName);
}
}
public static Task BeginAsync(this Storyboard storyboard)
{
System.Threading.Tasks.TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
if (storyboard == null)
tcs.SetException(new ArgumentNullException());
else
{
EventHandler<object> onComplete = null;
onComplete = (s, e) =>
{
storyboard.Completed -= onComplete;
tcs.SetResult(true);
};
storyboard.Completed += onComplete;
storyboard.Begin();
}
return tcs.Task;
}
}
public class RetryException : Exception
{
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/CreatePostVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using WB.SDK;
namespace WB.Craigslist8X.ViewModel
{
public class PickItemVM
{
public PickItemVM(string display, HtmlNode node)
{
this.Display = Utilities.HtmlToText(display);
this.Node = node;
this.Name = node.Attributes["name"].Value;
this.Value = node.Attributes["value"].Value;
}
public string Display
{
get;
set;
}
public HtmlNode Node
{
get;
private set;
}
public string Name
{
get;
set;
}
public string Value
{
get;
set;
}
}
public class FormFieldItem
{
public string Name { get; set; }
public string Value { get; set; }
public string Text { get; set; }
public FormFieldItem(string name, string value, string text)
{
this.Name = name;
this.Value = value;
this.Text = text;
}
}
public class FormHiddenField
{
public string Name { get; set; }
public string Value { get; set; }
public FormHiddenField(string name, string value)
{
this.Name = name;
this.Value = value;
}
}
public class EventDateFields
{
public string Year
{
get;
set;
}
public string Month
{
get;
set;
}
public string Day
{
get;
set;
}
}
public class ImageBoxVM
{
public ImageBoxVM()
{
this.HiddenFields = new List<FormHiddenField>();
}
public Uri Image
{
get;
set;
}
public List<FormHiddenField> HiddenFields
{
get;
set;
}
public virtual bool ShowDelete
{
get
{
return true;
}
}
}
public class AddImageBoxVM : ImageBoxVM
{
public override bool ShowDelete
{
get
{
return false;
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Flyouts/Filters/ChooseOneFilter.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WB.CraigslistApi;
namespace WB.Craigslist8X.View
{
public sealed partial class ChooseOneFilter : UserControl, INotifyPropertyChanged
{
public ChooseOneFilter()
{
this.InitializeComponent();
this.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs("Filter"));
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
}
public QueryFilterChooseOne Filter
{
get
{
return this._filter;
}
set
{
this._filter = value;
this.OnPropertyChanged("Filter");
}
}
QueryFilterChooseOne _filter;
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/RecentlyViewed.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Streams;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.Model
{
public class RecentlyViewed : BindableBase, IStorageBacked
{
#region Initialization
static RecentlyViewed()
{
_instanceLock = new object();
}
private RecentlyViewed()
{
this.Posts = new ObservableCollection<Post>();
this._listLock = new object();
this._fileLock = new AsyncLock();
this.Posts.CollectionChanged += Posts_CollectionChanged;
}
void Posts_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
this.OnPropertyChanged("Posts");
}
#endregion
#region Singleton
public static RecentlyViewed Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new RecentlyViewed();
return _instance;
}
}
}
static RecentlyViewed _instance;
static object _instanceLock;
#endregion
#region IStorageBacked
public async Task<bool> LoadAsync()
{
StorageFile file = null;
try
{
file = await ApplicationData.Current.RoamingFolder.GetFileAsync(RecentlyViewedFileName);
}
catch (System.IO.FileNotFoundException)
{
return false;
}
if (file != null)
{
Logger.LogMessage("RecentlyViewed", "Loading RecentlyViewed.xml");
try
{
string content = null;
using (await this._fileLock.LockAsync())
{
content = await file.LoadFileAsync();
}
if (string.IsNullOrEmpty(content))
return true;
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
XmlNodeList queries = doc.SelectNodes("/root/p");
lock (_listLock)
{
this.Posts.Clear();
foreach (var qn in queries)
{
Post post = Post.Deserialize(qn.GetXml());
this.Posts.Add(post);
}
}
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("RecentlyViewed", "Failed to read RecentlyViewed.xml");
Logger.LogException(ex);
}
}
return false;
}
public async Task<bool> SaveAsync()
{
Logger.LogMessage("RecentlyViewed", "Saving RecentlyViewed.xml");
if (!this.Dirty)
{
Logger.LogMessage("RecentlyViewed", "No changes to persist to RecentlyViewed.xml");
return false;
}
try
{
StringBuilder sb = new StringBuilder();
sb.Append("<root>");
lock (_listLock)
{
for (int i = 0; i < _posts.Count && i < SaveCount; ++i)
{
sb.AppendLine(Post.Serialize(_posts[i] as Post));
}
}
sb.Append("</root>");
using (await this._fileLock.LockAsync())
{
StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(RecentlyViewedFileName, CreationCollisionOption.ReplaceExisting);
await file.SaveFileAsync(sb.ToString());
}
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("RecentlyViewed", "Failed to save RecentlyViewed.xml");
Logger.LogException(ex);
}
return false;
}
private bool Dirty
{
get;
set;
}
private AsyncLock _fileLock;
#endregion
#region Methods
public bool Contains(Post post)
{
lock (this._listLock)
{
foreach (var p in this.Posts)
{
if (p.Url.Equals(post.Url))
return true;
}
}
return false;
}
public void AddPost(Post post)
{
if (!Settings.Instance.TrackRecentlyViewedPosts)
return;
// Add to the top because it is the most recent
lock (_listLock)
{
_posts.Insert(0, post);
// It could be the case that we have searched for this item before. If that is the case, then
// just remove the old dupe from the list.
for (int i = 1; i < this.Posts.Count; ++i)
{
Post p = this.Posts[i] as Post;
if (post.Url == p.Url)
{
this.Posts.RemoveAt(i);
break;
}
}
}
this.OnPropertyChanged("Posts");
this.Dirty = true;
}
#endregion
#region Properties
public ObservableCollection<Post> Posts
{
get
{
return _posts;
}
private set
{
this.SetProperty(ref this._posts, value);
}
}
#endregion
#region Fields
ObservableCollection<Post> _posts;
object _listLock;
#endregion
#region Constants
const string RecentlyViewedFileName = "RecentlyViewed.xml";
const int SaveCount = 50;
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Flyouts/ContinentPicker.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Callisto.Controls;
namespace WB.Craigslist8X.View
{
public sealed partial class ContinentPicker : UserControl
{
public ContinentPicker()
{
this.InitializeComponent();
}
private void TextBlock_Tapped(object sender, TappedRoutedEventArgs e)
{
TextBlock txt = sender as TextBlock;
this.Continent = txt.Text;
if (this.Parent is Flyout)
{
Flyout f = this.Parent as Flyout;
f.IsOpen = false;
}
}
public string Continent
{
get;
set;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/SearchResultsVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.ViewModel
{
public sealed class SearchResultsVM : BindableBase
{
public SearchResultsVM(QueryBatch qb)
{
this._qb = qb;
this.SearchCities = new ObservableCollection<CraigCity>();
foreach (var q in qb.Queries)
{
this.SearchCities.Add(q.City);
}
}
#region Methods
public event EventHandler QueryExecuted;
public async Task ExecuteQueryAsync(CancellationToken token)
{
this.LoadingItems = true;
List<QueryResult> qrs = null;
try
{
qrs = await this._qb.Execute(token);
}
catch (TaskCanceledException ex)
{
Logger.LogException(ex);
}
if (qrs != null)
{
this.QuerySucceeded = true;
this.QueryResults = (from x in qrs select new QueryResultVM(this, x)).ToList();
foreach (var qr in this.QueryResults)
{
qr.PostItems.CollectionChanged += PostItems_CollectionChanged;
}
this._postGroups = new ObservableCollection<PostGroup>();
for (int i = 0; i < this.QueryResults.Count; ++i)
{
QueryResultVM qr = this.QueryResults[i];
PostGroup group = new PostGroup() { City = qr.QueryResult.Query.City };
this._postGroups.Add(group);
foreach (var p in qr.PostItems)
{
group.Add(p);
}
}
}
if (this.SelectedCity == null)
{
this.SelectedCity = this._qb.Queries.First().City;
}
else
{
// HACK
CraigCity city = this.SelectedCity;
this._city = null;
this.SelectedCity = city;
}
this.LoadingItems = false;
if (this.QueryExecuted != null)
this.QueryExecuted(this, null);
}
public QueryResultVM GetCityQueryResult(CraigCity city)
{
if (this.QueryResults != null)
{
foreach (var qr in this.QueryResults)
{
if (qr.QueryResult.Query.City.Equals(city))
{
return qr;
}
}
}
return null;
}
async void PostItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var qr in this.QueryResults)
{
// Was the right sub list modified?
if (qr.PostItems == sender)
{
// Find the right group for the grid view
PostGroup group = this._postGroups.Where(x => x.City.Equals(qr.QueryResult.Query.City)).First();
await Logger.AssertNotNull(group, "we couldn't find the post group??");
// Add or remove the right posts
if (e.Action == NotifyCollectionChangedAction.Remove)
{
group.Remove(group.Last());
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
for (int j = 0; j < e.NewItems.Count; ++j)
{
PostBase post = e.NewItems[j] as PostBase;
group.Add(e.NewItems[j] as PostBase);
}
}
break;
}
}
}
#endregion
#region Properties
public bool ShowAds
{
get
{
return !App.IsPro;
}
}
public bool FiltersSet
{
get
{
if (this.FirstQuery.HasImage
|| this.FirstQuery.Type == Query.QueryType.TitleOnly
|| (this.FirstQuery.Filters != null && this.FirstQuery.Filters.FiltersSet())
)
return true;
return false;
}
}
public bool SortSet
{
get
{
return this.FirstQuery.Sort != Query.SortOrder.Recent;
}
}
public bool QuerySucceeded
{
get;
set;
}
public string SearchTitle
{
get
{
if (string.IsNullOrEmpty(this.FirstQuery.Text))
return string.Format(BrowsingPosts, this.FirstQuery.Category.Name);
else
return string.Format(SearchingPosts, this.FirstQuery.Text, this.FirstQuery.Category.Name);
}
}
public ObservableCollection<PostBase> PostItems
{
get
{
return this._postItems;
}
private set
{
this.SetProperty(ref this._postItems, value);
}
}
public List<QueryResultVM> QueryResults
{
get
{
return _qrVM;
}
private set
{
this.SetProperty(ref this._qrVM, value);
}
}
public ObservableCollection<CraigCity> SearchCities
{
get
{
return this._searchCities;
}
set
{
this.SetProperty(ref this._searchCities, value);
}
}
public CraigCity SelectedCity
{
get
{
return this._city;
}
set
{
if (value == null)
return;
if (this._city == null || !this._city.Equals(value))
{
this.SetProperty(ref this._city, value);
if (this._postGroups == null)
return;
foreach (var c in this._postGroups)
{
if (this._city.Equals(c.City))
{
this.PostItems = c;
break;
}
}
}
}
}
public bool LoadingItems
{
get
{
return _loadingItems;
}
set
{
this.SetProperty(ref this._loadingItems, value);
}
}
public Query FirstQuery
{
get
{
return this._qb.Queries.First();
}
}
public bool CollapseOnSelection
{
get
{
return Settings.Instance.CollapseOnSelection;
}
set
{
Settings.Instance.CollapseOnSelection = value;
}
}
#endregion
#region Fields
CraigCity _city;
QueryBatch _qb;
List<QueryResultVM> _qrVM;
ObservableCollection<PostBase> _postItems;
ObservableCollection<PostGroup> _postGroups;
ObservableCollection<CraigCity> _searchCities;
bool _loadingItems;
#endregion
#region Constants
const string BrowsingPosts = "Browsing {0}";
const string SearchingPosts = "{0} in {1}";
#endregion
}
public class PostGroup : ObservableCollection<PostBase>
{
public CraigCity City
{
get;
set;
}
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/CreatePostPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.Storage.Pickers;
using Windows.System;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Security.Credentials;
using HtmlAgilityPack;
using Syncfusion.UI.Xaml.Controls.Input;
using WinRTXamlToolkit.Controls;
using WinRTXamlToolkit.Tools;
using WinRTXamlToolkit.Net;
using WB.SDK;
using WB.SDK.Logging;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
namespace WB.Craigslist8X.View
{
public sealed partial class CreatePostPanel : UserControl, IPanel, IDisposable
{
public CreatePostPanel()
{
this.InitializeComponent();
}
#region IPanel
public async Task AttachContext(object context, IPanel parent)
{
this._backHistory = new Stack<Uri>();
this._context = (CreatePostContext)context;
this._parent = parent as UIElement;
if (this._context.Handler == null)
{
this._context.Handler = new HttpClientHandler();
this._context.Handler.UseCookies = true;
this._context.Handler.CookieContainer = new CookieContainer();
}
if (this._context.Client == null)
{
this._context.Client = new HttpClient(this._context.Handler, disposeHandler: true);
}
this.LoadingProgress.Visibility = Visibility.Visible;
if (!WebHelper.IsConnectedToInternet())
{
await this.AbortPost("Could not detect network connectivity. Aborting create post.");
return;
}
// If we are using cached creds, we need to login first.
if (this._context.Account != null)
{
this._context.Account.RetrievePassword();
// User may have changed his password or something and invalidated his cached credentials.
if (!await Craigslist.Instance.Login(this._context.Handler, this._context.Client, this._context.Account.UserName, this._context.Account.Password))
{
await this.AbortPost(string.Format("Failed to login with '{0}'. Please verify your cached credentials. Aborting create post.", this._context.Account.UserName));
return;
}
}
// Get the city specific create post URL
Uri startPostLink = null;
if (_context.Url != null)
startPostLink = _context.Url;
else
startPostLink = await Craigslist.Instance.GetPostUri(this._context.City);
if (startPostLink == null)
{
await this.AbortPost("Unexpected error initiating new post session from craigslist.org. Aborting create post.");
return;
}
// Initiate the posting
HttpResponseMessage response = null;
try
{
response = await this._context.Client.GetAsync(startPostLink);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
if (response == null || !response.IsSuccessStatusCode)
{
await this.AbortPost("Received bad response from craigslist.");
return;
}
else
{
// Set the post link for followup requests
this._postLink = new Uri(response.RequestMessage.RequestUri.AbsoluteUri.Replace(response.RequestMessage.RequestUri.Query, string.Empty));
await this.ParseResponse(response, false);
}
}
#endregion
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (this._context.Client != null)
{
this._context.Client.Dispose();
this._context.Client = null;
}
}
}
#endregion
#region Response Parsing
private async Task AbortPost(string message)
{
this.LoadingProgress.Visibility = Visibility.Collapsed;
await new MessageDialog(message, "Craigslist 8X").ShowAsync();
MainPage.Instance.RemoveChildPanels(this._parent);
MainPage.Instance.PanelView.SnapToPanel(this._parent);
}
private async Task ParseResponse(HttpResponseMessage response, bool wentBack)
{
string query = response.RequestMessage.RequestUri.Query;
bool success = false;
try
{
HtmlNode.ElementsFlags.Remove("form");
HtmlNode.ElementsFlags.Remove("option");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(await response.Content.ReadAsStringAsync());
this.SetTitle(doc);
// Grab and cache the hidden value identifying this posting session
var form = (from f in doc.DocumentNode.Descendants("form") select f).FirstOrDefault();
if (form != null)
{
var hiddens = (from input in form.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "hidden") select input);
if (hiddens != null)
{
this._hiddenFields = new List<FormHiddenField>();
foreach (var h in hiddens)
{
this._hiddenFields.Add(new FormHiddenField(h.Attributes["name"].Value, h.Attributes["value"].Value));
}
}
}
// Most of the create post pages are "pick one of the following" type pages. So we handle those in a generic container.
if (query.Contains("s=type") || query.Contains("s=cat") || query.Contains("s=hcat") ||
query.Contains("s=ptype") || query.Contains("s=subarea") || query.Contains("s=ltr") ||
query.Contains("s=gs"))
{
if (query.Contains("s=cat") && doc.DocumentNode.InnerText.IndexOf("select one or more categories", StringComparison.OrdinalIgnoreCase) > 0)
{
await this.ParseJobCategories(doc);
}
else
{
string label = "Choose one of the following";
if (query.Contains("s=type"))
label = "Choose your type of posting";
else if (query.Contains("s=hcat"))
label = "Choose your category";
else if (query.Contains("s=subarea"))
label = "Choose the area nearest you";
else if (query.Contains("s=ptype"))
label = "Choose what you have in mind";
else if (query.Contains("s=ltr"))
label = "Choose the kind of relationship you are looking for";
else if (query.Contains("s=cat"))
label = "Choose a category";
else if (query.Contains("s=gs"))
label = "Do you want to hire someone for a short-term gig or are you offering a service?";
await this.ParsePickOne(doc, label);
}
}
else if (query.Contains("s=mix"))
{
await this.ParseMix(doc);
}
else if (query.Contains("s=editimage"))
{
await this.ParseEditImages(doc);
}
else if (query.Contains("s=edit"))
{
await this.ParseEdit(doc);
}
else if (query.Contains("s=account"))
{
PasswordCredential account = await UserAccounts.PromptForCreds("Login to craigslist to continue with your posting");
if (account != null)
{
account.RetrievePassword();
if (!await Craigslist.Instance.Login(this._context.Handler, this._context.Client, account.UserName, account.Password))
{
await new MessageDialog("Login failed. Pease verify your username and password and try again.", "Craigslist 8X").ShowAsync();
}
else
{
await new MessageDialog("Login successful.", "Craigslist 8X").ShowAsync();
this._context.Account = account;
}
}
this.ToggleNavigationButtons(true);
this.LoadingProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
return;
}
else if (query.Contains("s=geoverify") || query.Contains("s=freejob"))
{
var inputs = (from input in doc.DocumentNode.Descendants("input").Where(x => x.Attributes["name"] != null) select input);
StringBuilder sb = new StringBuilder();
foreach (var input in inputs)
{
sb.Append(string.Format("&{0}={1}", Uri.EscapeDataString(input.Attributes["name"].Value), Uri.EscapeDataString(input.Attributes["value"].Value)));
}
HttpContent content = new StringContent(sb.ToString().Substring(1));
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content);
return;
}
else if (query.Contains("s=preview"))
{
await this.ParseEditPreview(doc);
}
else if (query.Contains("s=mailoop") || query.Contains("s=redirect"))
{
await this.ParseEmailApproval(doc);
}
else
{
MessageDialog dlg = new MessageDialog(@"Sorry, we have reached an unexpected posting state. Please notify the developer of this app so the issue may be fixed.
In the mean time, would you like to finish your post in the browser?");
dlg.Commands.Clear();
dlg.Commands.Add(new UICommand("Yes", null, true));
dlg.Commands.Add(new UICommand("No", null, false));
UICommand result = await dlg.ShowAsync() as UICommand;
if ((bool)result.Id)
{
await Launcher.LaunchUriAsync(response.RequestMessage.RequestUri);
}
}
// Once we have finished parsing the response and shown appropriate UI, we store the URI
// so we can enable the back button.
this._currentPage = response.RequestMessage.RequestUri;
this.ToggleNavigationButtons(true);
success = true;
}
catch (PostParseException ex)
{
Logger.LogException(ex);
}
finally
{
this.LoadingProgress.Visibility = Visibility.Collapsed;
}
if (!success)
{
MessageDialog dlg = new MessageDialog(@"Sorry, we ran into an issue parsing the response from craigslist. Please notify the developer of this app so the issue may be investigated.
In the mean time, would you like to finish your post in the browser?");
dlg.Commands.Clear();
dlg.Commands.Add(new UICommand("Yes", null, true));
dlg.Commands.Add(new UICommand("No", null, false));
UICommand result = await dlg.ShowAsync() as UICommand;
if ((bool)result.Id)
{
await Launcher.LaunchUriAsync(response.RequestMessage.RequestUri);
}
}
}
private async Task ParsePickOne(HtmlDocument doc, string label)
{
var formNode = (from body in doc.DocumentNode.Descendants("body")
from form in body.Descendants("form")
select form).FirstOrDefault();
if (formNode == null)
{
throw new PostParseException("Could not find form node");
}
var radios = (from input in formNode.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "radio")
select input);
if (!radios.Any())
{
throw new PostParseException("Could not find radio options.");
}
var items = (from input in radios
select new PickItemVM(input.ParentNode.InnerText.Trim(), input)).ToList();
this.PickOneLabel.Text = label;
this.PickOneGrid.ItemsSource = items;
await this.FinalizeSetPostState(CreatePostState.PickOne);
}
private async Task ParseJobCategories(HtmlDocument doc)
{
var formNode = (from body in doc.DocumentNode.Descendants("body")
from form in body.Descendants("form")
select form).FirstOrDefault();
if (formNode == null)
{
throw new PostParseException("Could not find form node");
}
var checkboxes = (from input in formNode.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "checkbox")
select input);
if (!checkboxes.Any())
{
throw new PostParseException("Could not find checkbox inputs");
}
List<PickItemVM> items = (from input in checkboxes
select new PickItemVM(input.ParentNode.InnerText.Trim(), input)).ToList();
this.JobsCategoryGrid.ItemsSource = items;
// Mark selected items
foreach (var item in items)
{
if (item.Node.Attributes["checked"] != null)
this.JobsCategoryGrid.SelectedItems.Add(item);
}
await this.FinalizeSetPostState(CreatePostState.JobsCategory);
}
private async Task ParseMix(HtmlDocument doc)
{
var formNode = (from body in doc.DocumentNode.Descendants("body")
from form in body.Descendants("form")
select form).FirstOrDefault();
if (formNode == null)
{
throw new PostParseException("Could not find form node");
}
var fieldSets = (from fieldSet in formNode.Descendants("fieldset")
select fieldSet).ToList();
if (fieldSets.Count != 2)
{
throw new PostParseException("Could not find fieldset nodes");
}
LeftMixGrid.ItemsSource = (from radio in fieldSets.First().Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "radio")
select new PickItemVM(
(from label in radio.ParentNode.Descendants("label").Where(x => x.Attributes["for"] != null && x.Attributes["for"].Value == radio.Id) select label).First().InnerText,
radio));
RightMixGrid.ItemsSource = (from radio in fieldSets.Last().Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "radio")
select new PickItemVM(
(from label in radio.ParentNode.Descendants("label").Where(x => x.Attributes["for"] != null && x.Attributes["for"].Value == radio.Id) select label).First().InnerText,
radio));
await this.FinalizeSetPostState(CreatePostState.Mix);
}
private async Task ParseEditImages(HtmlDocument doc)
{
// We only want the continue form fields to show up here
this._hiddenFields.Clear();
// There are a minimum of 3 forms on this page, we need the right one. (the right one being the done form)
var form = (from f in doc.DocumentNode.Descendants("form")
from d in f.Descendants("button").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("done"))
from fg in d.Ancestors("form")
select fg).FirstOrDefault();
var hiddenGo = (from input in form.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "hidden") select input);
foreach (var h in hiddenGo)
{
this._hiddenFields.Add(new FormHiddenField(h.Attributes["name"].Value, h.Attributes["value"].Value));
}
var maxImgCount = (from divposting in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("posting"))
from p in divposting.Descendants("p").Where(x => x.InnerText.Contains("add up to"))
select p).FirstOrDefault();
if (maxImgCount != null)
{
ImageBoxText.Text = maxImgCount.InnerText.Trim();
}
var imgbox = (from ib in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "imgbox")
select ib);
List<ImageBoxVM> images = new List<ImageBoxVM>();
// Add the images already on the server
foreach (var ib in imgbox)
{
ImageBoxVM vm = new ImageBoxVM();
var hidden = (from input in ib.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "hidden")
select input);
foreach (var h in hidden)
{
vm.HiddenFields.Add(new FormHiddenField(h.Attributes["name"].Value, h.Attributes["value"].Value));
}
vm.Image = (from uri in ib.Descendants("img").Where(x => x.Attributes["src"] != null)
select new Uri(uri.Attributes["src"].Value)).First();
images.Add(vm);
}
// Add the Add more items image box
var addMoreDiv = (from add in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "addmore")
select add).First();
if (addMoreDiv.Attributes["style"] == null || (addMoreDiv.Attributes["style"] != null && addMoreDiv.Attributes["style"].Value.Contains("none")))
{
AddImageBoxVM vm = new AddImageBoxVM();
vm.Image = new Uri("ms-appx:///Resources/AddImage.png");
var hidden = (from input in addMoreDiv.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "hidden")
select input);
foreach (var h in hidden)
{
vm.HiddenFields.Add(new FormHiddenField(h.Attributes["name"].Value, h.Attributes["value"].Value));
}
images.Add(vm);
}
ImageBoxGrid.ItemsSource = images;
await this.FinalizeSetPostState(CreatePostState.EditImages);
}
private async Task ParseEdit(HtmlDocument doc)
{
// Clean up the posting fields. User may have navigated away and come back.
List<UIElement> remove = new List<UIElement>();
foreach (var el in this.PostingFields.Children)
{
if (el == this.PostingTitleText || el == this.SpecificLocText)
continue;
remove.Add(el);
}
foreach (var el in remove)
{
this.PostingFields.Children.Remove(el);
}
var formNode = (from form in doc.DocumentNode.Descendants("form").Where(x => x.Id == "postingForm") select form).FirstOrDefault();
if (formNode == null)
{
throw new PostParseException("Could not find form node");
}
await this.ParseEditTitleRow(formNode);
await this.ParseEditEmailRow(formNode);
await this.ParseEditEventDates(formNode);
await this.ParseCompensation(formNode);
this.ParseEditPostMap(formNode);
this.ParseEditPerms(formNode);
await this.FinalizeSetPostState(CreatePostState.Edit);
}
private async Task ParseEditPreview(HtmlDocument doc)
{
var post = (from posting in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("posting")) select posting).FirstOrDefault();
if (post != null)
{
PreviewWebView.NavigateToString(post.OuterHtml);
}
await this.FinalizeSetPostState(CreatePostState.Preview);
}
private async Task ParseEmailApproval(HtmlDocument doc)
{
var email = (from font in doc.DocumentNode.Descendants("font").Where(x => x.Attributes["color"] != null && x.Attributes["color"].Value == "green") select font).FirstOrDefault();
if (email != null)
{
ApprovalEmail.Text = string.Format("Email sent to: {0}", email.InnerText);
}
await this.FinalizeSetPostState(CreatePostState.Approval);
}
private async Task ParseEditTitleRow(HtmlNode formNode)
{
var titleRow = (from div in formNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "title row") select div).FirstOrDefault();
if (titleRow == null)
{
throw new PostParseException("Could not find title row");
}
// The titlerow should only contain divs, which in turn may or may not contain actual fields
foreach (var node in titleRow.ChildNodes)
{
if (node.InnerText.IndexOf("Posting Title", StringComparison.OrdinalIgnoreCase) >= 0)
{
PostingTitleText.Tag = node.Descendants("input").First().Attributes["name"].Value;
PostingTitleText.Text = node.Descendants("input").First().Attributes["value"].Value;
continue;
}
if (node.InnerText.IndexOf("Specific Location", StringComparison.OrdinalIgnoreCase) >= 0)
{
SpecificLocText.Tag = node.Descendants("input").First().Attributes["name"].Value;
SpecificLocText.Text = node.Descendants("input").First().Attributes["value"].Value;
continue;
}
var inputNode = (from input in node.Descendants("input") select input).FirstOrDefault();
if (inputNode != null)
{
WatermarkTextBox tb = new WatermarkTextBox();
tb.WatermarkText = node.InnerText.Replace(":", string.Empty).Replace("$", string.Empty).Trim();
tb.Tag = inputNode.Attributes["name"].Value;
tb.Margin = new Thickness(10, 5, 10, 5);
tb.Text = node.Descendants("input").First().Attributes["value"].Value;
if (tb.WatermarkText.Contains("Price") || tb.WatermarkText.Contains("Age"))
{
tb.InputScope = new InputScope();
tb.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.NumberFullWidth });
}
if (inputNode.Attributes["class"] != null && inputNode.Attributes["class"].Value.Contains("req"))
{
tb.BorderBrush = new SolidColorBrush(Windows.UI.Colors.DarkGreen);
}
PostingFields.Children.Add(tb);
continue;
}
var missedNamedField = (from field in node.Descendants().Where(x => x.Attributes["name"] != null && x.Attributes["type"] != null && x.Attributes["type"].Value == "checkbox") select field);
if (missedNamedField != null && missedNamedField.Count() > 0)
await Logger.AssertNotReached("Looks like we may have missed a named field");
}
foreach (var node in titleRow.ChildNodes)
{
var selectNode = (from sel in node.Descendants("select") select sel).FirstOrDefault();
if (selectNode != null)
{
SfDomainUpDown dud = new SfDomainUpDown();
dud.Margin = new Thickness(10, 5, 10, 5);
dud.ContentTemplate = this.Resources["DomainUpDownTemplate"] as DataTemplate;
List<FormFieldItem> items = new List<FormFieldItem>();
foreach (var value in (from val in selectNode.Descendants("option") select val))
{
items.Add(new FormFieldItem(selectNode.Attributes["name"].Value, value.Attributes["value"].Value, value.InnerText));
}
dud.ItemsSource = items;
dud.Value = items.First();
var span = node.Descendants("span").FirstOrDefault();
if (span != null)
{
PostingFields.Children.Add(this.GetPostingFieldLabel(span.InnerText.Trim()));
}
else if (node.InnerText.Contains("Category"))
{
PostingFields.Children.Add(this.GetPostingFieldLabel("Category"));
}
PostingFields.Children.Add(dud);
continue;
}
}
if (PostingTitleText.Tag == null || SpecificLocText.Tag == null)
{
throw new PostParseException("Could not find Posting Title and Description fields");
}
var description = (from textarea in formNode.Descendants("textarea") select textarea).FirstOrDefault();
if (description == null)
{
throw new PostParseException("Could not find description field");
}
DescriptionText.Text = Utilities.HtmlToText(description.InnerText);
DescriptionText.Tag = description.Attributes["name"].Value;
}
private async Task ParseEditEmailRow(HtmlNode formNode)
{
var emailNode = (from email in formNode.Descendants().Where(x => x.Attributes["name"] != null && x.Attributes["name"].Value == "FromEMail") select email).First();
this.PostingFields.Children.Add(this.GetPostingFieldLabel("Reply-To Email"));
if (this._context.Account == null)
{
await Logger.AssertValue(emailNode.Attributes["type"].Value, "text", "Expected hidden email node");
WatermarkTextBox tb = new WatermarkTextBox();
tb.WatermarkText = "Your Email";
tb.Name = "FromEMail";
tb.Tag = "FromEMail";
tb.Margin = new Thickness(10, 5, 10, 5);
tb.BorderBrush = new SolidColorBrush(Colors.DarkGreen);
tb.Text = emailNode.Attributes["value"].Value.Contains("Your email address") ? string.Empty : emailNode.Attributes["value"].Value;
this.PostingFields.Children.Add(tb);
}
else
{
TextBlock tb = this.GetPostingFieldLabel(this._context.Account.UserName);
tb.Tag = "FromEMail";
tb.Name = "FromEMail";
tb.Margin = new Thickness(10, 5, 10, 5);
tb.FontWeight = Windows.UI.Text.FontWeights.Normal;
this.PostingFields.Children.Add(tb);
}
var inputs = (from div in formNode.Descendants("div").Where(x => x.Id == "oiab")
from radio in div.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "radio")
select radio);
var values = new List<FormFieldItem>();
SfDomainUpDown dud = new SfDomainUpDown();
dud.ItemsSource = values;
dud.Margin = new Thickness(10, 0, 10, 10);
dud.ContentTemplate = this.Resources["DomainUpDownTemplate"] as DataTemplate;
foreach (var value in inputs)
{
if (value.Attributes["type"] != null && value.Attributes["type"].Value == "radio")
{
string emailType = value.Attributes["value"].Value;
if (emailType == "P")
values.Add(new FormFieldItem(value.Attributes["name"].Value, value.Attributes["value"].Value, "show email"));
else if (emailType == "A")
values.Add(new FormFieldItem(value.Attributes["name"].Value, value.Attributes["value"].Value, "hide email"));
else if (emailType == "C")
values.Add(new FormFieldItem(value.Attributes["name"].Value, value.Attributes["value"].Value, "anonymize email"));
else
await Logger.AssertNotReached("Unexpected email option");
if (value.Attributes["checked"] != null)
dud.Value = values.Last();
}
}
if (values.Any())
this.PostingFields.Children.Add(dud);
}
private async Task ParseEditEventDates(HtmlNode formNode)
{
var ed = (from div in formNode.Descendants("div").Where(x => x.Id == "ed") select div).FirstOrDefault();
if (ed != null)
{
EventDateFields startDate = new EventDateFields();
EventDateFields endDate = new EventDateFields();
var inputs = (from input in ed.Descendants("input") select input);
foreach (var input in inputs)
{
var date = input.Attributes["class"] != null && input.Attributes["class"].Value == "req" ? startDate : endDate;
var type = input.ParentNode.InnerText;
if (type.Contains("Year"))
{
date.Year = input.Attributes["name"].Value;
}
else if (type.Contains("Mo"))
{
date.Month = input.Attributes["name"].Value;
}
else if (type.Contains("Day"))
{
date.Day = input.Attributes["name"].Value;
}
else
{
await Logger.AssertNotReached("Unknown date input field");
}
}
this.PostingFields.Children.Add(this.GetPostingFieldLabel("Event Start Date"));
SfDatePicker sdp = new SfDatePicker();
sdp.Name = "StartDate";
sdp.Margin = new Thickness(10, 0, 10, 5);
sdp.Tag = startDate;
sdp.ValueChanged += (s, e) =>
{
SfDatePicker dp = s as SfDatePicker;
DateTime dt = (DateTime)dp.Value;
if (DateTime.Now.Date > dt)
{
dp.Value = DateTime.Now.Date;
}
SfDatePicker _edp = this.PostingFields.FindName("EndDate") as SfDatePicker;
if ((DateTime)_edp.Value < (DateTime)dp.Value)
_edp.Value = dp.Value;
};
this.PostingFields.Children.Add(sdp);
this.PostingFields.Children.Add(this.GetPostingFieldLabel("Event End Date"));
SfDatePicker edp = new SfDatePicker();
edp.Name = "EndDate";
edp.Margin = new Thickness(10, 0, 10, 5);
edp.Tag = endDate;
edp.ValueChanged += (s, e) =>
{
SfDatePicker dp = s as SfDatePicker;
SfDatePicker _sdp = this.PostingFields.FindName("StartDate") as SfDatePicker;
if ((DateTime)dp.Value < (DateTime)_sdp.Value)
{
dp.Value = _sdp.Value;
}
};
this.PostingFields.Children.Add(edp);
}
}
private async Task ParseCompensation(HtmlNode formNode)
{
var cd = (from compdet in formNode.Descendants("span").Where(x => x.Id == "compdet")
select compdet).FirstOrDefault();
if (cd != null)
{
var p = cd.ParentNode;
await Logger.Assert(p.Name == "p", "Parent should be a p node");
this.PostingFields.Children.Add(this.GetPostingFieldLabel("Compensation"));
var radios = (from r in p.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "radio")
select r);
if (radios != null && radios.Count() > 0)
{
var values = new List<FormFieldItem>();
SfDomainUpDown dud = new SfDomainUpDown();
dud.ItemsSource = values;
dud.Margin = new Thickness(10, 0, 10, 10);
dud.ContentTemplate = this.Resources["DomainUpDownTemplate"] as DataTemplate;
foreach (var radio in radios)
{
values.Add(new FormFieldItem(radio.Attributes["name"].Value, radio.Attributes["value"].Value, radio.ParentNode.InnerText.Trim().Trim(':')));
if (radio.Attributes["checked"] != null)
{
dud.Value = values.Last();
}
}
if (dud.Value == null && values.Count > 0)
{
dud.Value = values.Last();
}
this.PostingFields.Children.Add(dud);
}
var text = (from t in p.Descendants("input").Where(x => x.Attributes["type"] == null) select t).FirstOrDefault();
if (text != null)
{
WatermarkTextBox tb = new WatermarkTextBox();
tb.WatermarkText = "Compensation Details";
tb.Tag = text.Attributes["name"].Value;
tb.Margin = new Thickness(10, 0, 10, 10);
tb.Text = text.Attributes["value"].Value;
this.PostingFields.Children.Add(tb);
}
}
}
private void ParseEditPostMap(HtmlNode formNode)
{
var map = (from div in formNode.Descendants("div").Where(x => x.Id == "map") select div).FirstOrDefault();
if (map != null && (from input in map.Descendants("input") select input).Any())
{
PostMapControl mapControl = new PostMapControl();
this.PostingFields.Children.Add(mapControl);
}
}
private void ParseEditPerms(HtmlNode formNode)
{
var checkboxes = (from perms in formNode.Descendants("div").Where(x => x.Id == "perms")
from cb in perms.Descendants("input").Where(x => x.Attributes["type"] != null && x.Attributes["type"].Value == "checkbox")
select cb);
foreach (var cb in checkboxes)
{
// This is handled by the map control.
if (cb.Id == "wantamap")
continue;
ToggleSwitch ts = new ToggleSwitch();
ts.Header = cb.ParentNode.InnerText.Trim();
ts.HeaderTemplate = this.Resources["ToggleSwitchHeaderTemplate"] as DataTemplate;
ts.Tag = cb.Attributes["name"].Value;
ts.Margin = new Thickness(10, 5, 10, 0);
ts.IsOn = cb.Attributes["checked"] != null;
this.PostingFields.Children.Add(ts);
}
}
private TextBlock GetPostingFieldLabel(string label)
{
TextBlock tb = new TextBlock();
tb.Margin = new Thickness(10, 10, 10, 5);
tb.Text = label;
tb.FontFamily = new FontFamily("Segoe UI Light");
tb.FontWeight = Windows.UI.Text.FontWeights.Light;
tb.FontSize = 20;
return tb;
}
private void SetTitle(HtmlDocument doc)
{
try
{
var contents = (from c in doc.DocumentNode.Descendants("section").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "contents") select c).FirstOrDefault();
if (contents != null)
{
var aside = (from a in contents.Descendants("aside") select a).FirstOrDefault();
if (aside != null)
aside.Remove();
this.PanelTitle.Text = Utilities.HtmlToText(contents.InnerText).Replace("\n", string.Empty).Trim();
}
else
{
this.PanelTitle.Text = "Create Post";
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
private async Task FinalizeSetPostState(CreatePostState step)
{
this._state = step;
PickOneState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
JobsCategoryState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
MixState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
EditState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
EditImageState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
PreviewState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
ApprovalState.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
switch (this._state)
{
case CreatePostState.PickOne:
PickOneState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case CreatePostState.JobsCategory:
JobsCategoryState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case CreatePostState.Mix:
MixState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case CreatePostState.Edit:
EditState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case CreatePostState.EditImages:
EditImageState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case CreatePostState.Preview:
PreviewState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case CreatePostState.Approval:
// Increment the number of in app posts we have made.
Settings.Instance.InAppPostCount++;
ContinueButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
BackButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
ApprovalState.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
default:
await Logger.AssertNotReached("Unknown step");
break;
}
this.LoadingProgress.Visibility = Visibility.Visible;
}
#endregion
#region Navigation
private async void ContinueButton_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
switch (this._state)
{
case CreatePostState.PickOne:
await this.ContinuePickOne(this.PickOneGrid.SelectedItem as PickItemVM);
break;
case CreatePostState.JobsCategory:
await this.ContinueJobCategory();
break;
case CreatePostState.Mix:
await this.ContinueMix();
break;
case CreatePostState.Edit:
await this.ContinueEditPost();
break;
case CreatePostState.Preview:
await this.ContinuePreview();
break;
case CreatePostState.EditImages:
await this.ContinueEditImages();
break;
default:
await new MessageDialog("NYI").ShowAsync();
break;
}
}
private async void BackButton_Tapped(object sender, TappedRoutedEventArgs e)
{
if (this._backHistory.Count == 0)
{
await Logger.AssertNotReached("Should have more than one in our history. The last one represents current page.");
}
else
{
this.ToggleNavigationButtons(false);
// The way this works is a little weird. If you pop the queue, the URL returned is actually the current URL. The second
// one would actual reference the page you came from. Therefore, if we want to go back, we need to pop twice.
this.LoadingProgress.Visibility = Visibility.Visible;
HttpResponseMessage response = null;
try
{
Uri url = this._backHistory.Peek();
response = await this._context.Client.GetAsync(url);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
if (response == null || !response.IsSuccessStatusCode)
{
await new MessageDialog("We received a bad response from Craigslist.", "Craigslist 8X").ShowAsync();
this.LoadingProgress.Visibility = Visibility.Collapsed;
return;
}
else
{
this._backHistory.Pop();
await this.ParseResponse(response, true);
}
}
}
private async void PickOneItem_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
await this.ContinuePickOne((sender as FrameworkElement).DataContext as PickItemVM);
}
private async Task ContinuePickOne(PickItemVM vm)
{
if (vm != null)
{
this.ToggleNavigationButtons(false);
HttpContent content = new StringContent(string.Format("{0}={1}{2}",
Uri.EscapeDataString(vm.Name),
Uri.EscapeDataString(vm.Value),
this.GetHiddenFields()
));
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
await this.IssueRequest(content);
}
else
{
await new MessageDialog("Select an item from the list to continue.", "Craigslist 8X").ShowAsync();
}
}
private async Task ContinueMix()
{
if (LeftMixGrid.SelectedIndex >= 0 && RightMixGrid.SelectedIndex >= 0
|| LeftMixGrid.SelectedIndex == -1 && RightMixGrid.SelectedIndex == -1)
{
this.ToggleNavigationButtons(false);
HttpContent content = null;
if (LeftMixGrid.SelectedIndex >= 0)
{
content = new StringContent(string.Format("{0}={1}&{2}={3}{4}",
Uri.EscapeDataString(((PickItemVM)LeftMixGrid.SelectedItem).Name),
Uri.EscapeDataString(((PickItemVM)LeftMixGrid.SelectedItem).Value),
Uri.EscapeDataString(((PickItemVM)RightMixGrid.SelectedItem).Name),
Uri.EscapeDataString(((PickItemVM)RightMixGrid.SelectedItem).Value),
this.GetHiddenFields()
));
}
else
{
content = new StringContent(this.GetHiddenFields().Substring(1));
}
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content);
}
else
{
await new MessageDialog("Select an item from each list or leave both lists blank to continue.", "Craigslist 8X").ShowAsync();
}
}
private async Task ContinueJobCategory()
{
if (JobsCategoryGrid.SelectedItems.Count > 0)
{
this.ToggleNavigationButtons(false);
StringBuilder postData = new StringBuilder();
foreach (var item in JobsCategoryGrid.SelectedItems)
{
PickItemVM vm = item as PickItemVM;
postData.Append(string.Format("{0}={1}&", Uri.EscapeDataString(vm.Name), Uri.EscapeDataString(vm.Value)));
}
postData.Append(this.GetHiddenFields().Substring(1));
HttpContent content = new StringContent(postData.ToString());
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content);
}
else
{
await new MessageDialog("Select one or more categories from the list to continue.", "Craigslist 8X").ShowAsync();
}
}
private async Task ContinuePreview()
{
this.ToggleNavigationButtons(false);
HttpContent content = new StringContent(this.GetHiddenFields().Substring(1));
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content);
}
private async Task ContinueEditImages()
{
this.ToggleNavigationButtons(false);
string hidden = this.GetHiddenFields();
if (!string.IsNullOrEmpty(hidden))
{
hidden = hidden.TrimStart('&');
}
HttpContent content = new StringContent(hidden);
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content);
}
private async Task ContinueEditPost()
{
var email = this.PostingFields.FindName("FromEMail") as WatermarkTextBox;
if (string.IsNullOrWhiteSpace(this.PostingTitleText.Text)
|| string.IsNullOrWhiteSpace(this.DescriptionText.Text)
|| (email != null && !email.Text.Contains("@")))
{
await new MessageDialog("Please fill out all required field before continuing.", "Craigslist 8X").ShowAsync();
return;
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("{0}={1}&{2}={3}",
Uri.EscapeDataString(PostingTitleText.Tag.ToString()),
Uri.EscapeDataString(PostingTitleText.Text),
Uri.EscapeDataString(DescriptionText.Tag.ToString()),
Uri.EscapeDataString(DescriptionText.Text)
));
foreach (var child in this.PostingFields.Children)
{
if (child is FrameworkElement)
{
FrameworkElement el = child as FrameworkElement;
if (el.Tag != null)
{
if (el.Tag is EventDateFields)
{
EventDateFields edf = el.Tag as EventDateFields;
SfDatePicker dp = el as SfDatePicker;
sb.Append(string.Format("&{0}={1}&{2}={3}&{4}={5}",
Uri.EscapeDataString(edf.Year),
Uri.EscapeDataString(((DateTime)dp.Value).Year.ToString()),
Uri.EscapeDataString(edf.Month),
Uri.EscapeDataString(((DateTime)dp.Value).Month.ToString()),
Uri.EscapeDataString(edf.Day),
Uri.EscapeDataString(((DateTime)dp.Value).Day.ToString())
));
}
else if (el is TextBox)
{
sb.Append(string.Format("&{0}={1}",
Uri.EscapeDataString(el.Tag.ToString()),
Uri.EscapeDataString((el as TextBox).Text.Trim())
));
if (el.Name == "FromEMail")
{
sb.Append(string.Format("&{0}={1}",
Uri.EscapeDataString("ConfirmEMail"),
Uri.EscapeDataString((el as TextBox).Text.Trim())
));
}
}
else if (el is TextBlock)
{
sb.Append(string.Format("&{0}={1}",
Uri.EscapeDataString(el.Tag.ToString()),
Uri.EscapeDataString((el as TextBlock).Text)
));
if (el.Name == "FromEMail")
{
sb.Append(string.Format("&{0}={1}",
Uri.EscapeDataString("ConfirmEMail"),
Uri.EscapeDataString((el as TextBlock).Text.Trim())
));
}
}
else if (el is ToggleSwitch)
{
sb.Append(string.Format("&{0}={1}",
Uri.EscapeDataString(el.Tag.ToString()),
Uri.EscapeDataString((el as ToggleSwitch).IsOn ? "on" : string.Empty)
));
}
}
else if (el is PostMapControl)
{
sb.Append(((PostMapControl)el).GetPostData());
}
else if (el is SfDomainUpDown)
{
sb.Append(string.Format("&{0}={1}",
Uri.EscapeDataString(((el as SfDomainUpDown).Value as FormFieldItem).Name),
Uri.EscapeDataString(((el as SfDomainUpDown).Value as FormFieldItem).Value)
));
}
}
}
sb.Append(this.GetHiddenFields());
HttpContent content = new StringContent(sb.ToString());
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content);
}
}
private async Task IssueRequest(HttpContent content, bool addHistory = true)
{
this.LoadingProgress.Visibility = Visibility.Visible;
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
HttpResponseMessage response = null;
try
{
response = await this._context.Client.PostAsync(this._postLink, content);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
if (response == null || !response.IsSuccessStatusCode)
{
await new MessageDialog("We received a bad response from Craigslist.", "Craigslist 8X").ShowAsync();
this.LoadingProgress.Visibility = Visibility.Collapsed;
return;
}
else
{
if (addHistory)
this._backHistory.Push(new Uri(this._currentPage.ToString()));
await this.ParseResponse(response, false);
}
}
private void ToggleNavigationButtons(bool enable)
{
this.ContinueButton.IsEnabled = enable;
this.BackButton.IsEnabled = enable && this._backHistory.Count > 0;
}
#endregion
#region Methods
private async void Image_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
FrameworkElement el = sender as FrameworkElement;
if (el.DataContext is AddImageBoxVM)
{
AddImageBoxVM vm = el.DataContext as AddImageBoxVM;
PopupMenu menu = new PopupMenu();
menu.Commands.Add(new UICommand() { Label = "Camera", Id = 0 });
menu.Commands.Add(new UICommand() { Label = "Pick File", Id = 1 });
var result = await menu.ShowForSelectionAsync(WB.Craigslist8X.Common.Utilities.GetElementRect(el), Placement.Below);
if (result == null)
return;
else if ((int)result.Id == 0)
{
var dialog = new CameraCaptureUI();
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png;
var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
MultipartFormDataContent content = new MultipartFormDataContent(Guid.NewGuid().ToString());
foreach (var hidden in vm.HiddenFields)
{
content.Add(new StringContent(hidden.Value), hidden.Name);
}
content.Add(new StreamContent(await file.OpenStreamForReadAsync()), "file", string.Format("{0}.png", Guid.NewGuid()));
await this.IssueRequest(content, addHistory: false);
}
}
else if ((int)result.Id == 1)
{
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
var file = await picker.PickSingleFileAsync();
if (file != null)
{
MultipartFormDataContent content = new MultipartFormDataContent(Guid.NewGuid().ToString());
foreach (var hidden in vm.HiddenFields)
{
content.Add(new StringContent(hidden.Value), hidden.Name);
}
content.Add(new StreamContent(await file.OpenStreamForReadAsync()), "file", file.Name);
await this.IssueRequest(content, addHistory: false);
}
}
}
else if (el.DataContext is ImageBoxVM)
{
// Do nothing?
}
else
{
await Logger.AssertNotReached("Unknown image type");
}
}
private async void DeleteImage_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
FrameworkElement el = sender as FrameworkElement;
if (el.DataContext is ImageBoxVM)
{
ImageBoxVM vm = el.DataContext as ImageBoxVM;
string data = string.Empty;
foreach (var h in vm.HiddenFields)
{
data += string.Format("&{0}={1}", Uri.EscapeDataString(h.Name), Uri.EscapeDataString(h.Value));
}
HttpContent content = new StringContent(data.Substring(1));
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
this._context.Client.DefaultRequestHeaders.ExpectContinue = false;
await this.IssueRequest(content, addHistory: false);
}
else
{
await Logger.AssertNotReached("Unknown image type");
}
}
private void JobsCategoryGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
double total = 0;
foreach (var item in JobsCategoryGrid.SelectedItems)
{
PickItemVM vm = item as PickItemVM;
HtmlNode node = vm.Node;
double cost = 0;
if (double.TryParse(node.Attributes["class"].Value, out cost))
{
total += cost;
}
}
TotalCost.Text = string.Format("{0:C}", total);
}
private async void OpenInBrowserButton_Tapped(object sender, TappedRoutedEventArgs e)
{
if (this._currentPage == null)
return;
await Launcher.LaunchUriAsync(this._currentPage);
}
private string GetHiddenFields()
{
string hiddens = string.Empty;
if (this._hiddenFields != null)
{
foreach (var h in this._hiddenFields)
{
hiddens += string.Format("&{0}={1}", Uri.EscapeDataString(h.Name), Uri.EscapeDataString(h.Value));
}
}
return hiddens;
}
#endregion
#region Fields
CreatePostContext _context;
CreatePostState _state;
UIElement _parent;
List<FormHiddenField> _hiddenFields;
Stack<Uri> _backHistory;
Uri _postLink;
Uri _currentPage;
#endregion
}
enum CreatePostState
{
PickOne,
JobsCategory,
Mix,
Edit,
EditImages,
Preview,
Approval,
}
public class CreatePostContext
{
public PasswordCredential Account
{
get;
set;
}
public CraigCity City
{
get;
set;
}
public Uri Url
{
get;
set;
}
public HttpClientHandler Handler
{
get;
set;
}
public HttpClient Client
{
get;
set;
}
}
public class PostParseException : Exception
{
public PostParseException(string message)
: base(message)
{
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/ExploreCategoriesVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.CraigslistApi;
namespace WB.Craigslist8X.ViewModel
{
public class ExploreCategoriesVM : BindableBase
{
public ExploreCategoriesVM(Category root)
{
this.Root = root;
IEnumerable<Category> categories;
if (root == null)
{
// Top level category
// Do we need to hide personals?
if (Settings.Instance.PersonalsUnlocked)
categories = CategoryManager.Instance.Categories.GroupBy(x => x.Root).Select(x => x.First());
else
categories = CategoryManager.Instance.Categories.GroupBy(x => x.Root).Select(x => x.First()).Where(x => x.Root != "personals");
}
else
{
categories = CategoryManager.Instance.Categories.Where(x => x.Root == root.Root);
}
this.Categories = new ObservableCollection<CategoryVM>(
from x in categories select new CategoryVM(x, root == null ? CategoryVM.DisplayField.Root : CategoryVM.DisplayField.Name)
);
CityManager.Instance.PropertyChanged += Instance_PropertyChanged;
}
void Instance_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "SearchCities")
{
this.OnPropertyChanged("Title");
}
}
#region Properties
public ObservableCollection<CategoryVM> Categories
{
get
{
return this._categories;
}
set
{
this.SetProperty(ref this._categories, value);
}
}
public string Title
{
get
{
if (this.Root == null)
{
return string.Format(BrowseTitleFormat, Utility.GetSearchCityLabel());
}
else
{
return string.Format(BrowseTitleFormat, this.Root.Root);
}
}
}
public Category Root
{
get;
set;
}
#endregion
#region Fields
ObservableCollection<CategoryVM> _categories;
#endregion
#region Constants
const string BrowseTitleFormat = "Browse {0}";
#endregion
}
public class CategoryVM : BindableBase
{
public enum DisplayField
{
Root,
Name,
}
public CategoryVM(Category cat, DisplayField field)
{
this.Category = cat;
this._field = field;
}
public string Display
{
get
{
switch (this._field)
{
case DisplayField.Name:
return this.Category.Name;
case DisplayField.Root:
return this.Category.Root;
default:
return string.Empty;
}
}
}
public Category Category
{
get;
private set;
}
public bool Selected
{
get
{
return this._selected;
}
set
{
this.SetProperty(ref this._selected, value);
}
}
DisplayField _field;
bool _selected;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Flyouts/Filters/NumericFilter.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WB.CraigslistApi;
namespace WB.Craigslist8X.View
{
public sealed partial class NumericFilter : UserControl, INotifyPropertyChanged
{
public NumericFilter()
{
this.InitializeComponent();
this.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs("Filter"));
}
public QueryFilterNumeric Filter
{
get
{
return this._filter;
}
set
{
this._filter = value;
this.OnPropertyChanged("Filter");
}
}
QueryFilterNumeric _filter;
private void FilterValue_KeyDown(object sender, KeyRoutedEventArgs e)
{
switch (e.Key)
{
case Windows.System.VirtualKey.Menu:
case Windows.System.VirtualKey.F4:
case Windows.System.VirtualKey.Number0:
case Windows.System.VirtualKey.Number1:
case Windows.System.VirtualKey.Number2:
case Windows.System.VirtualKey.Number3:
case Windows.System.VirtualKey.Number4:
case Windows.System.VirtualKey.Number5:
case Windows.System.VirtualKey.Number6:
case Windows.System.VirtualKey.Number7:
case Windows.System.VirtualKey.Number8:
case Windows.System.VirtualKey.Number9:
case Windows.System.VirtualKey.NumberPad0:
case Windows.System.VirtualKey.NumberPad1:
case Windows.System.VirtualKey.NumberPad2:
case Windows.System.VirtualKey.NumberPad3:
case Windows.System.VirtualKey.NumberPad4:
case Windows.System.VirtualKey.NumberPad5:
case Windows.System.VirtualKey.NumberPad6:
case Windows.System.VirtualKey.NumberPad7:
case Windows.System.VirtualKey.NumberPad8:
case Windows.System.VirtualKey.NumberPad9:
break;
case Windows.System.VirtualKey.Enter:
DummyButton.Focus(Windows.UI.Xaml.FocusState.Pointer);
e.Handled = true;
break;
default:
if (sender as TextBox != null && (e.Key == Windows.System.VirtualKey.Decimal || e.Key == (Windows.System.VirtualKey)190))
{
e.Handled = (sender as TextBox).Text.Contains(".");
}
else
{
e.Handled = true;
}
break;
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Common/Extensions.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq.Expressions;
using Windows.UI.Xaml.Data;
namespace WB.Craigslist8X.Common
{
/// <summary>
/// Generic extension methods
/// </summary>
public static class ExtensionMethods
{
public static void Copy<T>(this ObservableCollection<T> target, IEnumerable<T> source)
{
if (target == null)
{
target = new ObservableCollection<T>(source);
}
else
{
target.Clear();
foreach (T item in source)
{
target.Add(item);
}
}
}
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Flyouts/Filters/FiltersContainer.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WB.CraigslistApi;
namespace WB.Craigslist8X.View
{
public sealed partial class FiltersContainer : UserControl
{
public FiltersContainer()
{
this.InitializeComponent();
}
public void AttachContext(Query query)
{
if (query == null)
throw new ArgumentNullException("query");
Query q = query.Clone();
if (q.Filters == null)
this.Filters = WB.CraigslistApi.QueryFilter.GetFilters(q.Category);
else
this.Filters = q.Filters;
foreach (var filter in this.Filters)
{
if (filter is QueryFilterBoolean)
{
this.FilterPanel.Children.Add(new BooleanFilter() { Filter = filter as QueryFilterBoolean });
}
else if (filter is QueryFilterNumeric)
{
this.FilterPanel.Children.Add(new NumericFilter() { Filter = filter as QueryFilterNumeric });
}
else if (filter is QueryFilterChooseOne)
{
this.FilterPanel.Children.Add(new ChooseOneFilter() { Filter = filter as QueryFilterChooseOne });
}
}
this.SearchQuery = q.Text;
this.TitlesOnly = q.Type == Query.QueryType.TitleOnly;
this.HasPictures = q.HasImage;
this.DataContext = this;
}
public string SearchQuery
{
get;
set;
}
public bool TitlesOnly
{
get;
set;
}
public bool HasPictures
{
get;
set;
}
public bool HasFilters
{
get
{
return Filters != null && Filters.Count > 0;
}
}
public QueryFilters Filters
{
get;
set;
}
public Query Original
{
get;
set;
}
private void FilterContainer_Tapped(object sender, TappedRoutedEventArgs e)
{
DummyButton.Focus(Windows.UI.Xaml.FocusState.Pointer);
}
private void SearchBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
e.Handled = true;
DummyButton.Focus(Windows.UI.Xaml.FocusState.Pointer);
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/MainMenuOptionsPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Callisto.Controls;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class MainMenuOptionsPanel : UserControl, IPanel, IWebViewHost
{
public MainMenuOptionsPanel()
{
this.InitializeComponent();
this.buttons = new List<Button>()
{
SearchMenuButton,
BrowseMenuButton,
RecentlySearchedMenuButton,
FavoritesMenuButton,
RecentlyViewedMenuButton,
CreatePostMenuButton,
SavedSearchesMenuButton,
UpgradeMenuButton,
AccountManagementMenuButton,
};
this._vm = new MainOptionsVM();
this.DataContext = this._vm;
}
public async Task AttachContext(object context, IPanel parent)
{
await Logger.AssertNull(parent, "MainMenuOptionsPanel should not have a parent");
}
public void ToggleWebView(bool visible)
{
this._vm.HideWebView = !visible;
}
#region Commands
private void SearchMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().Show();
}
private async void BrowseMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
await MainPage.Instance.ExecuteBrowse(this, null);
}
private async void RecentlySearchedMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.SetSelection(RecentlySearchedMenuButton);
await MainPage.Instance.ExecuteRecentlySearched(this);
}
private async void SavedSearchesMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.SetSelection(SavedSearchesMenuButton);
await MainPage.Instance.ExecuteSavedSearches(this, null);
}
private async void FavoritesMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.SetSelection(FavoritesMenuButton);
await MainPage.Instance.ExecuteFavorites(this);
}
private async void RecentlyViewedMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.SetSelection(RecentlyViewedMenuButton);
await MainPage.Instance.ExecuteRecentlyViewed(this);
}
private async void CreatePostMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
if (!CityManager.Instance.SearchCitiesDefined)
{
MessageDialog dlg = new MessageDialog("Please set your cities and try again.", "Craigslist 8X");
await dlg.ShowAsync();
SettingsUI.ShowSearchSettings();
return;
}
this.SetSelection(CreatePostMenuButton);
await MainPage.Instance.ExecuteChooseAccount(this, ChooseAccountPurpose.CreatePost);
}
private async void AccountManagementMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.SetSelection(AccountManagementMenuButton);
await MainPage.Instance.ExecuteChooseAccount(this, ChooseAccountPurpose.AccountManagement);
}
private async void UpgradeMenuButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.SetSelection(UpgradeMenuButton);
await MainPage.Instance.ExecuteUpgrade(this);
}
public void SetPurchasedPro()
{
this._vm.ShowAds = false;
}
public void SetSelectionSearch()
{
this.SetSelection(this.SearchMenuButton);
}
public void SetSelectionBrowse()
{
this.SetSelection(this.BrowseMenuButton);
}
public void SetSelectionCreatePost()
{
this.SetSelection(this.CreatePostMenuButton);
}
private void SetSelection(Button btn)
{
foreach (Button b in this.buttons)
{
b.Background = new SolidColorBrush(Windows.UI.Colors.Transparent);
}
btn.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xDD, 0xDD, 0xDD));
}
MainOptionsVM _vm;
List<Button> buttons;
#endregion
private void SearchSettings_Tapped(object sender, TappedRoutedEventArgs e)
{
SettingsUI.ShowSearchSettings();
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/ChoosePostCityPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Security.Credentials;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.View;
namespace WB.Craigslist8X.View
{
public sealed partial class ChoosePostCityPanel : UserControl, IPanel
{
public ChoosePostCityPanel()
{
this.InitializeComponent();
}
public Task AttachContext(object context, IPanel parent)
{
this._account = context as PasswordCredential;
if (CityManager.Instance.SearchCitiesDefined)
{
IEnumerable<CraigCity> cities = (from x in CityManager.Instance.SearchCities select CityManager.Instance.GetCityByUri(x.Location));
CityItemsList.ItemsSource = (from x in cities select x).Distinct();
}
return null;
}
private void ListView_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(this.CityItemsList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
private async void CreatePostCity_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as CraigCity != null)
{
CreatePostContext context = new CreatePostContext();
context.Account = this._account;
context.City = (sender as FrameworkElement).DataContext as CraigCity;
await MainPage.Instance.ExecuteCreatePost(this, context);
}
}
PasswordCredential _account;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Common/Utilities.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
namespace WB.Craigslist8X.Common
{
public static class Utilities
{
public static async Task<MemoryStream> GetImageStream(Uri uri)
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
return new MemoryStream(await response.Content.ReadAsByteArrayAsync());
}
else
{
return null;
}
}
}
public static T GetVisualChild<T>(DependencyObject referenceVisual) where T : DependencyObject
{
DependencyObject child = null;
for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceVisual); i++)
{
child = VisualTreeHelper.GetChild(referenceVisual, i) as DependencyObject;
if (child != null && (child.GetType() == typeof(T)))
{
break;
}
else if (child != null)
{
child = GetVisualChild<T>(child);
if (child != null && (child.GetType() == typeof(T)))
{
break;
}
}
}
return child as T;
}
public static void ExecuteNotification(string title, string message)
{
var template = ToastTemplateType.ToastText02;
var content = ToastNotificationManager.GetTemplateContent(template);
content.SelectSingleNode("/toast/visual/binding/text[@id='1']").InnerText = title;
content.SelectSingleNode("/toast/visual/binding/text[@id='2']").InnerText = message;
ToastNotification toast = new ToastNotification(content);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
public static Rect GetElementRect(FrameworkElement element)
{
GeneralTransform buttonTransform = element.TransformToVisual(null);
Point point = buttonTransform.TransformPoint(new Point());
return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
}
public static async Task<string> LoadFileAsync(this StorageFile file)
{
using (var stream = await file.OpenAsync(FileAccessMode.Read))
using (var readStream = stream.GetInputStreamAt(0))
using (DataReader reader = new DataReader(readStream))
{
uint bytesLoaded = await reader.LoadAsync((uint)stream.Size);
return reader.ReadString(bytesLoaded);
}
}
public static async Task SaveFileAsync(this StorageFile file, string content)
{
using (var raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
using (var outStream = raStream.GetOutputStreamAt(0))
using (DataWriter writer = new DataWriter(outStream))
{
writer.WriteString(content);
await writer.StoreAsync();
await outStream.FlushAsync();
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/RecentlySearchedVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class RecentlySearchedVM
{
public RecentlySearchedVM()
{
this.RecentQueries = new ObservableCollection<RecentlySearchedQueryVM>((from x in RecentlySearched.Instance.Queries select new RecentlySearchedQueryVM(x)));
}
public ObservableCollection<RecentlySearchedQueryVM> RecentQueries
{
get;
set;
}
}
public class RecentlySearchedQueryVM
{
public RecentlySearchedQueryVM(Query q)
{
this.Query = q;
}
public string Label
{
get
{
if (string.IsNullOrEmpty(this.Query.Text))
return string.Format("Browse {0}", this.Query.Category.Name);
else
return string.Format("{0} in {1}", this.Query.Text, this.Query.Category.Name);
}
}
public Query Query
{
get;
set;
}
}
}
<file_sep>/Win8/WB/WB.SDK/Controls/PanelView.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using WB.SDK;
using WB.SDK.Logging;
namespace WB.SDK.Controls
{
public sealed class PanelView : Panel
{
public PanelView()
{
this._snapState.SnapOnRefresh = -1;
this.ManipulationMode = ManipulationModes.All;
this.ManipulationStarted += PanelView_ManipulationStarted;
this.ManipulationCompleted += PanelView_ManipulationCompleted;
this.ManipulationDelta += PanelView_ManipulationDelta;
this.PointerWheelChanged += PanelView_PointerWheelChanged;
}
#region Control Handlers
protected override Size MeasureOverride(Size availableSize)
{
Size size = new Size(Double.PositiveInfinity, availableSize.Height);
foreach (UIElement child in Children)
{
child.Measure(size);
}
return availableSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
if (this.Children == null || this.Children.Count == 0)
return finalSize;
if (this._snapState.SnapOnRefresh != -1)
{
this.SnapToPanel(this._snapState.SnapOnRefresh);
this._snapState.SnapOnRefresh = -1;
}
// Draw the panels
this.ArrangePanels(finalSize);
if (this.ItemsArranged != null)
{
this.ItemsArranged(this, this.Children);
}
//Logger.LogMessage("PanelView", "Snapped Panel: {0}. Direction: {1}", this._snapState.Panel, this._snapState.Direction);
//Logger.LogMessage("PanelView", "Calculated Render Origin: {0}, X Displacement: {1}", this._snapState.RenderOffset, this._snapState.DisplacementX);
return finalSize;
}
public void PanelView_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
e.Handled = true;
this._snapState.Manipulated = true;
this._snapState.InertialReleasedPanel = -1;
if (this.ItemsMoved != null)
this.ItemsMoved(this, PanelMove.Started);
}
public void PanelView_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
if (this._snapState.Manipulated)
{
e.Handled = true;
this._snapState.DisplacementX += e.Delta.Translation.X;
if (this._snapState.DisplacementX != 0)
{
this.InvalidateArrange();
}
if (e.IsInertial)
{
if (this._snapState.InertialReleasedPanel < 0 && Math.Abs(e.Velocities.Linear.X) >= 0.5)
{
this._snapState.IntertialDirection = e.Velocities.Linear.X > 0 ? Direction.Left : Direction.Right;
this._snapState.InertialReleasedPanel = this.GetPanelAtOffset(this._snapState.RenderOffset);
}
double leftMax = MaxEdgePull * -1;
double rightMax = this._snapState.PanelWidthSum - this.DesiredSize.Width + MaxEdgePull + (Math.Min(0, this._snapState.PanelWidthSum - this.DesiredSize.Width) * -1);
// If the movement is intertial and we have already reached the max edge we support, we should snap to the appropriate panel.
if (this._snapState.RenderOffset <= leftMax || this._snapState.RenderOffset >= rightMax)
{
e.Complete();
}
}
}
}
public void PanelView_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
if (this._snapState.Manipulated)
{
e.Handled = true;
if (this._snapState.InertialReleasedPanel == this._snapState.Panel && this._snapState.InertialReleasedPanel == this.GetPanelAtOffset(this._snapState.RenderOffset))
{
// We had inertia, but not enough to move to the next/previous panel
if (this._snapState.IntertialDirection == Direction.Left)
{
if (this._snapState.InertialReleasedPanel > 0)
{
this.SnapToPanel(this._snapState.InertialReleasedPanel - 1);
return;
}
}
else if (this._snapState.IntertialDirection == Direction.Right)
{
if (this._snapState.InertialReleasedPanel < this.Children.Count - 1)
{
this.SnapToPanel(this._snapState.InertialReleasedPanel + 1);
return;
}
}
}
this.SnapToOffset(this._snapState.RenderOffset);
}
}
public void PanelView_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
int delta = e.GetCurrentPoint(this).Properties.MouseWheelDelta;
if (delta != 0)
{
e.Handled = true;
if (this.ItemsMoved != null)
this.ItemsMoved(this, PanelMove.Started);
this._snapState.Manipulated = true;
this._snapState.DisplacementX += delta;
if (this._snapState.DisplacementX != 0)
{
this.InvalidateArrange();
}
if (this._wheelTimer != null)
this._wheelTimer.Cancel();
this._wheelTimer = ThreadPoolTimer.CreateTimer(
(source) =>
{
var x = CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
this.SnapToOffset(this._snapState.RenderOffset);
});
}, TimeSpan.FromMilliseconds(250));
}
}
#endregion
#region Public Methods / Events
public event EventHandler<IEnumerable<UIElement>> ItemsArranged;
public event EventHandler<PanelMove> ItemsMoved;
/// <summary>
/// Return the index of panel
/// </summary>
/// <param name="panel">Panel</param>
/// <returns></returns>
public int GetPanelIndex(UIElement panel)
{
for (int i = 0; i < this.Children.Count; ++i)
{
if (panel == this.Children[i])
{
return i;
}
}
return -1;
}
/// <summary>
/// Add a new panel to the PanelView control
/// </summary>
/// <param name="panel">Panel to be added</param>
public async Task AddPanel(UIElement panel)
{
this.Children.Add(panel);
this._snapState.SnapOnRefresh = this.Children.Count - 1;
this.InvalidateMeasure();
this.InvalidateArrange();
await this.AnimateEnter(panel);
}
/// <summary>
/// Remove panel
/// </summary>
/// <param name="panel">Panel to remove</param>
/// <param name="recursive">Include all panels to the right</param>
public void RemovePanel(UIElement panel, bool recursive)
{
this.RemovePanel(this.Children.IndexOf(panel), recursive);
}
/// <summary>
/// Remove panels starting from the given index.
/// </summary>
/// <param name="panel">Panel index to remove</param>
/// <param name="recursive">Include all panels to the right</param>
public void RemovePanel(int panel, bool recursive)
{
if (panel >= this.Children.Count)
return;
int count = this.Children.Count - panel;
for (int i = 0; i < (recursive ? count : 1); ++i)
{
this.Children.RemoveAt(panel);
}
}
/// <summary>
/// Snap to panel or closest allowed while keeping request panel in view.
/// </summary>
/// <param name="panel">Request panel to snap to</param>
public void SnapToPanel(UIElement panel)
{
for (int i = 0; i < this.Children.Count; ++i)
{
if (panel == this.Children[i])
{
this.SnapToPanel(i);
return;
}
}
}
/// <summary>
/// Snap to panel or closest allowed while keeping request panel in view.
/// </summary>
/// <param name="panel">Request panel to snap to</param>
public void SnapToPanel(int panel)
{
if (panel >= this.Children.Count)
throw new IndexOutOfRangeException("Panel index.");
if (panel + 1 == this.Children.Count)
{
this.SnapToOffset(int.MaxValue);
}
else
{
double widthTraversed = 0;
for (int i = 0; i < panel; ++i)
{
widthTraversed += this.Children[i].DesiredSize.Width;
}
this.SnapToOffset(widthTraversed);
}
}
public bool PanelOutOfView(UIElement panel)
{
double traversedWidth = 0;
for (int i = 0; i < this.Children.Count; ++i)
{
if (this.Children[i] == panel)
{
if (traversedWidth + panel.DesiredSize.Width <= this._snapState.RenderOffset
|| traversedWidth > this._snapState.RenderOffset + this.DesiredSize.Width)
{
return true;
}
else
{
return false;
}
}
traversedWidth += this.Children[i].DesiredSize.Width;
}
return false;
}
#endregion
#region Private Methods
/// <summary>
/// Calculate the pixel offset from left to right we should start drawing from. The result is a
/// function of the snapped panel and user manipulation (displacement).
/// </summary>
void CalculateRenderOffset()
{
double widthTraversedCalc = 0;
for (int i = 0; i < this.Children.Count; ++i)
{
if (this._snapState.Panel == i)
{
if (this._snapState.Direction == Direction.Left)
{
this._snapState.RenderOffset = widthTraversedCalc + (this._snapState.DisplacementX * -1);
break;
}
else if (this._snapState.Direction == Direction.Right)
{
this._snapState.RenderOffset = widthTraversedCalc + this.Children[i].DesiredSize.Width - this.DesiredSize.Width + (this._snapState.DisplacementX * -1);
break;
}
}
else
{
widthTraversedCalc += this.Children[i].DesiredSize.Width;
}
}
// Pull to the right
this._snapState.RenderOffset = Math.Max(this._snapState.RenderOffset, MaxEdgePull * -1);
// Pull to the left
this._snapState.RenderOffset = Math.Min(this._snapState.RenderOffset,
this._snapState.PanelWidthSum - this.DesiredSize.Width + MaxEdgePull + (Math.Min(0, this._snapState.PanelWidthSum - this.DesiredSize.Width) * -1));
}
/// <summary>
/// Arrange panels for drawing
/// </summary>
/// <param name="finalSize">Size of PanelView</param>
void ArrangePanels(Size finalSize)
{
Rect finalRect = new Rect(0, 0, finalSize.Width, finalSize.Height);
double widthTraversedExec = 0;
if (this._snapState.Direction == Direction.Left || this._snapState.Manipulated)
{
// We need a render origin if we are using Left to Right drawing
this.CalculateRenderOffset();
for (int i = 0; i < this.Children.Count; ++i)
{
var child = this.Children[i];
finalRect.X = widthTraversedExec - this._snapState.RenderOffset;
finalRect.Width = child.DesiredSize.Width;
child.Arrange(finalRect);
widthTraversedExec += child.DesiredSize.Width;
}
}
else if (this._snapState.Direction == Direction.Right)
{
for (int i = this.Children.Count - 1; i >= 0; --i)
{
var child = this.Children[i];
finalRect.X = this.DesiredSize.Width - widthTraversedExec - child.DesiredSize.Width;
finalRect.Width = child.DesiredSize.Width;
child.Arrange(finalRect);
widthTraversedExec += child.DesiredSize.Width;
}
}
}
/// <summary>
/// Based on the pixel offset we are currently at, we calculate which panel we should snap to.
/// We take into account user displacement, screen width and panel edges.
/// </summary>
/// <param name="offset">Left to right offset panels are being drawn</param>
void CacheSnappedPanel(double offset)
{
this.CachePanelWidthSum();
if (this._snapState.PanelWidthSum - offset <= this.DesiredSize.Width && this._snapState.PanelWidthSum > this.DesiredSize.Width)
{
this._snapState.Panel = this.Children.Count - 1;
this._snapState.Direction = Direction.Right;
return;
}
this._snapState.Direction = Direction.Left;
double widthTraversed = 0;
for (int i = 0; i < this.Children.Count; ++i)
{
UIElement child = this.Children[i];
if (this._snapState.PanelWidthSum - widthTraversed < this.DesiredSize.Width)
{
this._snapState.Panel = i;
return;
}
else if (widthTraversed + child.DesiredSize.Width >= offset)
{
if (i + 1 == this.Children.Count)
{
// We are the last panel we can snap to. Pick it.
this._snapState.Panel = i;
}
else
{
// Here we decide if we should snap to the left most panel in view, or snap to next panel if
// we are very close to the edge. We need to account that if we snap right one panel it is possible
// to get into a situation where there is a margin on the right side of the screen because we did
// not choose to snap to the right most panel using SnapDirection.Right
bool snapRight = (offset > widthTraversed + (child.DesiredSize.Width - Math.Min((child.DesiredSize.Width * (EdgeSnapToNextPercent)), EdgeSnapToNextPixel)));
// We think we should snap right because we are near the edge. Determine if that is the right move
// or if we should use SnapDirection.Right on the very last panel of the control.
if (snapRight && this._snapState.PanelWidthSum > this.DesiredSize.Width && this.CalculateRenderWidth(i + 1) < this.DesiredSize.Width)
{
this._snapState.Panel = this.Children.Count - 1;
this._snapState.Direction = Direction.Right;
}
else
{
this._snapState.Panel = i + (snapRight ? 1 : 0);
}
}
return;
}
else
{
widthTraversed += child.DesiredSize.Width;
}
}
}
/// <summary>
/// Cache the sum of the width of all child panels
/// </summary>
void CachePanelWidthSum()
{
this._snapState.PanelWidthSum = 0;
for (int i = 0; i < this.Children.Count; ++i)
{
this._snapState.PanelWidthSum += this.Children[i].DesiredSize.Width;
}
}
/// <summary>
/// Animate snap to offset.
/// </summary>
/// <param name="offset">Offset to snap to</param>
void SnapToOffset(double offset)
{
double origin = this._snapState.RenderOffset;
this.CacheSnappedPanel(offset);
if (this._snapState.Manipulated)
{
if (this.ItemsMoved != null)
this.ItemsMoved(this, PanelMove.Finished);
}
this._snapState.Manipulated = false;
this._snapState.DisplacementX = 0;
this.CalculateRenderOffset();
double displacement = this._snapState.RenderOffset - origin;
this.AnimateSnap(displacement);
this.InvalidateArrange();
}
int GetPanelAtOffset(double offset)
{
double widthTraversed = 0;
for (int i = 0; i < this.Children.Count; ++i)
{
widthTraversed += this.Children[0].DesiredSize.Width;
if (offset < widthTraversed)
return i;
}
return 0;
}
void AnimateSnap(double displacement)
{
if (displacement == 0)
return;
foreach (var child in this.Children)
{
if (child.RenderTransform as TranslateTransform == null)
child.RenderTransform = new TranslateTransform();
Storyboard storyboard = new Storyboard();
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = displacement;
doubleAnimation.To = 0.0;
doubleAnimation.EasingFunction = new CircleEase() { EasingMode = Windows.UI.Xaml.Media.Animation.EasingMode.EaseOut };
doubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(this.SnapAnimationMilliseconds));
storyboard.Children.Add(doubleAnimation);
Storyboard.SetTarget(doubleAnimation, child.RenderTransform);
Storyboard.SetTargetProperty(doubleAnimation, "X");
storyboard.Begin();
}
}
async Task AnimateEnter(UIElement panel)
{
if (panel.RenderTransform as TranslateTransform == null)
panel.RenderTransform = new TranslateTransform();
Storyboard storyboard = new Storyboard();
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = this.DesiredSize.Width;
doubleAnimation.To = 0.0;
doubleAnimation.EasingFunction = new CircleEase() { EasingMode = Windows.UI.Xaml.Media.Animation.EasingMode.EaseOut };
doubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(this.EnterAnimationMilliseconds));
storyboard.Children.Add(doubleAnimation);
Storyboard.SetTarget(doubleAnimation, panel.RenderTransform);
Storyboard.SetTargetProperty(doubleAnimation, "X");
await storyboard.BeginAsync();
}
async Task AnimateRemove(UIElement panel)
{
if (panel.RenderTransform as ScaleTransform == null)
panel.RenderTransform = new ScaleTransform();
Storyboard storyboard = new Storyboard();
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = 1;
doubleAnimation.To = 0.0;
doubleAnimation.EasingFunction = new CircleEase() { EasingMode = Windows.UI.Xaml.Media.Animation.EasingMode.EaseOut };
doubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(this.EnterAnimationMilliseconds));
storyboard.Children.Add(doubleAnimation);
Storyboard.SetTarget(doubleAnimation, panel.RenderTransform);
Storyboard.SetTargetProperty(doubleAnimation, "ScaleX");
await storyboard.BeginAsync();
}
double CalculateRenderWidth(int panel)
{
double width = 0;
for (int i = panel; i < this.Children.Count; ++i)
{
width += this.Children[i].DesiredSize.Width;
}
return width;
}
#endregion
#region Properties
public double EdgeSnapToNextPixel
{
get { return (double)GetValue(EdgeSnapToNextPixelProperty); }
set { SetValue(EdgeSnapToNextPixelProperty, value); }
}
public static readonly DependencyProperty EdgeSnapToNextPixelProperty =
DependencyProperty.Register("EdgeSnapToNextPixel", typeof(double), typeof(PanelView), new PropertyMetadata(100.0));
public double EdgeSnapToNextPercent
{
get { return (double)GetValue(EdgeSnapToNextPercentProperty); }
set { SetValue(EdgeSnapToNextPercentProperty, value); }
}
public static readonly DependencyProperty EdgeSnapToNextPercentProperty =
DependencyProperty.Register("EdgeSnapToNextPercent", typeof(double), typeof(PanelView), new PropertyMetadata(0.33));
public int SnapAnimationMilliseconds
{
get { return (int)GetValue(SnapAnimationMillisecondsProperty); }
set { SetValue(SnapAnimationMillisecondsProperty, value); }
}
public static readonly DependencyProperty SnapAnimationMillisecondsProperty =
DependencyProperty.Register("SnapAnimationMilliseconds", typeof(int), typeof(PanelView), new PropertyMetadata(300));
public int EnterAnimationMilliseconds
{
get { return (int)GetValue(EnterAnimationMillisecondsProperty); }
set { SetValue(EnterAnimationMillisecondsProperty, value); }
}
public static readonly DependencyProperty EnterAnimationMillisecondsProperty =
DependencyProperty.Register("EnterAnimationMilliseconds", typeof(int), typeof(PanelView), new PropertyMetadata(300));
public double MaxEdgePull
{
get { return (double)GetValue(MaxEdgePullProperty); }
set { SetValue(MaxEdgePullProperty, value); }
}
public static readonly DependencyProperty MaxEdgePullProperty =
DependencyProperty.Register("MaxEdgePull", typeof(double), typeof(PanelView), new PropertyMetadata(100.0));
#endregion
private PanelSnapState _snapState;
private ThreadPoolTimer _wheelTimer;
}
public enum PanelMove
{
Started,
Finished,
}
struct PanelSnapState
{
internal int Panel;
internal Direction Direction;
internal bool Manipulated;
internal double DisplacementX;
internal int InertialReleasedPanel;
internal Direction IntertialDirection;
internal double PanelWidthSum;
internal double RenderOffset;
internal int SnapOnRefresh;
}
enum Direction
{
Left,
Right,
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/FavoritePostsVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.Common;
namespace WB.Craigslist8X.ViewModel
{
class FavoritePostsVM : BindableBase
{
public FavoritePostsVM()
{
this.PostItems = new ObservableCollection<PostBase>();
foreach (Post p in FavoritePosts.Instance.Posts)
{
this.PostItems.Add(new PostVM(p));
}
}
public async Task InitAsync()
{
const int pageLoad = 5;
for (int i = 0; i < this._postItems.Count; i += pageLoad)
{
await Task.WhenAll(from item in this._postItems.ToList().GetRange(i, Math.Min(this._postItems.Count - i, pageLoad)) select ((PostVM)item).LoadDetailsAsync());
}
}
public ObservableCollection<PostBase> PostItems
{
get
{
return this._postItems;
}
set
{
this.SetProperty(ref this._postItems, value);
}
}
private ObservableCollection<PostBase> _postItems;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/QueryResultVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.ViewModel
{
public class QueryResultVM : BindableBase
{
#region Initialization
public QueryResultVM(SearchResultsVM srvm, QueryResult qr)
{
if (qr == null)
throw new ArgumentNullException("qr");
if (srvm == null)
throw new ArgumentNullException("srvm");
this._srvm = srvm;
this._qr = qr;
this._postItems = new ObservableCollection<PostBase>();
#pragma warning disable 4014
this.SyncResults();
#pragma warning restore 4014
}
#endregion
#region Methods
public async Task<bool> LoadMoreResults()
{
await Logger.Assert(!this._qr.DoneLoading, "We are already done loading. Why are we trying to load more?");
if (this._qr.DoneLoading)
return false;
await this._qr.LoadMoreAsync();
await this.SyncResults();
return true;
}
private async Task SyncResults()
{
// Before we start syncing we need to remove the last "Load more items" fake post.
if (this._postItems.Count > 0 && this._postItems[this._postItems.Count()-1].Type == PostBase.PostType.LoadMore)
{
this._postItems.Remove(this._postItems.Last());
}
List<PostVM> itemsAdded = new List<PostVM>();
if (this._postItems.Count < this._qr.Count)
{
for (int i = this._postItems.Count; i < this._qr.Posts.Count; ++i)
{
// Add the item to the serialized list.
PostVM vm = new PostVM(this, this._qr.Posts[i]);
itemsAdded.Add(vm);
this._postItems.Add(vm);
}
}
if (!this._qr.DoneLoading)
{
this._postItems.Add(new LoadMorePostsVM(this));
}
const int pageLoad = 20;
for (int i = 0; i < itemsAdded.Count; i += pageLoad)
{
await Task.WhenAll(from item in itemsAdded.GetRange(i, Math.Min(pageLoad, itemsAdded.Count - i)) select item.LoadDetailsAsync());
}
}
#endregion
#region Properties
public bool DoneLoading
{
get
{
return _qr.DoneLoading;
}
}
public ObservableCollection<PostBase> PostItems
{
get
{
return this._postItems;
}
set
{
this.SetProperty(ref this._postItems, value);
}
}
public SearchResultsVM SearchResults
{
get
{
return _srvm;
}
}
public QueryResult QueryResult
{
get
{
return _qr;
}
}
#endregion
#region Fields
ObservableCollection<PostBase> _postItems;
QueryResult _qr;
SearchResultsVM _srvm;
#endregion
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/CategoryManager.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;
using Windows.Storage;
using Windows.Storage.Streams;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.Model
{
internal class CategoryManager : BindableBase, IStorageBacked
{
#region Constructors
static CategoryManager()
{
_instanceLock = new object();
}
private CategoryManager()
{
this._fileLock = new AsyncLock();
}
#endregion
#region Singleton
public static CategoryManager Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new CategoryManager();
return _instance;
}
}
}
static CategoryManager _instance;
static object _instanceLock;
#endregion
#region IStorageBacked
public async Task<bool> LoadAsync()
{
StorageFile file = null;
try
{
file = await ApplicationData.Current.LocalFolder.GetFileAsync(CraigslistCategoriesFileName);
}
catch (System.IO.FileNotFoundException)
{
}
if (file == null)
{
file = await SDK.Utilities.GetPackagedFile("Resources", CraigslistCategoriesFileName);
}
if (file != null)
{
Logger.LogMessage("Categories", "Reading CraigslistCategories.csv");
try
{
string content = null;
using (await this._fileLock.LockAsync())
{
content = await FileIO.ReadTextAsync(file);
}
CategoryList data = new CategoryList();
foreach (var line in content.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
{
Category city = Category.Deserialize(line.Trim());
data.Add(city);
}
await Logger.Assert(data.GetCategories().Count() > 0, "No categories found in file!");
if (this.Categories == null)
this.Categories = new ObservableCollection<Category>(data.GetCategories());
else
this.Categories.Copy(data.GetCategories());
_cachedCategories = data;
if (SearchCategory == null)
{
// Set the default category
SearchCategory = (from x in _categories where x.Name.Equals(DefaultCategoryName, StringComparison.OrdinalIgnoreCase) select x).First();
}
return true;
}
catch (Exception ex)
{
Logger.LogMessage("Categories", "Failed to read CraigslistCategories.csv");
Logger.LogException(ex);
}
}
return false;
}
public async Task<bool> SaveAsync()
{
if (_cachedCategories == null)
{
await Logger.AssertNotReached("No cached categories.");
return false;
}
try
{
StringBuilder sb = new StringBuilder();
foreach (var city in _cachedCategories.GetCategories())
{
sb.AppendLine(Category.Serialize(city));
}
using (await this._fileLock.LockAsync())
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(CraigslistCategoriesFileName, CreationCollisionOption.ReplaceExisting);
await file.SaveFileAsync(sb.ToString());
}
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("CraigslistCategories", "Failed to save CraigslistCategories.csv");
Logger.LogException(ex);
}
return false;
}
private AsyncLock _fileLock;
#endregion
#region Public Properties
public bool CategoriesLoaded
{
get
{
return _cachedCategories != null;
}
}
public Category SearchCategory
{
get
{
return Category.Deserialize(Settings.Instance.SearchCategory);
}
set
{
Settings.Instance.SearchCategory = Category.Serialize(value);
this.OnPropertyChanged("SearchCategory");
}
}
public ObservableCollection<Category> Categories
{
get
{
return _categories;
}
private set
{
this.SetProperty(ref this._categories, value);
}
}
#endregion
#region Fields
ObservableCollection<Category> _categories;
CategoryList _cachedCategories;
#endregion
#region Constants
internal const string DefaultCategoryName = "all for sale";
internal const string CraigslistCategoriesFileName = "CraigslistCategories.csv";
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/LoadMorePostsVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WB.Craigslist8X.ViewModel
{
class LoadMorePostsVM : PostBase
{
public LoadMorePostsVM(QueryResultVM qrvm)
: base()
{
this._qrvm = qrvm;
}
public QueryResultVM QueryResultVM
{
get
{
return this._qrvm;
}
}
public bool LoadingMoreItems
{
get
{
return this._loadingMoreItems;
}
set
{
this.SetProperty(ref this._loadingMoreItems, value);
}
}
public override PostType Type
{
get { return PostType.LoadMore; }
}
QueryResultVM _qrvm;
bool _loadingMoreItems;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/RecentQueryVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.CraigslistApi;
using WB.SDK.Logging;
namespace WB.Craigslist8X.ViewModel
{
public class RecentQueryVM
{
#region Initialization
public RecentQueryVM(Query query)
{
Logger.Assert(query != null, "Query is null!");
_query = query;
}
#endregion
#region Properties
public Query Query
{
get
{
return _query;
}
}
public string QueryText
{
get
{
if (string.IsNullOrEmpty(_query.Text))
return "Browsing";
else
return _query.Text;
}
}
public string Context
{
get
{
return string.Format("{0} @ {1}", _query.Category.Name, _query.City.City);
}
}
#endregion
#region Fields
Query _query;
#endregion
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/CityManager.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Devices.Geolocation;
using Windows.Storage;
using Windows.Storage.Streams;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK;
using WB.SDK.Logging;
using WB.SDK.Parsing;
namespace WB.Craigslist8X.Model
{
internal class CityManager : BindableBase, IStorageBacked
{
#region Constructors
static CityManager()
{
_instanceLock = new object();
}
private CityManager()
{
this._fileLock = new AsyncLock();
this._searchCities = new ObservableCollection<CraigCity>();
string xml = string.Format("<sc>{0}</sc>", Settings.Instance.SearchCities);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
IXmlNode root = doc.SelectSingleNode("/sc");
if (!string.IsNullOrEmpty(root.InnerText))
{
// In 1.0 of Craigslist8X the data was not serialized in an XML format so it is possible that the
// text is just a single record.
// Starting in 1.1 we contain each record in a "c" tag.
XmlNodeList cities = doc.SelectNodes("/sc/c");
if (cities.Count > 0)
{
foreach (IXmlNode c in cities)
{
this._searchCities.Add(CraigCity.Deserialize(c.InnerText));
}
}
else
{
this._searchCities.Add(CraigCity.Deserialize(doc.InnerText));
}
}
}
#endregion
#region Singleton
public static CityManager Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new CityManager();
return _instance;
}
}
}
static CityManager _instance;
static object _instanceLock;
#endregion
#region IStorageBacked
public async Task<bool> LoadAsync()
{
using (new MonitoredScope("Load City Data"))
{
await Logger.Assert(!CitiesLoaded, "City data already loaded");
bool ret = await LoadFromDisk();
await Logger.Assert(ret, "Unable to load city data");
return ret;
}
}
/// <summary>
/// Loads cities to local member variable
/// </summary>
/// <returns>Boolean indicating success</returns>
private async Task<bool> LoadFromDisk()
{
StorageFile file = null;
try
{
file = await ApplicationData.Current.LocalFolder.GetFileAsync(CraigslistCitiesFileName);
}
catch (System.IO.FileNotFoundException ex)
{
Logger.LogException(ex);
}
if (file == null)
{
file = await SDK.Utilities.GetPackagedFile("Resources", "CraigslistCities.csv");
}
if (file != null)
{
CraigCityList cities = new CraigCityList();
try
{
string content = null;
using (await this._fileLock.LockAsync())
{
content = await file.LoadFileAsync();
}
foreach (var line in content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
CraigCity city = CraigCity.Deserialize(line.Trim());
cities.Add(city);
}
await Logger.Assert(cities.Count > 0, "should be more than 0 cities");
_cachedCities = cities;
List<CraigCity> sortedCities = cities.GetCities().ToList<CraigCity>();
sortedCities.Sort();
if (this.Cities == null)
this.Cities = new ObservableCollection<CraigCity>(sortedCities);
else
this.Cities.Copy(sortedCities);
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogException(ex);
}
}
return false;
}
/// <summary>
/// Serializes the CraigCityList member field to disk.
/// </summary>
/// <returns>Boolean indicating success</returns>
public async Task<bool> SaveAsync()
{
if (this._cachedCities == null)
{
await Logger.AssertNotReached("we have not cached cities! nothing to save");
return false;
}
StringBuilder sb = new StringBuilder();
foreach (var city in _cachedCities.GetCities())
{
sb.AppendLine(CraigCity.Serialize(city));
}
using (await this._fileLock.LockAsync())
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(CraigslistCitiesFileName, CreationCollisionOption.ReplaceExisting);
await file.SaveFileAsync(sb.ToString());
}
this.Dirty = false;
return true;
}
private bool Dirty
{
get;
set;
}
private AsyncLock _fileLock;
#endregion
#region Methods
public CraigCity GetCityByUri(Uri uri)
{
return this._cachedCities.GetCityByUri(uri);
}
public void AddSearchCity(CraigCity city)
{
if (!this._searchCities.Contains(city))
{
this._searchCities.Add(city);
this.SaveSearchCities();
}
}
public void RemoveSearchCity(CraigCity city)
{
this._searchCities.Remove(city);
this.SaveSearchCities();
}
public void PromoteSearchCity(CraigCity city)
{
if (this._searchCities.Contains(city))
{
int index = this._searchCities.IndexOf(city);
this._searchCities.Move(index, 0);
this.SaveSearchCities();
}
}
public async Task<CraigCity> FindNearestCityGps(Geocoordinate coordinate)
{
if (this._cachedCities == null || this._cachedCities.Count == 0)
{
await Logger.AssertNotReached("Craig cities have not been cached!");
return null;
}
CraigCity city = null;
double diff = double.MaxValue;
foreach (var c in this._cachedCities.GetCities())
{
if (c.Latitude == double.MinValue || c.Longitude == double.MinValue)
continue;
double d = Math.Abs(coordinate.Latitude - c.Latitude) + Math.Abs(coordinate.Longitude - c.Longitude);
if (d < diff)
{
if (c != null)
{
city = c;
diff = d;
}
}
}
return city;
}
#endregion
#region Private Methods
private void SaveSearchCities()
{
string xml = string.Empty;
foreach (CraigCity c in this._searchCities)
{
xml += string.Format("<c>{0}</c>", CraigCity.Serialize(c));
}
Settings.Instance.SearchCities = xml;
this.OnPropertyChanged("SearchCities");
}
#endregion
#region Properties
internal bool CitiesLoaded
{
get
{
return _cachedCities != null;
}
}
internal bool SearchCitiesDefined
{
get
{
return this.SearchCities != null && this.SearchCities.Count > 0;
}
}
internal ReadOnlyObservableCollection<CraigCity> SearchCities
{
get
{
return new ReadOnlyObservableCollection<CraigCity>(this._searchCities);
}
}
internal ObservableCollection<CraigCity> Cities
{
get
{
return _cities;
}
private set
{
this.SetProperty(ref this._cities, value);
}
}
#endregion
#region Fields
/// <summary>
/// We need a CraigCityList because this is used by CraigslistApi methods
/// </summary>
CraigCityList _cachedCities;
ObservableCollection<CraigCity> _cities;
ObservableCollection<CraigCity> _searchCities;
#endregion
#region Constants
internal const string CraigslistCitiesFileName = "CraigslistCities.csv";
#endregion
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/Common/Utility.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public static class Utility
{
public static string GetSearchCityLabel()
{
string location = string.Empty;
if (!CityManager.Instance.SearchCitiesDefined)
{
location = "undefined";
}
else
{
location = CityManager.Instance.SearchCities.First().DisplayName;
}
// More?
if (CityManager.Instance.SearchCities.Count > 1)
{
location += string.Format(", +{0}", CityManager.Instance.SearchCities.Count - 1);
}
return location;
}
public static string GetSearchCategoryLabel()
{
return CategoryManager.Instance.SearchCategory == null ? "undefined" : CategoryManager.Instance.SearchCategory.Name;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/Settings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
namespace WB.Craigslist8X.Model
{
public class Settings
{
#region Initialization
static Settings()
{
_instanceLock = new object();
}
private Settings()
{
}
#endregion
#region Singleton
public static Settings Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new Settings();
return _instance;
}
}
}
static Settings _instance;
static object _instanceLock;
#endregion
#region Properties
public string SearchCities
{
get
{
return GetSetting(SearchCitiesKey, SearchCitiesDefault);
}
set
{
SetSetting(SearchCitiesKey, value);
}
}
public string SearchCategory
{
get
{
return GetSetting(SearchCategoryKey, SearchCategoryDefault);
}
set
{
SetSetting(SearchCategoryKey, value);
}
}
public int CitiesRefreshDays
{
get
{
return GetSetting(CitiesRefreshDaysKey, CitiesRefreshDaysDefault);
}
set
{
SetSetting(CitiesRefreshDaysKey, value);
}
}
public int InAppPostCount
{
get
{
return GetSetting(InAppPostCountKey, InAppPostDefault);
}
set
{
SetSetting(InAppPostCountKey, value);
}
}
public DateTime LastCitiesRefresh
{
get
{
return DateTime.Parse(GetSetting(LastCitiesRefreshKey, DateTime.MinValue.ToString()));
}
set
{
SetSetting(LastCitiesRefreshKey, value.ToString());
}
}
public bool ShouldRefreshCities
{
get
{
TimeSpan span = DateTime.Now - LastCitiesRefresh;
return span.TotalDays >= CitiesRefreshDays;
}
}
public bool DetailedSearchResults
{
get
{
return GetSetting(DetailedSearchResultsKey, DetailedSearchResultsDefault);
}
set
{
SetSetting(DetailedSearchResultsKey, value);
}
}
public bool OnlyShowPostsPictures
{
get
{
return GetSetting(OnlyShowPostsPicturesKey, OnlyShowPostsPicturesDefault);
}
set
{
SetSetting(OnlyShowPostsPicturesKey, value);
}
}
public bool OnlySearchTitles
{
get
{
return GetSetting(OnlySearchTitleKey, OnlySearchTitlesDefault);
}
set
{
SetSetting(OnlySearchTitleKey, value);
}
}
public bool TrackRecentlyViewedPosts
{
get
{
return GetSetting(TrackRecentlyViewedKey, TrackRecentlyViewedDefault);
}
set
{
SetSetting(TrackRecentlyViewedKey, value);
}
}
public bool TrackRecentSearches
{
get
{
return GetSetting(TrackRecentSearchesKey, TrackRecentSearchesDefault);
}
set
{
SetSetting(TrackRecentSearchesKey, value);
}
}
public bool ExpandPost
{
get
{
return GetSetting(ExpandPostKey, ExpandPostKeyDefault);
}
set
{
SetSetting(ExpandPostKey, value);
}
}
public bool ExpandSearchResults
{
get
{
return GetSetting(ExpandSearchResultsKey, ExpandSearchResultsDefault);
}
set
{
SetSetting(ExpandSearchResultsKey, value);
}
}
public bool CollapseOnSelection
{
get
{
return GetSetting(CollapseOnSelectionKey, CollapseOnSelectionDefault);
}
set
{
SetSetting(CollapseOnSelectionKey, value);
}
}
public int AppBootCount
{
get
{
return GetSetting(AppBootCountKey, AppBootCountDefault);
}
set
{
SetSetting(AppBootCountKey, value);
}
}
public bool ShowExpandTip
{
get
{
return GetSetting(ShowExpandTipKey, ShowExpandTipDefault);
}
set
{
SetSetting(ShowExpandTipKey, value);
}
}
public bool PromptForRating
{
get
{
return GetSetting(PromptForRatingKey, PromptForRatingDefault);
}
set
{
SetSetting(PromptForRatingKey, value);
}
}
public bool ShowPostNavBar
{
get
{
return GetSetting(ShowPostNavBarKey, ShowPostNavBarDefault);
}
set
{
SetSetting(ShowPostNavBarKey, value);
}
}
public string LastReadNewsItem
{
get
{
return GetSetting(LastReadNewsItemKey, LastReadNewsItemDefault);
}
set
{
SetSetting(LastReadNewsItemKey, value);
}
}
public bool PersonalsUnlocked
{
get
{
return GetSetting(PersonalsUnlockedKey, PersonalsUnlockDefault);
}
set
{
SetSetting(PersonalsUnlockedKey, value);
}
}
#endregion
#region Methods
public static T GetSetting<T>(string key, T defaultValue)
{
if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
ApplicationData.Current.LocalSettings.Values.Add(key, defaultValue);
return (T)ApplicationData.Current.LocalSettings.Values[key];
}
public static void SetSetting<T>(string key, T value)
{
ApplicationData.Current.LocalSettings.Values.Remove(key);
ApplicationData.Current.LocalSettings.Values.Add(key, value);
}
#endregion
#region Constants
private const string SearchCitiesKey = "CurrentCityKey";
private const string SearchCitiesDefault = null;
private const string SearchCategoryKey = "CurrentCategoryKey";
private const string SearchCategoryDefault = "for sale,all for sale,sss";
private const string CitiesRefreshDaysKey = "CitiesRefreshDays";
private const int CitiesRefreshDaysDefault = 30;
private const string LastCitiesRefreshKey = "DaysSinceCitiesRefresh";
private const string CategoriesRefreshDaysKey = "CategoriesRefreshDays";
private const int CategoriesRefreshDaysDefault = 30;
private const string LastCategoriesRefreshKey = "DaysSinceCategoriesRefresh";
private const string DetailedSearchResultsKey = "DetailedSearchResults";
private const bool DetailedSearchResultsDefault = true;
private const string OnlyShowPostsPicturesKey = "OnlyShowPostsPicturesKey";
private const bool OnlyShowPostsPicturesDefault = false;
private const string OnlySearchTitleKey = "OnlySearchTitlesKey";
private const bool OnlySearchTitlesDefault = false;
private const string TrackRecentlyViewedKey = "TrackRecentlyViewedKey";
private const bool TrackRecentlyViewedDefault = true;
private const string TrackRecentSearchesKey = "TrackRecentSearchesKey";
private const bool TrackRecentSearchesDefault = true;
private const string ExpandPostKey = "ExpandPostKey";
private const bool ExpandPostKeyDefault = false;
private const string ExpandSearchResultsKey = "ExpandSearchResultsKey";
private const bool ExpandSearchResultsDefault = true;
private const string CollapseOnSelectionKey = "CollapseOnSelectionKey";
private const bool CollapseOnSelectionDefault = true;
private const string AppBootCountKey = "AppBootCountKey";
private const int AppBootCountDefault = 0;
private const string ShowExpandTipKey = "ShowExpandTipKey";
private const bool ShowExpandTipDefault = true;
private const string PromptForRatingKey = "PromptForRatingKey";
private const bool PromptForRatingDefault = true;
private const string ShowPostNavBarKey = "ShowPostNavBarKey";
private const bool ShowPostNavBarDefault = true;
private const string InAppPostCountKey = "InAppPostCountKey";
private const int InAppPostDefault = 0;
private const string LastReadNewsItemKey = "LastReadNewsItemKey";
private readonly string LastReadNewsItemDefault = DateTime.MinValue.ToString();
private const string PersonalsUnlockedKey = "AppPUnlockedKey";
private const bool PersonalsUnlockDefault = false;
#endregion
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/ChooseAccountPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Security.Credentials;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.View;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class ChooseAccountPanel : UserControl, IPanel
{
public ChooseAccountPanel()
{
this.InitializeComponent();
this._msgLock = new AsyncLock();
}
public Task AttachContext(object context, IPanel parent)
{
UserAccounts.Instance.Accounts.CollectionChanged += Accounts_CollectionChanged;
this._purpose = (ChooseAccountPurpose)context;
this.PopulateList();
return null;
}
void Accounts_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
this.PopulateList();
}
private void PopulateList()
{
List<AccountVMBase> accountList = (from x in UserAccounts.Instance.Accounts select new AccountVM(x)).ToList<AccountVMBase>();
if (this._purpose == ChooseAccountPurpose.CreatePost)
{
accountList.Add(new AnonymousVM());
}
accountList.Add(new AddAccountVM());
this.AccountsItemList.ItemsSource = accountList;
}
private void ListView_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(this.AccountsItemList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
private async void ChooseAccount_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
using (await this._msgLock.LockAsync())
{
if (container != null && container.DataContext as AccountVMBase != null)
{
AccountVMBase accountVM = (AccountVMBase)container.DataContext;
if (accountVM.Type == AccountVMBase.ViewModelType.Add)
{
await AddAccountAsync();
return;
}
else
{
// There are two other accountVM.Types: Anonymous and logged in user.
// If we are in account management, the anonymous option should not be visible.
switch (this._purpose)
{
case ChooseAccountPurpose.CreatePost:
await this.CreatePostAsync(container.DataContext as AccountVM);
break;
case ChooseAccountPurpose.AccountManagement:
await this.ManageAccountAsync(container.DataContext as AccountVM);
break;
default:
await Logger.AssertNotReached("Unknown purpose type.");
break;
}
}
}
}
}
private async void DeleteAccount_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
if (!(sender is FrameworkElement) || !((sender as FrameworkElement).DataContext is AccountVM))
{
await Logger.AssertNotReached("We expect an account item");
return;
}
AccountVM account = ((sender as FrameworkElement).DataContext as AccountVM);
UserAccounts.Instance.Remove(account.Account);
}
private async Task AddAccountAsync()
{
PasswordCredential account = await UserAccounts.PromptForCreds("Add your Craigslist username and password to Craigslist 8X");
if (account != null)
{
account.RetrievePassword();
if (!await Craigslist.Instance.ValidateCreds(account.UserName, account.Password))
{
await new MessageDialog("We have failed to login to craigslist using the credentials provided.", "Craigslist 8X").ShowAsync();
}
else
{
UserAccounts.Instance.Add(account);
}
}
}
private async Task CreatePostAsync(AccountVM avm)
{
await Logger.Assert(CityManager.Instance.SearchCitiesDefined, "How did we get this far without defining search cities?");
if (!CityManager.Instance.SearchCitiesDefined)
{
await new MessageDialog("Please define your search cities before proceeding.", "Craigslist 8X").ShowAsync();
SettingsUI.ShowSearchSettings();
return;
}
if (!App.IsPro && Settings.Instance.InAppPostCount >= InAppFreeLimit)
{
MessageDialog msg = new MessageDialog(@"Sorry, you have reached the in app post limit. Please upgrade to Craigslist 8X PRO to unlock unlimited in app posts and other goodies.");
await msg.ShowAsync();
return;
}
PasswordCredential acct = avm != null ? avm.Account : null;
// There is actually more than one city, let the user pick which one he wants to post to.
List<CraigCity> cities = (from x in CityManager.Instance.SearchCities select CityManager.Instance.GetCityByUri(x.Location)).Distinct().ToList();
if (cities.Count > 1)
{
await MainPage.Instance.ExecuteChooseCity(this, acct);
}
else
{
CreatePostContext context = new CreatePostContext();
context.Account = acct;
context.City = cities.First();
await MainPage.Instance.ExecuteCreatePost(this, context);
}
}
private async Task ManageAccountAsync(AccountVM avm)
{
if (!App.IsPro)
{
MessageDialog msg = new MessageDialog(@"Sorry, this is a Craigslist 8X Pro only feature. Please upgrade to Craigslist 8X PRO to unlock account management, unlimited in app posts and other goodies.");
await msg.ShowAsync();
return;
}
PasswordCredential acct = avm != null ? avm.Account : null;
if (acct == null)
{
await Logger.AssertNotReached("Should have valid user credentials");
return;
}
await MainPage.Instance.ExecuteAccountManagement(this, acct);
}
private ChooseAccountPurpose _purpose;
private AsyncLock _msgLock;
const int InAppFreeLimit = 3;
}
public enum ChooseAccountPurpose
{
CreatePost,
AccountManagement,
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/NewsManager.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WB.SDK.Logging;
using Windows.ApplicationModel;
using Windows.Data.Xml.Dom;
namespace WB.Craigslist8X.Model
{
public class NewsManager
{
static NewsManager()
{
_instanceLock = new object();
}
private NewsManager()
{
}
#region Singleton
public static NewsManager Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new NewsManager();
return _instance;
}
}
}
static NewsManager _instance;
static object _instanceLock;
#endregion
private async Task CacheFeed()
{
try
{
if (this._feed != null)
return;
using (HttpClient client = new HttpClient())
using (var response = await client.GetAsync(NewsfeedUrl))
{
if (response.IsSuccessStatusCode)
{
this._feed = new XmlDocument();
this._feed.LoadXml(await response.Content.ReadAsStringAsync());
}
}
}
catch (Exception)
{
}
}
public async Task<bool> IsNewItem()
{
try
{
await this.CacheFeed();
if (this._feed == null)
return false;
DateTime start = NewsStartTime;
var items = this._feed.SelectNodes("//item");
foreach (var item in items)
{
DateTime itemDate;
var date = item.SelectSingleNode("pubDate").InnerText;
DateTimeFormatInfo format = new DateTimeFormatInfo();
if (DateTime.TryParseExact(date, format.RFC1123Pattern, null, DateTimeStyles.None, out itemDate))
{
// Make sure we haven't read it before and that the news item is no more than 30 days old.
if (itemDate > start)
{
return true;
}
}
}
}
catch (Exception)
{
}
return false;
}
public async Task<List<NewsItem>> GetNews()
{
// We only start getting items from the time we last read a news item or 30 days old, whichever is more recent.
DateTime start = NewsStartTime;
List<NewsItem> news = new List<NewsItem>();
try
{
await this.CacheFeed();
if (this._feed == null)
return null;
DateTime lastItemRead = DateTime.Parse(Settings.Instance.LastReadNewsItem);
var items = this._feed.SelectNodes("//item");
foreach (var item in items)
{
DateTime itemDate;
var date = item.SelectSingleNode("pubDate").InnerText;
DateTimeFormatInfo format = new DateTimeFormatInfo();
if (DateTime.TryParseExact(date, format.RFC1123Pattern, null, DateTimeStyles.None, out itemDate))
{
if (itemDate > start)
{
if (itemDate > lastItemRead)
{
Settings.Instance.LastReadNewsItem = itemDate.ToString();
}
NewsItem newsItem = new NewsItem();
newsItem.Date = itemDate.ToString("MM/dd/yyyy");
newsItem.Title = item.SelectSingleNode("title").InnerText;
newsItem.Content = item.SelectSingleNode("description").InnerText;
news.Add(newsItem);
}
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
return null;
}
return news;
}
/// <summary>
/// Basically this only exists because of the Windows 8 certification process. They suck.
/// Every once in a while you get a reviewer that simply does not understand the app is a storefront app
/// and personals is allowed. This is an attempt to bypass that.
/// </summary>
/// <returns></returns>
public async Task<bool> IsPersonalsAvailable()
{
try
{
await this.CacheFeed();
if (this._feed == null)
return false;
var latest = this._feed.SelectNodesNS("//c8x:latest", "xmlns:c8x='http://www.craigslist8x.com'").FirstOrDefault();
if (latest != null)
{
Version latestAllowed;
if (Version.TryParse(latest.InnerText, out latestAllowed))
{
PackageVersion app = Package.Current.Id.Version;
Version current = new Version(string.Format("{0}.{1}.{2}.{3}", app.Major, app.Minor, app.Build, app.Revision));
int result = latestAllowed.CompareTo(current);
return result >= 0;
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
return false;
}
private DateTime NewsStartTime
{
get
{
// We only start getting items from the time we last read a news item or 30 days old, whichever is more recent.
DateTime readNewsItem = DateTime.Parse(Settings.Instance.LastReadNewsItem);
DateTime force2013 = DateTime.Parse("1/1/2013 12:00:00 AM");
// The previous default on minvalue was not a good idea, but we can't change it at this point
// just force the new minimum to start of 2013.
readNewsItem = readNewsItem < force2013 ? force2013 : readNewsItem;
return DateTime.FromFileTime(Math.Max(readNewsItem.ToFileTime(), DateTime.Now.AddDays(-30).ToFileTime()));
}
}
private Uri NewsfeedUrl
{
get
{
#if CRAIGSLIST8XPRO
return new Uri("http://wbishop.azurewebsites.net/rss/craigslist8xpro.xml");
#else
return new Uri("http://wbishop.azurewebsites.net/rss/craigslist8x.xml");
#endif
}
}
XmlDocument _feed;
}
public class NewsItem
{
public string Date
{
get;
set;
}
public string Title
{
get;
set;
}
public string Content
{
get;
set;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/ManagePostPanel.xaml.cs
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Credentials;
using Windows.System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace WB.Craigslist8X.View
{
public sealed partial class ManagePostPanel : UserControl, IPanel
{
public ManagePostPanel()
{
this.InitializeComponent();
}
public async Task AttachContext(object context, IPanel parent)
{
var postingContext = context as ManagePostContext;
if (postingContext == null)
{
await Logger.AssertNotReached("null managepostcontext?");
await AbortAccountManagement("Invalid posting context. Aborting post management.");
return;
}
_parent = parent as UIElement;
_context = postingContext;
_commands = new Dictionary<ManageCommand, Dictionary<string, string>>();
HttpResponseMessage response = null;
try
{
response = await this._context.Client.GetAsync(this._context.Posting.Manage);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
if (response == null || !response.IsSuccessStatusCode)
{
await this.AbortAccountManagement("Received bad response from craigslist.");
return;
}
else
{
await this.ParseResponse(response);
}
}
public async Task ParseResponse(HttpResponseMessage response)
{
bool success = false;
this.TitleHeader.Text = string.Format("Manage Posting: {0}", this._context.Posting.Title);
try
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(await response.Content.ReadAsStringAsync());
var container = (from pc in doc.DocumentNode.Descendants("div").Where(x => x.Id == "pagecontainer") select pc).FirstOrDefault();
if (container != null)
{
string html = @"<html>
<head>
<link type=""text/css"" rel=""stylesheet"" media=""all"" href=""https://post.craigslist.org/styles/clnew.css"">
</head>
<body class=""post"">
<article id=""pagecontainer"">
<section class=""body"">
{0}
</section>
</article>
</body>
</html>";
PostingWebView.NavigateToString(string.Format(html, container.OuterHtml));
EditButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
RepostButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
DeleteButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
UndeleteButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
_commands.Clear();
var edit = (from manageButtons in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "managebutton")
from hidden in manageButtons.Descendants("input").Where(x => x.Attributes["type"].Value == "hidden" && x.Attributes["value"] != null && x.Attributes["value"].Value == "edit")
select hidden).FirstOrDefault();
if (edit != null)
{
_commands.Add(ManageCommand.Edit, new Dictionary<string, string>());
var fields = (from f in edit.ParentNode.Descendants("input") select f);
foreach (var field in fields)
{
_commands[ManageCommand.Edit].Add(field.Attributes["name"].Value, field.Attributes["value"].Value);
}
EditButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
var delete = (from manageButtons in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "managebutton")
from hidden in manageButtons.Descendants("input").Where(x => x.Attributes["type"].Value == "hidden" && x.Attributes["value"] != null && x.Attributes["value"].Value == "delete")
select hidden).FirstOrDefault();
if (delete != null)
{
_commands.Add(ManageCommand.Delete, new Dictionary<string, string>());
var fields = (from f in delete.ParentNode.Descendants("input") select f);
foreach (var field in fields)
{
_commands[ManageCommand.Delete].Add(field.Attributes["name"].Value, field.Attributes["value"].Value);
}
DeleteButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
var repost = (from manageButtons in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "managebutton")
from hidden in manageButtons.Descendants("input").Where(x => x.Attributes["type"].Value == "hidden" && x.Attributes["value"] != null && x.Attributes["value"].Value == "repost")
select hidden).FirstOrDefault();
if (repost != null)
{
_commands.Add(ManageCommand.Repost, new Dictionary<string, string>());
var fields = (from f in repost.ParentNode.Descendants("input") select f);
foreach (var field in fields)
{
_commands[ManageCommand.Repost].Add(field.Attributes["name"].Value, field.Attributes["value"].Value);
}
RepostButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
var undelete = (from manageButtons in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "managebutton")
from hidden in manageButtons.Descendants("input").Where(x => x.Attributes["type"].Value == "hidden" && x.Attributes["value"] != null && x.Attributes["value"].Value == "undelete")
select hidden).FirstOrDefault();
if (undelete != null)
{
_commands.Add(ManageCommand.Undelete, new Dictionary<string, string>());
var fields = (from f in undelete.ParentNode.Descendants("input") select f);
foreach (var field in fields)
{
_commands[ManageCommand.Undelete].Add(field.Attributes["name"].Value, field.Attributes["value"].Value);
}
UndeleteButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
success = true;
}
}
finally
{
this.ProgressBar.Visibility = Visibility.Collapsed;
}
if (!success)
{
MessageDialog dlg = new MessageDialog(@"Sorry, we ran into an issue parsing the response from craigslist. Please notify the developer of this app so the issue may be investigated.
In the mean time, would you like to manage your post in the browser?");
dlg.Commands.Clear();
dlg.Commands.Add(new UICommand("Yes", null, true));
dlg.Commands.Add(new UICommand("No", null, false));
UICommand result = await dlg.ShowAsync() as UICommand;
if ((bool)result.Id)
{
await Launcher.LaunchUriAsync(response.RequestMessage.RequestUri);
}
}
}
private async Task AbortAccountManagement(string message)
{
this.ProgressBar.Visibility = Visibility.Collapsed;
await new MessageDialog(message, "Craigslist 8X").ShowAsync();
MainPage.Instance.RemoveChildPanels(this._parent);
MainPage.Instance.PanelView.SnapToPanel(this._parent);
}
private async void DeletePosting_Tapped(object sender, TappedRoutedEventArgs e)
{
bool success = false;
try
{
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
var query = GetPostData(ManageCommand.Delete);
var uri = new Uri(string.Format("{0}?{1}", _context.Posting.Manage, query));
HttpResponseMessage response = await _context.Client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
success = true;
var dlg = new MessageDialog("Are you sure you want to delete this post?", "Craigslist 8X");
dlg.Commands.Add(new UICommand("Yes"));
dlg.Commands.Add(new UICommand("No"));
var answer = await dlg.ShowAsync();
if (answer.Label == "Yes")
{
// Reset the success to false in case actual deleting fails and not because user anwered no
success = false;
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(await response.Content.ReadAsStringAsync());
var delete = (from manageButtons in doc.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "managebutton")
from hidden in manageButtons.Descendants("input").Where(x => x.Attributes["type"].Value == "hidden" && x.Attributes["value"] != null && x.Attributes["value"].Value == "delete")
select hidden).FirstOrDefault();
if (delete != null)
{
var form = delete.ParentNode;
var inputs = (from i in form.Descendants("input") select i);
string postData = string.Empty;
foreach (var input in inputs)
{
postData += string.Format("&{0}={1}", Uri.EscapeDataString(input.Attributes["name"].Value), Uri.EscapeDataString(input.Attributes["value"].Value));
}
postData = postData.Substring(1);
var content = new StringContent(postData);
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
response = await _context.Client.PostAsync(_context.Posting.Manage, content);
if (response.IsSuccessStatusCode)
{
if (this._parent is AccountManagementPanel)
{
var managePosts = this._parent as AccountManagementPanel;
managePosts.RefreshPosts();
}
MainPage.Instance.RemoveChildPanels(this._parent);
MainPage.Instance.PanelView.SnapToPanel(this._parent);
success = true;
}
}
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (!success)
{
MessageDialog dlg = new MessageDialog("Sorry, we ran into an issue while trying to undelete this posting. Please try again.", "Craigslist 8X");
await dlg.ShowAsync();
}
}
private async void UndeletePosting_Tapped(object sender, TappedRoutedEventArgs e)
{
bool success = false;
try
{
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
var content = new StringContent(GetPostData(ManageCommand.Undelete));
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await _context.Client.PostAsync(_context.Posting.Manage, content);
if (response.IsSuccessStatusCode)
{
await ParseResponse(response);
success = true;
if (this._parent is AccountManagementPanel)
{
var managePosts = this._parent as AccountManagementPanel;
managePosts.RefreshPosts();
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (!success)
{
MessageDialog dlg = new MessageDialog("Sorry, we ran into an issue while trying to undelete this posting. Please try again.", "Craigslist 8X");
await dlg.ShowAsync();
}
}
private async void RepostPosting_Tapped(object sender, TappedRoutedEventArgs e)
{
// For some fucked up reason, much like everything on Craigslist, REPOST is different,
// all other actions. We need to do a GET instead of a POST
CreatePostContext ctx = new CreatePostContext();
ctx.Handler = _context.Handler;
ctx.Client = _context.Client;
ctx.Account = _context.Account;
ctx.Url = GetRepostUri();
MainPage.Instance.RemoveChildPanels(this._parent);
await MainPage.Instance.ExecuteCreatePost(this._parent, ctx);
}
private async void EditPosting_Tapped(object sender, TappedRoutedEventArgs e)
{
bool success = false;
try
{
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
var content = new StringContent(GetPostData(ManageCommand.Edit));
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await _context.Client.PostAsync(_context.Posting.Manage, content);
if (response.IsSuccessStatusCode)
{
CreatePostContext ctx = new CreatePostContext();
ctx.Handler = _context.Handler;
ctx.Client = _context.Client;
ctx.Account = _context.Account;
ctx.Url = response.RequestMessage.RequestUri;
MainPage.Instance.RemoveChildPanels(this._parent);
await MainPage.Instance.ExecuteCreatePost(this._parent, ctx);
success = true;
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
ProgressBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (!success)
{
MessageDialog dlg = new MessageDialog("Sorry, we ran into an issue while trying to edit this posting. Please try again.", "Craigslist 8X");
await dlg.ShowAsync();
}
}
private Uri GetRepostUri()
{
StringBuilder sb = new StringBuilder();
sb.Append(_context.Posting.Manage.ToString());
for (int i = 0; i < this._commands[ManageCommand.Repost].Count; ++i)
{
sb.Append(i == 0 ? "?" : "&");
var kvp = this._commands[ManageCommand.Repost].ElementAt(i);
sb.AppendFormat("{0}={1}", Uri.EscapeUriString(kvp.Key), kvp.Value.Replace(' ', '+'));
}
return new Uri(sb.ToString());
}
private string GetPostData(ManageCommand cmd)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this._commands[cmd].Count; ++i)
{
sb.Append(i == 0 ? string.Empty : "&");
var kvp = this._commands[cmd].ElementAt(i);
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value));
}
return sb.ToString();
}
UIElement _parent;
ManagePostContext _context;
Dictionary<ManageCommand, Dictionary<string, string>> _commands;
}
enum ManageCommand
{
Edit,
Delete,
Repost,
Undelete,
}
public class ManagePostContext
{
public PasswordCredential Account
{
get;
set;
}
public HttpClientHandler Handler
{
get;
set;
}
public HttpClient Client
{
get;
set;
}
public PostingVM Posting
{
get;
set;
}
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/ExploreCategoriesPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class ExploreCategoriesPanel : UserControl, IPanel
{
public ExploreCategoriesPanel()
{
this.InitializeComponent();
this.DataContext = this;
}
public Task AttachContext(object context, IPanel parent)
{
Category cat = context as Category;
this.RefreshRootCategory(cat);
return null;
}
private void SearchItemsList_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(SearchItemsList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
private async void Category_Tapped(object sender, TappedRoutedEventArgs e)
{
Border el = sender as Border;
if (el == null)
return;
CategoryVM cvm = (el.DataContext as CategoryVM);
Category cat = cvm.Category;
this.SetSelection(cvm);
if (this._vm.Root == null)
{
List<Category> categories = CategoryManager.Instance.Categories.Where(x => x.Root == cat.Root).ToList();
if (categories.Count() == 1)
{
Query template = new Query(CityManager.Instance.SearchCities.First(), categories.First(), string.Empty);
template.HasImage = Settings.Instance.OnlyShowPostsPictures;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
await MainPage.Instance.ExecuteSearchQuery(this, qb);
}
else
{
await MainPage.Instance.ExecuteBrowse(this, cat);
}
}
else
{
Query template = new Query(CityManager.Instance.SearchCities.First(), cat, string.Empty);
template.HasImage = Settings.Instance.OnlyShowPostsPictures;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
await MainPage.Instance.ExecuteSearchQuery(this, qb);
}
}
private void SetSelection(CategoryVM item)
{
if (this._selected != null)
{
this._selected.Selected = false;
}
this._selected = item;
item.Selected = true;
}
private void RefreshRootCategory(Category root)
{
this._vm = new ExploreCategoriesVM(root);
this.DataContext = this._vm;
}
ExploreCategoriesVM _vm;
CategoryVM _selected;
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8XTasks/SearchAgentTask.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Notifications;
namespace Craigslist8XTasks
{
public sealed class SearchAgentTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
StringBuilder notifications = new StringBuilder();
XmlDocument doc = await LoadSavedSearches();
if (doc != null)
{
// We may have saved searches. Do something.
var savedQueries = doc.SelectNodes("root/sq");
int globalCount = 0;
notifications.AppendLine("<root>");
foreach (var sq in savedQueries)
{
if (sq.Attributes.GetNamedItem("url") != null)
{
Guid tile = Guid.Parse(sq.Attributes.GetNamedItem("tile").InnerText);
DateTime dt = DateTime.Now.Subtract(TimeSpan.FromDays(1));
if (sq.Attributes.GetNamedItem("time") != null)
dt = DateTime.Parse(sq.Attributes.GetNamedItem("time").InnerText);
Uri query = new Uri(string.Format("{0}&format=rss", Uri.UnescapeDataString(sq.Attributes.GetNamedItem("url").InnerText)));
try
{
using (HttpClient client = new HttpClient())
using (var response = await client.GetAsync(query))
{
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
XmlDocument xml = new XmlDocument();
xml.LoadXml(content);
var items = xml.SelectNodesNS("//ns:item", "xmlns:ns='http://purl.org/rss/1.0/'");
int newItems = 0;
DateTime newestItem = DateTime.MinValue;
foreach (var item in items)
{
DateTime postTime = DateTime.Parse(item.SelectSingleNodeNS("dc:date", "xmlns:dc='http://purl.org/dc/elements/1.1/'").InnerText);
if (postTime > dt)
{
++newItems;
}
if (postTime > newestItem)
{
newestItem = postTime;
}
}
notifications.AppendLine(string.Format(@"<n tile=""{0}"" count=""{1}"" time=""{2}"" />", tile, newItems, newestItem));
if (newItems > 0)
{
globalCount += newItems;
if (sq.Attributes.GetNamedItem("tile") != null)
{
try
{
XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", globalCount.ToString());
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdater updater = BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile(sq.Attributes.GetNamedItem("tile").InnerText);
updater.Update(badge);
}
catch
{
// Tile does not exist
}
}
}
else
{
try
{
BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile(tile.ToString()).Clear();
}
catch
{
// Tile does not exist
}
}
}
}
}
catch
{
}
}
}
notifications.AppendLine("</root>");
// We only save to the local notifications file. Never touch the actual roaming saved searches file
await SaveNotificationsAsync(notifications.ToString());
if (globalCount > 0)
{
try
{
XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", globalCount.ToString());
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
}
catch
{
}
}
else
{
try
{
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
}
catch
{
}
}
}
else
{
try
{
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
}
catch
{
}
}
deferral.Complete();
}
public IAsyncOperation<XmlDocument> LoadSavedSearches()
{
return Task.Run<XmlDocument>(async () =>
{
StorageFile file = null;
try
{
file = await ApplicationData.Current.RoamingFolder.GetFileAsync(SavedSearchesFileName);
}
catch (FileNotFoundException)
{
return null;
}
if (file != null)
{
try
{
using (var stream = await file.OpenAsync(FileAccessMode.Read))
using (var readStream = stream.GetInputStreamAt(0))
using (DataReader reader = new DataReader(readStream))
{
uint bytesLoaded = await reader.LoadAsync((uint)stream.Size);
string content = reader.ReadString(bytesLoaded);
if (string.IsNullOrEmpty(content))
return null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
return doc;
}
}
catch
{
System.Diagnostics.Debugger.Break();
}
}
return null;
}).AsAsyncOperation();
}
public IAsyncAction SaveNotificationsAsync(string content)
{
return Task.Run(async () =>
{
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(NotificationsFileName, CreationCollisionOption.ReplaceExisting);
using (var raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
using (var outStream = raStream.GetOutputStreamAt(0))
using (DataWriter writer = new DataWriter(outStream))
{
writer.WriteString(content);
await writer.StoreAsync();
await outStream.FlushAsync();
}
}
catch
{
}
}).AsAsyncAction();
}
#region Constants
const string SavedSearchesFileName = "SavedSearches.xml";
const string NotificationsFileName = "SavedSearchesNotifications.xml";
#endregion
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/QueryResult.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Data.Html;
using Windows.Data.Xml.Dom;
using Windows.UI.Core;
using Windows.UI.Xaml.Media;
using HtmlAgilityPack;
using WinRTXamlToolkit.Async;
using WB.SDK;
using WB.SDK.Logging;
namespace WB.CraigslistApi
{
public class QueryResult
{
#region Constructor
public QueryResult(Query query, ObservableCollection<Post> posts, HttpResponseMessage response)
{
this.Query = query;
this.Posts = posts;
this.HttpResponse = response;
this.ItemsLock = new AsyncLock();
}
#endregion
#region Methods
public async Task LoadMoreAsync()
{
await Logger.Assert(!DoneLoading, "We think we are already done loading but trying to load more");
if (DoneLoading)
return;
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(await this.Query.ConstructUri(this.Posts.Count)))
{
if (response.IsSuccessStatusCode)
{
this.HttpResponse = response;
await QueryResult.ParseRows(new CancellationToken(), response, this);
}
}
}
#endregion
static internal async Task ParseRows(CancellationToken token, HttpResponseMessage response, QueryResult qr)
{
token.ThrowIfCancellationRequested();
await Logger.Assert(response.IsSuccessStatusCode, "We are parsing rows for an unsuccessful response!");
HtmlDocument html = new HtmlDocument();
html.LoadHtml(await response.Content.ReadAsStringAsync());
token.ThrowIfCancellationRequested();
using (await qr.ItemsLock.LockAsync())
{
ParseBrowseResults(token, html, qr);
}
}
static void ParseBrowseResults(CancellationToken token, HtmlDocument html, QueryResult qr)
{
var rows = (from x in html.DocumentNode.Descendants().Where(x => x.Name == "h4" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("ban")
|| x.Name == "p" && x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("row"))
select x).ToList();
string shortDate = null;
int count = 0;
foreach (var node in rows)
{
if (node.Name == "h4")
{
shortDate = node.InnerText;
}
else if (node.Name == "p")
{
++count;
Post p = new Post();
p.Parse(qr, node, shortDate);
qr.Posts.Add(p);
token.ThrowIfCancellationRequested();
}
}
qr.DoneLoading = (count < 100);
qr.Count += count;
}
static void ParseSearchResults(CancellationToken token, HtmlDocument html, QueryResult qr)
{
var rows =
(from p in html.DocumentNode.Descendants("p").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("row"))
select p).ToList();
if (rows == null || rows.Count == 0) // No results found
{
qr.Count = 0;
qr.DoneLoading = true;
return;
}
var dateBanner = (from x in html.DocumentNode.Descendants("h4").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("ban"))
select x).FirstOrDefault();
if (dateBanner != null)
{
string[] parts = Uri.UnescapeDataString(dateBanner.InnerText).Split(' ');
for (int i = 0; i < parts.Length; ++i)
{
int count;
if (int.TryParse(parts[i], out count))
{
qr.Count = count;
break;
}
}
}
// If there are too few results, Craigslist might show nearby results. We probably do not want to show that here.
if (dateBanner != null && qr.Count == 0 && rows.Count < 10)
{
qr.DoneLoading = true;
return;
}
// Parsing each row should take approximately 0.5 milliseconds. Do this synchronously as it actually degrades perceived performance
// to schedule this via the taskpool.
using (MonitoredScope scope = new MonitoredScope("Parse '{0}' search rows", rows.Count))
{
for (int i = 0; i < rows.Count; ++i)
{
Post p = new Post();
p.Parse(qr, rows[i], null);
qr.Posts.Add(p);
token.ThrowIfCancellationRequested();
}
}
qr.DoneLoading = (qr.Posts.Count == qr.Count);
}
#region Properties
public bool DoneLoading
{
get;
set;
}
public int Count
{
get;
set;
}
public Query Query
{
get;
private set;
}
public ObservableCollection<Post> Posts
{
get;
internal set;
}
public HttpResponseMessage HttpResponse
{
get;
private set;
}
#endregion
#region Fields
public AsyncLock ItemsLock;
#endregion
}
}<file_sep>/Win8/Craigslist8X/CraigslistApi/Post.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Data.Html;
using Windows.Data.Xml.Dom;
using Windows.UI.Core;
using Windows.UI.Xaml.Media;
using HtmlAgilityPack;
using WB.SDK;
using WB.SDK.Logging;
namespace WB.CraigslistApi
{
public class Post
{
public Post()
{
this._detailStatusLock = new object();
this.PostText = string.Empty;
this.Images = new List<Uri>();
this.Pictures = new List<Uri>();
this.DetailStatus = PostDetailStatus.NotLoaded;
}
#region Serialization
public static string Serialize(Post p)
{
return string.Format("<p><url>{0}</url><title>{1}</title><date>{2}</date><tn>{3}</tn><loc>{4}</loc><price>{5}</price><pic>{6}</pic><img>{7}</img></p>",
Uri.EscapeDataString(p.Url.ToString()),
Uri.EscapeDataString(p.Title ?? string.Empty),
Uri.EscapeDataString(p.ShortDate ?? string.Empty),
Uri.EscapeDataString(p.ThumbnailUri == null ? string.Empty : p.ThumbnailUri.ToString()),
Uri.EscapeDataString(p.Location ?? string.Empty),
p.Price,
p.HasPictures,
p.HasImages);
}
public static Post Deserialize(string q)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(q);
Post post = new Post();
post.Url = new Uri(Uri.UnescapeDataString(doc.SelectSingleNode("p/url").InnerText));
post.Title = Uri.UnescapeDataString(doc.SelectSingleNode("p/title").InnerText);
post.ShortDate = Uri.UnescapeDataString(doc.SelectSingleNode("p/date").InnerText);
post.Location = Uri.UnescapeDataString(doc.SelectSingleNode("p/loc").InnerText);
post.Price = int.Parse(doc.SelectSingleNode("p/price").InnerText);
post.HasPictures = bool.Parse(doc.SelectSingleNode("p/pic").InnerText);
post.HasImages = bool.Parse(doc.SelectSingleNode("p/img").InnerText);
if (!string.IsNullOrEmpty(doc.SelectSingleNode("p/tn").InnerText))
post.ThumbnailUri = new Uri(Uri.UnescapeDataString(doc.SelectSingleNode("p/tn").InnerText));
return post;
}
#endregion
#region Parsing
public event EventHandler DetailsLoaded;
internal void Parse(QueryResult qr, HtmlNode row, string shortDate)
{
this.QueryResult = qr;
// Parse map coordinates
if (row.Attributes["data-latitude"] != null && row.Attributes["data-longitude"] != null)
{
Coordinate coordinates;
double value;
if (double.TryParse(row.Attributes["data-latitude"].Value, out value))
{
coordinates.Latitude = value;
}
if (double.TryParse(row.Attributes["data-longitude"].Value, out value))
{
coordinates.Longitude = value;
}
}
// Try to find the right link that contains the title
var links = (from pl in row.Descendants("span").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("pl"))
from anchor in pl.Descendants("a").Where(x => x.Attributes["href"] != null)
select anchor);
if (links == null || links.Count() < 1)
links = (from anchor in row.Descendants("a").Where(x => x.Attributes["href"] != null) select anchor);
foreach (var link in links)
{
Regex postLink = new Regex(@"\d+\.html?$");
if (postLink.IsMatch(link.Attributes["href"].Value))
{
this.Title = Utilities.HtmlToText(link.InnerText);
Uri url = null;
if (Uri.TryCreate(link.Attributes["href"].Value, UriKind.Absolute, out url))
{
this.Url = url;
}
else if (Uri.TryCreate(
string.Format("{0}://{1}{2}",
qr.HttpResponse.RequestMessage.RequestUri.Scheme,
qr.HttpResponse.RequestMessage.RequestUri.Host,
link.Attributes["href"].Value), UriKind.Absolute,
out url))
{
this.Url = url;
}
break;
}
}
var itemi = (from a in row.Descendants("a").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("i") && x.Attributes["data-id"] != null) select a).FirstOrDefault();
if (itemi != null)
{
var dataId = itemi.Attributes["data-id"].Value;
if (dataId.StartsWith("0:", StringComparison.OrdinalIgnoreCase))
ThumbnailUri = new Uri(string.Format("http://images.craigslist.org/{0}_50x50c.jpg", dataId.Substring(2)));
else
ThumbnailUri = new Uri(string.Format("http://images.craigslist.org/medium/{0}", itemi.Attributes["data-id"].Value));
}
var itemdate = (from span in row.Descendants("span").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("date")) select span).FirstOrDefault();
if (itemdate != null)
{
this.ShortDate = shortDate;
if (string.IsNullOrEmpty(this.ShortDate) && itemdate != null)
this.ShortDate = itemdate.InnerText.TrimStart(' ');
}
var itemcg = (from a in row.Descendants("a").Where(x => x.Attributes["class"] != null && x.Attributes["data-cat"] != null && x.Attributes["class"].Value.Contains("gc")) select a).FirstOrDefault();
if (itemcg != null)
{
this.CategoryCode = itemcg.Attributes["data-cat"].Value;
}
var itempx = (from span in row.Descendants("span").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("px")) select span).FirstOrDefault();
if (itempx != null)
{
this.HasImages = itempx.InnerText.Contains("img");
this.HasPictures = new Regex("(pic)|(Photo)").IsMatch(itempx.InnerText);
this.HasMap = itempx.InnerText.Contains("map");
#if DEBUG
if (!string.IsNullOrWhiteSpace(itempx.InnerText) && !this.HasImages && !this.HasPictures)
{
Logger.LogMessage("Post", "We found a non empty itempx span, but we did not set HasImages or HasPictures to true. Different language?");
}
#endif
}
var itempn = (from span in row.Descendants("span").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("pnr"))
from small in span.Descendants("small")
select small).FirstOrDefault();
if (itempn != null)
{
var location = itempn.InnerText;
if (location.StartsWith(" (") && location.EndsWith(")"))
this.Location = location.Substring(2, location.Length - 3);
else
this.Location = location;
}
var itempp = (from span in row.Descendants("span").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("price")) select span).FirstOrDefault();
if (itempp != null)
{
Regex price = new Regex(@"^\$|($)(\d+)$");
Match m = price.Match(itempp.InnerText);
if (m.Success)
int.TryParse(m.Groups[2].Value, out this._price);
}
var itemph = (from span in row.Descendants("span").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("ph")) select span).FirstOrDefault();
if (itemph != null)
{
Regex price = new Regex(@"\$(\d*)");
Match m = price.Match(itemph.InnerText);
if (m.Success)
int.TryParse(m.Groups[1].Value, out this._price);
// TODO: Parse other housing specific info (bedrooms, etc)
}
}
public async Task LoadDetailsAsync()
{
// Prevent someone from trying to load details multiple times for the same post
if (this.DetailStatus == PostDetailStatus.Loaded || this.DetailStatus == PostDetailStatus.Loading)
{
await Logger.AssertNotReached("Trying to reload Post details.");
return;
}
this.DetailStatus = PostDetailStatus.Loading;
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(this.Url))
{
if (response != null && response.IsSuccessStatusCode)
{
await this.ParseDetails(await response.Content.ReadAsStringAsync());
this.DetailStatus = PostDetailStatus.Loaded;
}
else
{
if (response == null)
Logger.LogMessage("CraigslistApi", "Post.LoadDetailsAsync failed to get response from '{0}'", this.Url);
else
Logger.LogMessage("CraigslistApi", "Received non-succcess status code: {0}", response.StatusCode);
this.DetailStatus = PostDetailStatus.Failed;
}
}
}
catch (Exception ex)
{
Logger.LogException(ex);
this.DetailStatus = PostDetailStatus.Failed;
}
if (this.DetailsLoaded != null)
this.DetailsLoaded(this, null);
}
private async Task ParseDetails(string content)
{
await Task.Factory.StartNew(async () =>
{
using (new MonitoredScope("Parsing Post detail: {0}", this.Url))
{
HtmlDocument html = new HtmlDocument();
html.LoadHtml(content);
var userBody =
(from userbody in html.DocumentNode.Descendants().Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "userbody" || x.Id != null && x.Id == "userbody")
select userbody).FirstOrDefault();
if (userBody != null)
{
var removed = (from div in html.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "removed")
select div).FirstOrDefault();
if (removed != null)
{
this.UserHtml = removed.InnerHtml;
this.PostText = HtmlUtilities.ConvertToText(this.UserHtml);
return;
}
var postingBody = (from body in html.DocumentNode.Descendants("section").Where(x => x.Id == "postingbody") select body).FirstOrDefault();
if (postingBody == null)
{
await Logger.AssertNotReached("No body?");
return;
}
if (this.HasMap)
{
var leaflet = (from div in html.DocumentNode.Descendants("div").Where(x => x.Id == "leaflet") select div).FirstOrDefault();
if (leaflet != null && leaflet.Attributes.Contains("data-latitude") && leaflet.Attributes.Contains("data-longitude"))
{
Coordinate coords = new Coordinate();
coords.Latitude = double.Parse(leaflet.Attributes["data-latitude"].Value);
coords.Longitude = double.Parse(leaflet.Attributes["data-longitude"].Value);
this.MapCoordinate = coords;
}
}
this.UserHtml = postingBody.InnerHtml;
var blurbs = (from tags in html.DocumentNode.Descendants("ul").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "blurbs")
select tags).FirstOrDefault();
if (blurbs != null)
{
this.UserHtml += "<br/>" + blurbs.InnerHtml;
}
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(string.Format("{0}://{1}/reply/{2}", this.Url.Scheme, this.Url.Host, this.ID)))
{
if (response != null && response.IsSuccessStatusCode)
{
var replyText = await response.Content.ReadAsStringAsync();
HtmlDocument replyDom = new HtmlDocument();
replyDom.LoadHtml(replyText);
Regex phoneRegex = new Regex(@"\(?(\d{3})\)?\s?[\-\.]?\s?(\d{3})\s?[\-\.]?\s?(\d{4})");
Match match = phoneRegex.Match(replyText);
if (match.Success)
{
this.Phone = string.Format("{0}-{1}-{2}", match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value);
}
var email = (from mailto in replyDom.DocumentNode.Descendants("a").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value.Contains("mailto"))
select mailto).FirstOrDefault();
if (email != null)
{
this.Email = email.InnerText.Trim();
}
}
}
if (string.IsNullOrEmpty(this.Phone))
{
Regex phoneRegex = new Regex(@"\(?(\d{3})\)?\s?[\-\.]?\s?(\d{3})\s?[\-\.]?\s?(\d{4})");
Match match = phoneRegex.Match(this.UserHtml);
if (match.Success)
{
this.Phone = string.Format("{0}-{1}-{2}", match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value);
}
}
var dateNode = (from div in html.DocumentNode.Descendants("p").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "postinginfo")
from d in div.Descendants("date")
select d).FirstOrDefault();
if (dateNode != null)
{
string date = dateNode.InnerText;
date = date.Contains("AM") ? date.Substring(0, date.IndexOf("AM") + 2) : date;
date = date.Contains("PM") ? date.Substring(0, date.IndexOf("PM") + 2) : date;
this.Timestamp = DateTime.Parse(date);
}
var postingInfos = (from div in html.DocumentNode.Descendants("div").Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "postinginfos") select div).FirstOrDefault();
if (postingInfos != null)
{
postingInfos.Remove();
}
// Get the short body description. Basically a text dump with no images or layout.
Regex descriptionRegex = new Regex(@"(\s){3,}");
this.PostText = HtmlUtilities.ConvertToText(this.UserHtml);
this.PostText = descriptionRegex.Replace(this.PostText, "\r\n\r\n").Trim();
this.ParseImages(userBody);
}
else
{
// node = html.FindNode(new Regex(@"(This posting has been deleted by its author\.)|(This posting has been flagged for removal\.)"));
this.UserHtml = string.Empty;
this.IsDeleted = true;
}
}
},
CancellationToken.None
);
}
private void ParseImages(HtmlNode userBody)
{
// Get all the images in the post
if (this.HasImages)
{
var imgs = (from img in userBody.Descendants("img").Where(x => x.Attributes["src"] != null) select img);
this.Images.Clear();
foreach (var img in imgs)
{
this.Images.Add(new Uri(img.Attributes["src"].Value));
}
}
// Get the pictures. Pics are those images at the bottom of a post that are part of a lightbox type control.
if (this.HasPictures)
{
var thumbs = (from th in userBody.Descendants("div").Where(x => x.Id == "thumbs") select th).FirstOrDefault();
// On 1/17/2013 Craigslist pushed out an update that messes up image parsing. We now have two potential ways of getting images.
if (thumbs != null)
{
var pics = (from tn in thumbs.Descendants("a") select tn);
this.Pictures.Clear();
foreach (var pic in pics)
{
this.Pictures.Add(new Uri(pic.Attributes["href"].Value));
}
}
else
{
var pics = (from ci in userBody.Descendants("div").Where(x => x.Attributes["id"] != null && x.Attributes["id"].Value == "ci")
from img in ci.Descendants("img").Where(x => x.Attributes["src"] != null)
select img);
this.Pictures.Clear();
foreach (var pic in pics)
{
this.Pictures.Add(new Uri(pic.Attributes["src"].Value));
}
}
}
// There is no thumbnail, so we try just grab any image we can from the post and hopefully
// it is useful
if (this.ThumbnailUri == null)
{
if (this.HasPictures && this.Pictures.Any())
this.ThumbnailUri = this.Pictures.First();
else if (this.HasImages && this.Images.Any())
this.ThumbnailUri = this.Images.First();
}
}
#endregion
#region Listing Properties
public bool IsDeleted
{
get;
private set;
}
public Uri Url
{
get;
private set;
}
public string Title
{
get;
private set;
}
public Uri ThumbnailUri
{
get;
private set;
}
public string Location
{
get;
private set;
}
public string ShortDate
{
get;
private set;
}
public int Price
{
get
{
return _price;
}
set
{
_price = value;
}
}
public bool HasPictures
{
get;
private set;
}
public bool HasImages
{
get;
private set;
}
public bool HasMap
{
get;
private set;
}
public ulong ID
{
get
{
if (this.Url != null)
{
Regex idMatch = new Regex(@".*/(\d*)\.html$");
Match match = idMatch.Match(this.Url.ToString());
if (match.Success)
{
return ulong.Parse(match.Groups[1].Value);
}
}
return 0;
}
}
#endregion
#region Detail Properties
public DateTime Timestamp
{
get;
private set;
}
public string Email
{
get;
private set;
}
public string Phone
{
get;
private set;
}
public string UserHtml
{
get;
private set;
}
public string PostText
{
get;
private set;
}
public PostDetailStatus DetailStatus
{
get
{
lock (_detailStatusLock)
{
return _detailStatus;
}
}
set
{
lock (_detailStatusLock)
{
_detailStatus = value;
}
}
}
public QueryResult QueryResult
{
get;
private set;
}
public string CategoryCode
{
get;
private set;
}
public List<Uri> Images
{
get;
private set;
}
public List<Uri> Pictures
{
get;
set;
}
public Coordinate MapCoordinate
{
get;
private set;
}
#endregion
#region Fields
int _price;
object _detailStatusLock;
volatile PostDetailStatus _detailStatus;
#endregion
#region Constants
public enum PostDetailStatus
{
NotLoaded,
Loading,
Loaded,
Failed,
}
#endregion
public struct Coordinate
{
public double Latitude;
public double Longitude;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/SearchResultsPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Callisto.Controls;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class SearchResultsPanel : UserControl, IPanel, IPostList, IWebViewHost
{
public SearchResultsPanel()
{
this.InitializeComponent();
this.SetView(Settings.Instance.ExpandSearchResults ? View.Grid : View.List);
}
#region IPanel
public async Task AttachContext(object context, IPanel parent)
{
if (context is QueryBatch)
{
await this.ExecuteQuery(context as QueryBatch);
}
else if (context is SavedQuery)
{
// If this is a saved query, there a few extra steps we need to take:
// 1. Make sure we default to the city the user saved the query as.
// 2. Update notifications to 0
// 3. Update cached time
this._sq = (SavedQuery)context;
List<CraigCity> cities = CityManager.Instance.SearchCities.ToList();
cities.Remove(this._sq.Query.City);
cities.Insert(0, this._sq.Query.City);
QueryBatch qb = QueryBatch.BuildQueryBatch(cities, this._sq.Query);
await this.ExecuteQuery(qb, this._sq);
// Reset the notification counter and save the file
if (this._vm.QuerySucceeded)
{
this._sq.Notifications = 0;
DateTime time = DateTime.Now;
if (this._vm.PostItems.Where(x => x.Type == PostBase.PostType.Post).Any())
{
PostVM vm = (this._vm.PostItems.Where(x => x.Type == PostBase.PostType.Post).First() as PostVM) as PostVM;
await vm.LoadDetailsAsync();
if (vm.DetailStatus == Post.PostDetailStatus.Loaded)
{
time = vm.Post.Timestamp;
}
}
this._sq.CacheDate = time > this._sq.RssNewDate ? time : this._sq.RssNewDate;
// Save the list
var s = SavedSearches.Instance.SaveAsync();
var n = SavedSearches.Instance.SaveNotificationsAsync();
}
}
else
{
await Logger.AssertNotReached("Unrecognized search context");
}
}
#endregion
#region IPostList
public void SetSelection(PostVM post)
{
if (post != null)
{
if (this._selected != null)
{
this._selected.Selected = false;
}
this._selected = post;
this._selected.Selected = true;
this.SearchItemsList.ScrollIntoView(this._selected);
this.SearchItemsGrid.ScrollIntoView(this._selected);
}
}
public ObservableCollection<PostBase> PostItems
{
get
{
if (this._vm == null)
return null;
return this._vm.PostItems;
}
}
#endregion
#region IWebViewHost
public void ToggleWebView(bool visible)
{
if (!visible)
AdBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
else
AdBar.Visibility = App.IsPro ? Windows.UI.Xaml.Visibility.Collapsed : Windows.UI.Xaml.Visibility.Visible;
}
#endregion
#region Query Execution
public async Task ExecuteQuery(QueryBatch qb, SavedQuery sq = null)
{
if (qb == null)
{
await Logger.AssertNotReached("why is the querybatch null?");
return;
}
this.SearchProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
this.NoResultsMessageList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.NoResultsMessageGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
SearchResultsVM oldvm = this._vm;
this._qb = qb;
this._vm = new SearchResultsVM(this._qb);
this.DataContext = this._vm;
if (oldvm != null)
{
this._vm.SelectedCity = oldvm.SelectedCity;
}
this.SearchTitle.Text = this._vm.SearchTitle;
this.FilterButton.IsChecked = this._vm.FiltersSet;
this.SortButton.IsChecked = this._vm.SortSet;
this._vm.QueryExecuted += SearchQueryExecuted;
if (!WinRTXamlToolkit.Net.WebHelper.IsConnectedToInternet())
{
this.SetResultMessage(NotReachedCraigslist);
this.SearchProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
return;
}
this._tokenSource = new CancellationTokenSource();
await this._vm.ExecuteQueryAsync(this._tokenSource.Token);
if (sq != null && this._vm.PostItems.Where(x => x.Type == PostBase.PostType.Post).Any())
{
PostVM vm = (this._vm.PostItems.Where(x => x.Type == PostBase.PostType.Post).First() as PostVM) as PostVM;
vm.DetailsLoaded += PostVM_DetailsLoaded;
await vm.LoadDetailsAsync();
if (vm.DetailStatus == Post.PostDetailStatus.Loaded)
{
this.PostVM_DetailsLoaded(vm, Post.PostDetailStatus.Loaded);
}
}
}
public void CancelExecution()
{
if (this._tokenSource != null && this.DataContext != null)
this._tokenSource.Cancel();
}
private void PostVM_DetailsLoaded(object sender, Post.PostDetailStatus e)
{
PostVM vm = sender as PostVM;
if (DateTime.Compare(vm.Post.Timestamp, DateTime.Now.Subtract(TimeSpan.FromMinutes(20))) < 1)
{
DateTime recent = DateTime.Now.Subtract(TimeSpan.FromMinutes(15));
this._sq.CacheDate = recent > this._sq.RssNewDate ? recent : this._sq.RssNewDate;
}
else
{
this._sq.CacheDate = vm.Post.Timestamp > this._sq.RssNewDate ? vm.Post.Timestamp : this._sq.RssNewDate;
}
}
private async void SearchQueryExecuted(object sender, EventArgs e)
{
this._vm.QueryExecuted -= SearchQueryExecuted;
this.SearchProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
// Handle no connectivity
if (this.SetNoConnectivityMessage())
return;
// Handle no results found
if (this.SetNotFoundMessage(this._vm.SelectedCity))
return;
// Handle auto selecting in listview
if (this._currentView == View.List)
{
foreach (var post in this._vm.PostItems)
{
if (post.Type == PostBase.PostType.Post)
{
await this.SelectItem(post as PostVM);
break;
}
}
}
}
#endregion
#region Header Buttons
private async void LoadMoreItems_Tapped(object sender, TappedRoutedEventArgs e)
{
LoadMorePostsVM vm = (sender as FrameworkElement).DataContext as LoadMorePostsVM;
vm.LoadingMoreItems = true;
await vm.QueryResultVM.LoadMoreResults();
vm.LoadingMoreItems = false;
}
private async void SortButton_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
this.SortButton.IsChecked = this._vm.SortSet;
if (!this._vm.FiltersSet)
{
await new MessageDialog("Sorting requires at least one filter to be set. Please set any filter or search query and try again.", "Craigslist 8X").ShowAsync();
return;
}
MainPage.Instance.ToggleWebView(show: false);
PopupMenu menu = new PopupMenu();
menu.Commands.Add(new UICommand() { Label = "Most Recent", Id = Query.SortOrder.Recent });
menu.Commands.Add(new UICommand() { Label = "Best Match", Id = Query.SortOrder.Match });
menu.Commands.Add(new UICommand() { Label = "Low Price", Id = Query.SortOrder.LowPrice });
menu.Commands.Add(new UICommand() { Label = "High Price", Id = Query.SortOrder.HighPrice });
var result = await menu.ShowForSelectionAsync(WB.Craigslist8X.Common.Utilities.GetElementRect(sender as FrameworkElement), Placement.Below);
MainPage.Instance.ToggleWebView(show: true);
if (result == null)
return;
Query first = this._qb.Queries.First();
if (first.Sort != (Query.SortOrder)result.Id)
{
Query template = first.Clone();
template.Sort = (Query.SortOrder)result.Id;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
if (this._vm.PostItems != null && this._vm.PostItems.Any())
{
this.SearchItemsGrid.ScrollIntoView(this._vm.PostItems.First());
this.SearchItemsList.ScrollIntoView(this._vm.PostItems.First());
}
await this.ExecuteQuery(qb);
}
}
private void FilterButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.FilterButton.IsChecked = this._vm.FiltersSet;
MainPage.Instance.ToggleWebView(show: false);
Flyout flyout = new Flyout();
FiltersContainer filters = new FiltersContainer();
filters.AttachContext(this._vm.FirstQuery);
flyout.Content = filters;
flyout.PlacementTarget = FilterButton;
flyout.Placement = PlacementMode.Bottom;
flyout.IsOpen = true;
flyout.Closed += Filters_Closed;
}
private async void MoreOptionsButton_Tapped(object sender, TappedRoutedEventArgs e)
{
MainPage.Instance.ToggleWebView(show: false);
PopupMenu menu = new PopupMenu();
menu.Commands.Add(new UICommand() { Label = "Save Search", Id = 0 });
menu.Commands.Add(new UICommand() { Label = "Refresh", Id = 1 });
var result = await menu.ShowForSelectionAsync(WB.Craigslist8X.Common.Utilities.GetElementRect(sender as FrameworkElement), Placement.Below);
MainPage.Instance.ToggleWebView(show: true);
if (result == null)
{
return;
}
else if ((int)result.Id == 0)
{
this.ShowSaveSearch();
}
else if ((int)result.Id == 1)
{
await this.ExecuteQuery(this._qb);
}
else
{
await Logger.AssertNotReached("Unknown menu option");
}
}
private void ShowSaveSearch()
{
MainPage.Instance.ToggleWebView(show: false);
Flyout flyout = new Flyout();
SaveSearch saveSearch = new SaveSearch();
flyout.Content = saveSearch;
flyout.PlacementTarget = FilterButton;
flyout.Placement = PlacementMode.Bottom;
flyout.IsOpen = true;
flyout.Closed += SaveSearch_Closed;
}
private async void Filters_Closed(object sender, object e)
{
MainPage.Instance.ToggleWebView(show: true);
if (this._qb == null || this._qb.Queries == null || this._qb.Queries.Count < 1)
return;
Query first = this._qb.Queries.First();
Flyout flyout = sender as Flyout;
flyout.Closed -= Filters_Closed;
FiltersContainer filterDialog = flyout.Content as FiltersContainer;
QueryFilters filters;
if (first.Filters == null && filterDialog.Filters.ListItemsEqual(QueryFilter.GetFilters(first.Category)))
{
filters = null;
}
else
{
filters = new QueryFilters(filterDialog.Filters);
}
Query template = new Query(first.City, first.Category, filterDialog.SearchQuery, filters);
template.Type = filterDialog.TitlesOnly ? Query.QueryType.TitleOnly : Query.QueryType.EntirePost;
template.HasImage = filterDialog.HasPictures;
template.Sort = first.Sort;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
if (!first.Equals(template))
{
RecentlySearched.Instance.AddQuery(qb.Queries.First());
if (this._vm.PostItems != null && this._vm.PostItems.Any())
{
this.SearchItemsGrid.ScrollIntoView(this._vm.PostItems.First());
this.SearchItemsList.ScrollIntoView(this._vm.PostItems.First());
}
await this.ExecuteQuery(qb);
}
}
private async void SaveSearch_Closed(object sender, object e)
{
Flyout flyout = sender as Flyout;
SaveSearch saveSearch = flyout.Content as SaveSearch;
string name = saveSearch.SearchName;
if (string.IsNullOrEmpty(name))
return;
if (SavedSearches.Instance.Contains(name))
{
MessageDialog dlg = new MessageDialog("Sorry, you already have a saved search by that name. Try a different name.", "Craigslist 8X");
await dlg.ShowAsync();
return;
}
Query q = this._vm.FirstQuery.Clone();
q.City = this._vm.SelectedCity;
SavedQuery sq = new SavedQuery(q, name);
DateTime time = DateTime.Now;
if (this._vm.PostItems.Where(x => x.Type == PostBase.PostType.Post).Any())
{
PostVM vm = (this._vm.PostItems.Where(x => x.Type == PostBase.PostType.Post).First() as PostVM) as PostVM;
if (vm.DetailStatus == Post.PostDetailStatus.Loaded)
{
time = vm.Post.Timestamp;
}
}
sq.CacheDate = time;
SavedSearches.Instance.Add(sq);
Utilities.ExecuteNotification("Craigslist 8X", "Successfully saved search.");
}
private void ExpandViewButton_Tapped(object sender, TappedRoutedEventArgs e)
{
if (this._currentView == View.List)
{
this.SetView(View.Grid);
Settings.Instance.ExpandSearchResults = true;
}
else
{
this.SetView(View.List);
Settings.Instance.ExpandSearchResults = false;
}
}
#endregion
#region PanelView Fixes
private void SearchResultsBackground_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
// Prevent manipulation events from bubbling up from the gridview.
e.Handled = true;
}
private void SearchItemsList_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
ScrollViewer scroller = Utilities.GetVisualChild<ScrollViewer>(SearchItemsList);
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (scroller.VerticalOffset <= 2.01)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (scroller.VerticalOffset >= scroller.ExtentHeight - scroller.ViewportHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
#endregion
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count == 1)
{
if (this._vm.PostItems != null && this._vm.PostItems.Any())
{
this.SearchItemsList.ScrollIntoView(this._vm.PostItems.FirstOrDefault());
this.SearchItemsGrid.ScrollIntoView(this._vm.PostItems.FirstOrDefault());
}
// Handle no results found
if (this.SetNotFoundMessage(e.AddedItems[0] as CraigCity))
return;
}
}
private async Task SelectItem(PostVM post)
{
if (post != null)
{
await MainPage.Instance.ExecuteViewPost(this as UIElement, post);
this.SetSelection(post);
}
}
private async void SearchItem_Tapped(object sender, TappedRoutedEventArgs e)
{
FrameworkElement container = sender as FrameworkElement;
if (container != null && container.DataContext as PostVM != null)
{
if (this._currentView == View.Grid && this._vm.CollapseOnSelection)
{
this.SetView(View.List);
if (Settings.Instance.ShowExpandTip)
{
Flyout flyout = new Flyout();
flyout.Content = new ExpandTip();
flyout.Placement = PlacementMode.Top;
flyout.PlacementTarget = MainPage.Instance.MainMenu;
flyout.RenderTransform = new TranslateTransform() { Y = 65, X = -5 };
flyout.IsOpen = true;
Settings.Instance.ShowExpandTip = false;
}
}
await this.SelectItem((sender as FrameworkElement).DataContext as PostVM);
}
}
#region View / Messages
private void SetView(View view)
{
if (view == View.List)
{
this.ListViewResultsGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
this.GridViewResultsGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
MainPage.Instance.SetSearchResultsWidth(this, max: false);
MainPage.Instance.PanelView.SnapToPanel(this);
this.ExpandViewButton.IsChecked = false;
this.SearchItemsList.ScrollIntoView(this._selected);
}
else if (view == View.Grid)
{
this.ListViewResultsGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.GridViewResultsGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
MainPage.Instance.SetSearchResultsWidth(this, max: true);
MainPage.Instance.PanelView.SnapToPanel(this);
this.ExpandViewButton.IsChecked = true;
this.SearchItemsGrid.ScrollIntoView(this._selected);
}
this._currentView = view;
}
private bool SetNoConnectivityMessage()
{
if (!this._vm.QuerySucceeded)
{
this.SetResultMessage(NotReachedCraigslist);
return true;
}
return false;
}
private bool SetNotFoundMessage(CraigCity city)
{
QueryResultVM qr = this._vm.GetCityQueryResult(city);
if (qr == null)
{
return true;
}
if (qr.PostItems.Count < 1)
{
if (this._vm.FirstQuery.Mode == Query.SearchMode.Query)
{
this.SetResultMessage(string.Format(NoItemsFoundSearchFormat, qr.QueryResult.Query.Text, qr.QueryResult.Query.Category.Name, qr.QueryResult.Query.City.DisplayName));
}
else
{
this.SetResultMessage(string.Format(NoItemsFoundBrowseFormat, qr.QueryResult.Query.Category.Name, qr.QueryResult.Query.City.DisplayName));
}
return true;
}
else
{
NoResultsMessageGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
NoResultsMessageList.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
return false;
}
private void SetResultMessage(string message)
{
NoResultsMessageList.Visibility = Windows.UI.Xaml.Visibility.Visible;
NoResultsMessageList.Text = message;
NoResultsMessageGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
NoResultsMessageGrid.Text = message;
}
#endregion
#region Fields
SavedQuery _sq;
QueryBatch _qb;
SearchResultsVM _vm;
PostVM _selected;
CancellationTokenSource _tokenSource;
View _currentView;
#endregion
#region Constants
enum View
{
List,
Grid,
None,
}
const string NotReachedCraigslist = "Craigslist 8X is having trouble reaching Craigslist. Check your internet connection and try again.";
const string NoItemsFoundSearchFormat = @"No results found for ""{0}"" in the {1} category in {2}.
Please refine your query, try a different location or change your search category in settings.";
const string NoItemsFoundBrowseFormat = @"No results found in the {0} category in {1}.
Please refine your query, try a different location or change your search category in settings.";
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/ViewPostPanel.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.ApplicationModel.DataTransfer;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Storage.Streams;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media.Imaging;
using Callisto.Controls;
using Microsoft.Live;
using Newtonsoft.Json;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class ViewPostPanel : UserControl, IPanel, IWebViewHost
{
public ViewPostPanel()
{
this.InitializeComponent();
this.TogglePostNavBar(Settings.Instance.ShowPostNavBar);
}
#region IWebViewHost
public void ToggleWebView(bool visible)
{
// We only use the webview when there are images
if (this._post != null && this._post.Post.HasImages)
{
if (visible)
{
// Show the webview
PostWebView.Visibility = Windows.UI.Xaml.Visibility.Visible;
PostWebViewRect.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
else
{
WebViewBrush brush = new WebViewBrush();
brush.SourceName = "PostWebView";
brush.SetSource(PostWebView);
PostWebViewRect.Visibility = Windows.UI.Xaml.Visibility.Visible;
PostWebViewRect.Fill = brush;
PostWebView.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
}
#endregion
#region IPanel
public async Task AttachContext(object context, IPanel parent)
{
this.ExpandPostButton.IsChecked = Settings.Instance.ExpandPost;
// If the parent panel is not a list, then hide the previous and next buttons
this._parentList = parent as IPostList;
if (this._parentList == null)
{
this.PreviousPostBarButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.NextPostBarButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
await this.ShowPost(context as PostVM);
}
#endregion
public async Task ShowPost(PostVM post)
{
this._post = post;
this.DataContext = this._post;
RecentlyViewed.Instance.AddPost(this._post.Post);
await this.LoadPost();
}
public void HandleShare(DataRequest request)
{
request.Data.Properties.Title = this._post.Title;
request.Data.Properties.Description = this._post.ShortDescription;
request.Data.SetUri(new Uri(this._post.Url));
if (this._post.HasThumbnail)
{
request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromUri(this._post.Post.ThumbnailUri);
}
}
private async Task LoadPost()
{
this.ProgressBar.Visibility = Visibility.Visible;
PicturesGrid.ItemsSource = null;
if (this._post.Post.DetailStatus == CraigslistApi.Post.PostDetailStatus.NotLoaded)
{
await this._post.LoadDetailsAsync();
}
this._post.DetailsLoaded += DetailsLoaded;
if (this._post.DetailStatus == Post.PostDetailStatus.Loaded)
{
this.ShowContent();
this._post.DetailsLoaded -= DetailsLoaded;
}
else if (this._post.DetailStatus != Post.PostDetailStatus.Loading)
{
this.ShowLoadError();
}
}
private void DetailsLoaded(object sender, Post.PostDetailStatus e)
{
this.ShowContent();
this._post.DetailsLoaded -= DetailsLoaded;
}
private async void SaveToOneNote_Tapped(object sender, TappedRoutedEventArgs e)
{
var scopes = new string[] { "wl.signin", "wl.basic", "Office.onenote_create" };
var client = new LiveAuthClient();
var result = await client.InitializeAsync(scopes);
// We may already be connected without logging in (SSO)
if (result.Status != LiveConnectSessionStatus.Connected)
{
result = await client.LoginAsync(scopes);
}
if (result.Status != LiveConnectSessionStatus.Connected)
{
await new Windows.UI.Popups.MessageDialog("Could not login to your Microsoft Account.", "Authentication Failed").ShowAsync();
return;
}
using (var httpClient = new HttpClient())
{
bool success = true;
var img = new BitmapImage(new Uri("ms-appx:///Resources/OneNotePurple.png"));
SaveToOneNoteButton.IsChecked = true;
SaveToOneNoteButton.Content = new Image() { Source = img, Width = 36, Height = 36 };
var postBostText = string.Format(OneNotePostContent, this._post.Title, DateTime.UtcNow, this._post.Url);
var presentationPart = new StringContent(postBostText, System.Text.Encoding.UTF8, "application/xhtml+xml");
MultipartFormDataContent multipart = new MultipartFormDataContent("NewPart");
multipart.Add(presentationPart, "Presentation");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://www.onenote.com/api/v1.0/pages");
request.Content = multipart;
request.Headers.Add("Authorization", "Bearer " + result.Session.AccessToken);
try
{
var response = await httpClient.SendAsync(request);
if (response.StatusCode == HttpStatusCode.Created)
{
dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
ShowSaveToOneNoteToast(string.Format("Successfully finished saving '{0}' to OneNote", this._post.Title), responseObject.links.oneNoteWebUrl.href.ToString());
}
else
{
success = false;
ShowSaveToOneNoteToast(string.Format("Failed saving '{0}' to OneNote. Please try again.", this._post.Title));
}
}
catch (Exception)
{
success = false;
ShowSaveToOneNoteToast(string.Format("Failed saving '{0}' to OneNote. Please try again.", this._post.Title));
}
finally
{
SaveToOneNoteButton.IsChecked = success;
}
}
}
private void ShowSaveToOneNoteToast(string msg, string arg = null)
{
var template = ToastTemplateType.ToastText02;
var toastContent = ToastNotificationManager.GetTemplateContent(template);
toastContent.SelectSingleNode("/toast/visual/binding/text[@id='1']").InnerText = "Craigslist 8X";
toastContent.SelectSingleNode("/toast/visual/binding/text[@id='2']").InnerText = msg;
if (!string.IsNullOrEmpty(arg))
{
((XmlElement)toastContent.SelectSingleNode("/toast")).SetAttribute("launch",
string.Format("{{\"type\":\"toast\",\"clientUrl\":\"{0}\"}}", arg));
}
ToastNotification toast = new ToastNotification(toastContent);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
private void ToggleExpandPost_Tapped(object sender, TappedRoutedEventArgs e)
{
Settings.Instance.ExpandPost = !Settings.Instance.ExpandPost;
this.ExpandPostButton.IsChecked = Settings.Instance.ExpandPost;
MainPage.Instance.SetViewPostWidth(this);
MainPage.Instance.PanelView.SnapToPanel(this);
}
private void ToggleFavorite_Tapped(object sender, TappedRoutedEventArgs e)
{
this._post.Favorite = !this._post.Favorite;
}
private async void ShowDetails_Tapped(object sender, TappedRoutedEventArgs e)
{
await MainPage.Instance.ExecutePostDetails(this, this._post);
MainPage.Instance.SetViewPostWidth(this);
}
private void ShowContent()
{
this.ProgressBar.Visibility = Visibility.Collapsed;
this.TitleHeader.Text = this._post.Title;
this.PostWebView.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.PostTextView.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
// If we have rich context (read: img tags) in the post, then we use the WebView control to display the content.
// otherwise
if (this._post.HasImages)
{
PostWebView.Visibility = Visibility.Visible;
PostWebView.NavigateToString(this._post.UserHtml);
}
else
{
PostTextView.Visibility = Visibility.Visible;
PostTextView.Text = this._post.ShortDescription ?? string.Empty;
}
if (this._post.HasPictures)
{
PicturesGrid.ItemsSource = this._post.Pictures;
}
}
private void ShowLoadError()
{
Logger.LogMessage("ViewPostPanel", "Failed to load post details: {0}", this._post.Post.Url);
this.ProgressBar.Visibility = Visibility.Collapsed;
this.TitleHeader.Text = this._post.Title;
this.PostTextView.Visibility = Visibility.Visible;
this.PostTextView.Text = "We encountered an error while trying to load the post. Please check your network connectivity and try again.";
this.PostTextView.FontSize = 24;
this.PostWebView.MaxWidth = this.Width;
this.PicturesGrid.Visibility = Visibility.Collapsed;
}
#region Post Flagging
private void FlagPost_Tapped(object sender, TappedRoutedEventArgs e)
{
MenuItem mmi = new MenuItem() { Text = "Miscategorized", CommandParameter = FlagCode.Miscategorized };
MenuItem pmi = new MenuItem() { Text = "Prohibited", CommandParameter = FlagCode.Prohibited };
MenuItem smi = new MenuItem() { Text = "Spam / Overpost", CommandParameter = FlagCode.Spam };
MenuItem bmi = new MenuItem() { Text = "Best of Craigslist", CommandParameter = FlagCode.BestOf };
mmi.Tapped += FlagMenuItem_Tapped;
pmi.Tapped += FlagMenuItem_Tapped;
smi.Tapped += FlagMenuItem_Tapped;
bmi.Tapped += FlagMenuItem_Tapped;
Menu menu = new Menu();
menu.Items.Add(mmi);
menu.Items.Add(pmi);
menu.Items.Add(smi);
menu.Items.Add(bmi);
// Hide the webview and use the brush
MainPage.Instance.ToggleWebView(false);
Flyout flyout = new Flyout();
flyout.PlacementTarget = FlagPostButton;
flyout.Placement = PlacementMode.Bottom;
flyout.Content = menu;
flyout.IsOpen = true;
flyout.Closed += (a, b) => { MainPage.Instance.ToggleWebView(true); };
}
private async void FlagMenuItem_Tapped(object sender, TappedRoutedEventArgs e)
{
MenuItem mi = sender as MenuItem;
if (mi != null && mi.CommandParameter is FlagCode)
{
FlagCode code = (FlagCode)mi.CommandParameter;
string name = code.ToString();
switch (code)
{
case FlagCode.BestOf:
name = "Best of Craigslist";
break;
case FlagCode.Miscategorized:
name = "Miscategorized";
break;
case FlagCode.Prohibited:
name = "Prohibited";
break;
case FlagCode.Spam:
name = "Spam / Overpost";
break;
default:
await Logger.AssertNotReached("Unknown flag code");
break;
}
if (await Craigslist.Instance.FlagPost(this._post.Post, code))
{
Utilities.ExecuteNotification("Craigslist 8X", string.Format("Successfully flagged post as: {0}", name));
}
else
{
Utilities.ExecuteNotification("Craigslist 8X", string.Format("An error occurred trying to flag post as: {0}", name));
}
}
}
#endregion
#region Full screen image
private void Image_Tapped(object sender, TappedRoutedEventArgs e)
{
MainPage.Instance.ToggleWebView(show: false);
List<BitmapImage> images = (from x in this._post.Pictures select new BitmapImage(x)).ToList();
FlipView flipView = new FlipView();
flipView.ItemsSource = images;
flipView.SelectedItem = images[PicturesGrid.Items.IndexOf(new Uri((sender as FrameworkElement).DataContext as string))];
flipView.ItemTemplate = this.Resources["FlipItemTemplate"] as DataTemplate;
flipView.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
flipView.MaxWidth = CoreApplication.MainView.CoreWindow.Bounds.Width;
flipView.MaxHeight = CoreApplication.MainView.CoreWindow.Bounds.Height;
flipView.Tapped += FlipView_Tapped;
Canvas sp = new Canvas();
sp.Width = CoreApplication.MainView.CoreWindow.Bounds.Width;
sp.Height = CoreApplication.MainView.CoreWindow.Bounds.Height;
sp.Background = new Windows.UI.Xaml.Media.SolidColorBrush(new Windows.UI.Color() { A = 225, R = 0, G = 0, B = 0 });
sp.Children.Add(flipView);
Popup popup = new Popup();
popup.HorizontalAlignment = HorizontalAlignment.Center;
popup.VerticalAlignment = VerticalAlignment.Center;
popup.Child = sp;
popup.Width = CoreApplication.MainView.CoreWindow.Bounds.Width;
popup.Height = CoreApplication.MainView.CoreWindow.Bounds.Height;
popup.IsLightDismissEnabled = true;
popup.HorizontalOffset = 0;
popup.VerticalOffset = 0;
popup.IsOpen = true;
sp.Tapped += (s, x) =>
{
popup.IsOpen = false;
MainPage.Instance.ToggleWebView(show: true);
};
}
private void FlipView_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = e.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse
&& (e.OriginalSource is Border)
&& (e.OriginalSource as Border).Child is Windows.UI.Xaml.Shapes.Path;
}
private void FlipViewImage_Tapped(object sender, TappedRoutedEventArgs e)
{
e.Handled = true;
}
#endregion
#region Mouse / Touch Handling
private void PostTextView_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
{
this._verticalOffset = PostScroller.VerticalOffset;
}
private void PostTextView_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
// Calculate 27mm worth of pixels.
float pixels = Windows.Graphics.Display.DisplayProperties.LogicalDpi * 2.54f * 0.27f;
e.Handled = true;
if (this._translating != TranslateAxis.Y && (this._manipulating || Math.Abs(e.Cumulative.Translation.X) >= pixels))
{
this._manipulating = true;
this._translating = TranslateAxis.X;
MainPage.Instance.PanelView.PanelView_ManipulationDelta(sender, e);
}
else if (this._translating != TranslateAxis.X && Math.Abs(e.Cumulative.Translation.Y) >= pixels)
{
this.PostScroller.ScrollToVerticalOffset(_verticalOffset - e.Cumulative.Translation.Y);
this._translating = TranslateAxis.Y;
}
}
private void PostTextView_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
this._manipulating = false;
this._translating = TranslateAxis.None;
}
private void PostTextView_PointerWheelChanged(object sender, PointerRoutedEventArgs e)
{
int delta = e.GetCurrentPoint(null).Properties.MouseWheelDelta;
if (delta > 0)
{
if (PostScroller.VerticalOffset < 1)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
else if (delta < 0)
{
if (PostScroller.VerticalOffset >= PostScroller.ScrollableHeight)
{
MainPage.Instance.PanelView.PanelView_PointerWheelChanged(sender, e);
}
}
}
#endregion
#region Nav Bar
private void ShowPostNavBarButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.TogglePostNavBar(show: true);
}
private void HidePostNavBarButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this.TogglePostNavBar(show: false);
}
private void TogglePostNavBar(bool show)
{
if (show)
{
Settings.Instance.ShowPostNavBar = true;
PostNavBarGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
ShowPostNavBarButton.Visibility = Visibility.Collapsed;
HidePostNavBarButton.Visibility = Visibility.Visible;
}
else
{
Settings.Instance.ShowPostNavBar = false;
PostNavBarGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
ShowPostNavBarButton.Visibility = Visibility.Visible;
HidePostNavBarButton.Visibility = Visibility.Collapsed;
}
}
private async void ReloadPostButton_Tapped(object sender, TappedRoutedEventArgs e)
{
this._post.DetailStatus = Post.PostDetailStatus.NotLoaded;
await this.LoadPost();
}
private async void PreviousPostButton_Tapped(object sender, TappedRoutedEventArgs e)
{
await Logger.AssertNotNull(this._parentList, "This button should not be visible if there is no parentlist");
if (this._parentList == null)
return;
if (this._parentList.PostItems == null)
return;
int index = this._parentList.PostItems.IndexOf(this._post);
while (index > 0)
{
--index;
if (this._parentList.PostItems[index] is PostVM)
{
this._parentList.SetSelection(this._parentList.PostItems[index] as PostVM);
await this.ShowPost(this._parentList.PostItems[index] as PostVM);
MainPage.Instance.RemoveChildPanels(this);
return;
}
}
Utilities.ExecuteNotification("Craigslist 8X", "You have reached the beginning of the list.");
}
private async void NextPostButton_Tapped(object sender, TappedRoutedEventArgs e)
{
await Logger.AssertNotNull(this._parentList, "This button should not be visible if there is no parentlist");
if (this._parentList == null)
return;
if (this._parentList.PostItems == null)
return;
int index = this._parentList.PostItems.IndexOf(this._post);
while (index < this._parentList.PostItems.Count - 1)
{
++index;
if (this._parentList.PostItems[index] is PostVM)
{
this._parentList.SetSelection(this._parentList.PostItems[index] as PostVM);
await this.ShowPost(this._parentList.PostItems[index] as PostVM);
MainPage.Instance.RemoveChildPanels(this);
return;
}
}
Utilities.ExecuteNotification("Craigslist 8X", "You have reached the end of the list.");
}
#endregion
PostVM _post;
bool _manipulating;
double _verticalOffset;
TranslateAxis _translating;
IPostList _parentList;
enum TranslateAxis
{
None,
X,
Y,
}
const string OneNotePostContent = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<html xmlns=""http://www.w3.org/1999/xhtml"" lang=""en-us"">
<head>
<title>{0}</title>
<meta name=""created"" content=""{1}""/>
</head>
<body>
From <<a href=""{2}"">{2}</a>>
<br/>
<img data-render-src=""{2}"" alt=""Craigslist Post"" />
</body>
<html>";
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/IStorageBacked.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WB.Craigslist8X.Model
{
interface IStorageBacked
{
Task<bool> LoadAsync();
Task<bool> SaveAsync();
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/Craigslist8XData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.Storage;
using Windows.UI.Popups;
using Callisto.Controls;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.View;
using WB.SDK.Logging;
namespace WB.Craigslist8X.Model
{
public static class Craigslist8XData
{
static Craigslist8XData()
{
_dataLock = new AsyncLock();
}
/// <summary>
/// Initialize Craigslist8X data
/// </summary>
/// <returns>True if Craigslist8X data was loaded. False if data was already loaded.</returns>
public static async Task<bool> LoadAsync()
{
if (Loaded)
{
return false; // Craigslist8X is already initialized
}
using (new MonitoredScope("Loading Craigslist8XData"))
{
using (await _dataLock.LockAsync())
{
await CategoryManager.Instance.LoadAsync();
await CityManager.Instance.LoadAsync();
await RecentlyViewed.Instance.LoadAsync();
await FavoritePosts.Instance.LoadAsync();
await RecentlySearched.Instance.LoadAsync();
await SavedSearches.Instance.LoadAsync();
await UserAccounts.Instance.LoadAsync();
}
++Settings.Instance.AppBootCount;
Loaded = true;
}
return Loaded;
}
public static async Task SaveAsync()
{
using (new LoggerGroup("Saving Craigslist8XData"))
{
using (await _dataLock.LockAsync())
{
await RecentlyViewed.Instance.SaveAsync();
await FavoritePosts.Instance.SaveAsync();
await RecentlySearched.Instance.SaveAsync();
await SavedSearches.Instance.SaveAsync();
await UserAccounts.Instance.SaveAsync();
}
}
}
#region Properties
public static Geoposition Location
{
get;
set;
}
public static bool Loaded
{
get;
private set;
}
#endregion
static AsyncLock _dataLock;
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/QueryFilters.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using WB.SDK;
using WB.SDK.Logging;
namespace WB.CraigslistApi
{
public static class QueryFilterExtensions
{
public static bool ListItemsEqual<T>(this List<T> source, List<T> target) where T : IEquatable<T>
{
// If both are null that is ok, but if only one of the lists is null.
if (source == null && target == null)
return true;
if (source == null || target == null)
return false;
foreach (var filter in source)
{
if (!target.Contains(filter))
return false;
}
return true;
}
public static List<T> CloneList<T>(this List<T> source) where T : ICloneable<T>
{
if (source == null)
throw new ArgumentNullException("source");
return (from x in source select x.Clone()).ToList();
}
}
public abstract class QueryFilter : ICloneable<QueryFilter>, IEquatable<QueryFilter>
{
public static QueryFilters GetFilters(Category category)
{
QueryFilters filters = new QueryFilters();
switch (category.Root)
{
case "community":
case "discussion forums":
case "resumes":
case "services":
break; // no filters
case "personals":
switch (category.Name)
{
case "rants and raves":
break;
default:
filters.Add(new QueryFilterNumeric("Minimum Age", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Age", "maxAsk"));
break;
}
break;
case "housing":
switch (category.Name)
{
case "rooms / shared":
filters.Add(new QueryFilterNumeric("Minimum Rent", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Rent", "maxAsk"));
filters.Add(new QueryFilterBoolean("Cats", "addTwo", "purrr", null));
filters.Add(new QueryFilterBoolean("Dogs", "addThree", "wooof", null));
break;
case "parking / storage":
filters.Add(new QueryFilterNumeric("Minimum Rent", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Rent", "maxAsk"));
break;
case "office / commercial":
filters.Add(new QueryFilterNumeric("Minimum Rent", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Rent", "maxAsk"));
filters.Add(new QueryFilterNumeric("Minimum Sq. Ft.", "minSqft"));
filters.Add(new QueryFilterNumeric("Maximum Sq. Ft.", "maxSqft"));
break;
case "real estate for sale":
filters.Add(new QueryFilterNumeric("Minimum Price", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Price", "maxAsk"));
filters.Add(new QueryFilterChooseOne("Rooms", "bedrooms",
new QueryFilterChooseOneItem { Label = "0+ BR", Value = null },
new QueryFilterChooseOneItem { Label = "1 BR", Value = "1" },
new QueryFilterChooseOneItem { Label = "2 BR", Value = "2" },
new QueryFilterChooseOneItem { Label = "3 BR", Value = "3" },
new QueryFilterChooseOneItem { Label = "4 BR", Value = "4" },
new QueryFilterChooseOneItem { Label = "5 BR", Value = "5" },
new QueryFilterChooseOneItem { Label = "6 BR", Value = "6" },
new QueryFilterChooseOneItem { Label = "7 BR", Value = "7" },
new QueryFilterChooseOneItem { Label = "8 BR", Value = "8" })
);
break;
default:
filters.Add(new QueryFilterNumeric("Minimum Rent", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Rent", "maxAsk"));
filters.Add(new QueryFilterBoolean("Cats", "addTwo", "purrr", null));
filters.Add(new QueryFilterBoolean("Dogs", "addThree", "wooof", null));
filters.Add(new QueryFilterChooseOne("Rooms", "bedrooms",
new QueryFilterChooseOneItem { Label = "0+ BR", Value = null },
new QueryFilterChooseOneItem { Label = "1 BR", Value = "1" },
new QueryFilterChooseOneItem { Label = "2 BR", Value = "2" },
new QueryFilterChooseOneItem { Label = "3 BR", Value = "3" },
new QueryFilterChooseOneItem { Label = "4 BR", Value = "4" },
new QueryFilterChooseOneItem { Label = "5 BR", Value = "5" },
new QueryFilterChooseOneItem { Label = "6 BR", Value = "6" },
new QueryFilterChooseOneItem { Label = "7 BR", Value = "7" },
new QueryFilterChooseOneItem { Label = "8 BR", Value = "8" })
);
break;
}
break;
case "for sale":
filters.Add(new QueryFilterNumeric("Minimum Price", "minAsk"));
filters.Add(new QueryFilterNumeric("Maximum Price", "maxAsk"));
break;
case "jobs":
filters.Add(new QueryFilterBoolean("Telecommute", "addOne", "telecommute", null));
filters.Add(new QueryFilterBoolean("Contract", "addTwo", "contract", null));
filters.Add(new QueryFilterBoolean("Internship", "addThree", "internship", null));
filters.Add(new QueryFilterBoolean("Part-time", "addFour", "part-time", null));
filters.Add(new QueryFilterBoolean("Non-profit", "addFive", "non-profit", null));
break;
case "gigs":
filters.Add(new QueryFilterChooseOne("Payed", "addThree",
new QueryFilterChooseOneItem { Label = "All", Value = string.Empty },
new QueryFilterChooseOneItem { Label = "Yes", Value = "forpay" },
new QueryFilterChooseOneItem { Label = "No", Value = "nopay" })
);
break;
default:
Logger.AssertNotReached("Unable to get filter list for category");
break;
}
return filters;
}
public static string Serialize(QueryFilter filter)
{
if (filter is QueryFilterBoolean)
{
QueryFilterBoolean qb = (QueryFilterBoolean)filter;
return string.Format("<qb><l>{0}</l><qf>{1}></qf><qvt>{2}</qvt><qvf>{3}</qvf><s>{4}</s></qb>",
qb.Label,
qb.QueryField,
qb.TrueValue,
qb.FalseValue,
qb.Selected
);
}
else if (filter is QueryFilterNumeric)
{
QueryFilterNumeric qn = (QueryFilterNumeric)filter;
return string.Format("<qn><l>{0}</l><qf>{1}</qf><v>{2}</v></qn>",
qn.Label,
qn.QueryField,
qn.Value
);
}
else if (filter is QueryFilterChooseOne)
{
QueryFilterChooseOne qc = (QueryFilterChooseOne)filter;
string values = string.Empty;
foreach (var qco in qc.Values)
{
values += string.Format(@"<vi sel=""{0}""><l>{1}</l><v>{2}</v></vi>", qc.Selected == qco, qco.Label, qco.Value);
}
return string.Format("<qc><l>{0}</l><qf>{1}</qf><vs>{2}</vs></qc>",
qc.Label,
qc.QueryField,
values
);
}
else
{
Logger.AssertNotReached("Unrecognized filter type");
}
return null;
}
public static QueryFilter Deserialize(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement xe = doc.DocumentElement;
if (xe.NodeName == "qn")
{
QueryFilterNumeric qn = new QueryFilterNumeric(xe.SelectSingleNode("l").InnerText,
xe.SelectSingleNode("qf").InnerText);
qn.Value = xe.SelectSingleNode("v").InnerText;
return qn;
}
else if (xe.NodeName == "qb")
{
QueryFilterBoolean qb = new QueryFilterBoolean(xe.SelectSingleNode("l").InnerText,
xe.SelectSingleNode("qf").InnerText,
xe.SelectSingleNode("qvt").InnerText,
xe.SelectSingleNode("qvf").InnerText);
qb.Selected = bool.Parse(xe.SelectSingleNode("s").InnerText);
return qb;
}
else if (xe.NodeName == "qc")
{
QueryFilterChooseOneItem selected = null;
List<QueryFilterChooseOneItem> values = new List<QueryFilterChooseOneItem>();
XmlNodeList vi = xe.SelectNodes("vs/vi");
foreach (var node in vi)
{
bool sel = false;
values.Add(new QueryFilterChooseOneItem() { Label = node.SelectSingleNode("l").InnerText, Value = node.SelectSingleNode("v").InnerText });
if (bool.TryParse(node.Attributes[0].InnerText, out sel) && sel)
{
selected = values[values.Count - 1];
}
}
QueryFilterChooseOne co = new QueryFilterChooseOne(xe.SelectSingleNode("l").InnerText,
xe.SelectSingleNode("qf").InnerText,
values.ToArray());
if (selected != null)
co.Selected = selected;
return co;
}
else
{
Logger.AssertNotReached("Unrecognized filter type");
}
return null;
}
public virtual bool Equals(QueryFilter o)
{
if (this.GetType() != o.GetType())
return false;
bool equals = true;
equals &= this.Type == o.Type;
equals &= this.Label == o.Label;
equals &= this.QueryField == o.QueryField;
return equals;
}
public abstract QueryFilter Clone();
public abstract string GetQueryField();
public FilterType Type
{
get;
protected set;
}
public string Label
{
get;
protected set;
}
public string QueryField
{
get;
protected set;
}
public enum FilterType
{
Numeric,
Boolean,
ChooseOne,
}
}
public class QueryFilters : List<QueryFilter>
{
public QueryFilters()
{
}
public QueryFilters(IEnumerable<QueryFilter> filters)
: this()
{
if (filters != null)
{
foreach (var f in filters)
{
this.Add(f);
}
}
}
public static string Serialize(QueryFilters qf)
{
if (qf == null)
return null;
StringBuilder sb = new StringBuilder();
foreach (var filter in qf)
{
sb.AppendLine(QueryFilter.Serialize(filter));
}
return string.Format("<qf>{0}</qf>", sb.ToString());
}
public static QueryFilters Deserialize(string xml)
{
if (string.IsNullOrEmpty(xml))
return null;
QueryFilters qf = new QueryFilters();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
if (doc.FirstChild.NodeName == "qf")
{
XmlNodeList nodes = doc.SelectNodes("qf/qn | qf/qb | qf/qc");
if (nodes != null)
{
foreach (var node in nodes)
{
qf.Add(QueryFilter.Deserialize(node.GetXml()));
}
}
return qf;
}
else
{
Logger.AssertNotReached("Unknown xml element");
}
return null;
}
public bool FiltersSet()
{
foreach (var filter in this)
{
if (filter is QueryFilterNumeric && !string.IsNullOrEmpty(((QueryFilterNumeric)filter).Value))
return true;
else if (filter is QueryFilterBoolean && ((QueryFilterBoolean)filter).Selected)
return true;
else if (filter is QueryFilterChooseOne && ((QueryFilterChooseOne)filter).Selected != ((QueryFilterChooseOne)filter).Values[0])
return true;
}
return false;
}
}
public class QueryFilterNumeric : QueryFilter
{
public QueryFilterNumeric(string label, string qf)
{
this.Type = QueryFilter.FilterType.Numeric;
this.Label = label;
this.QueryField = qf;
}
public override bool Equals(QueryFilter o)
{
bool equals = base.Equals(o);
if (!equals)
return false;
equals &= this.Value == (o as QueryFilterNumeric).Value;
return equals;
}
public override QueryFilter Clone()
{
return new QueryFilterNumeric(this.Label, this.QueryField) { Value = this.Value };
}
public override string GetQueryField()
{
return string.Format("{0}={1}", this.QueryField, this.Value);
}
public string Value
{
get;
set;
}
}
public class QueryFilterBoolean : QueryFilter
{
public QueryFilterBoolean(string label, string qf, string qvt, string qvf)
{
this.Type = QueryFilter.FilterType.Boolean;
this.Label = label;
this.QueryField = qf;
this._qvt = qvt;
this._qvf = qvf;
}
public override bool Equals(QueryFilter o)
{
bool equals = base.Equals(o);
if (!equals)
return false;
equals &= this.Selected == (o as QueryFilterBoolean).Selected;
return equals;
}
public override QueryFilter Clone()
{
return new QueryFilterBoolean(this.Label, this.QueryField, this._qvt, this._qvf) { Selected = this.Selected };
}
public override string GetQueryField()
{
return string.Format("{0}={1}", this.QueryField, this.Selected ? this._qvt : this._qvf);
}
public bool Selected
{
get;
set;
}
public string TrueValue
{
get
{
return this._qvt;
}
}
public string FalseValue
{
get
{
return this._qvf;
}
}
string _qvt;
string _qvf;
}
public class QueryFilterChooseOne : QueryFilter
{
public QueryFilterChooseOne(string label, string qf, params QueryFilterChooseOneItem[] values)
{
this.Type = FilterType.ChooseOne;
this.Label = label;
this.QueryField = qf;
Logger.Assert(values.Length > 2, "Choose one filter implies multiple choices possible");
Values = new List<QueryFilterChooseOneItem>(values);
Selected = Values[0];
}
public override bool Equals(QueryFilter o)
{
bool equals = base.Equals(o);
if (!equals)
return false;
equals &= this.Selected.Equals((o as QueryFilterChooseOne).Selected);
equals &= this.Values.ListItemsEqual((o as QueryFilterChooseOne).Values);
return equals;
}
public override QueryFilter Clone()
{
var values = (from x in this.Values select x.Clone()).ToList();
int index = values.IndexOf(this.Selected);
QueryFilterChooseOne item = new QueryFilterChooseOne(this.Label, this.QueryField, values.ToArray());
if (index >= 0)
item.Selected = item.Values[index];
return item;
}
public override string GetQueryField()
{
return string.Format("{0}={1}", this.QueryField, Selected.Value);
}
public List<QueryFilterChooseOneItem> Values { get; set; }
public QueryFilterChooseOneItem Selected { get; set; }
}
public class QueryFilterChooseOneItem : ICloneable<QueryFilterChooseOneItem>, IEquatable<QueryFilterChooseOneItem>, IComparable<QueryFilterChooseOneItem>
{
public QueryFilterChooseOneItem Clone()
{
return new QueryFilterChooseOneItem() { Label = this.Label, Value = this.Value };
}
public bool Equals(QueryFilterChooseOneItem o)
{
return this.CompareTo(o) == 0;
}
public int CompareTo(QueryFilterChooseOneItem o)
{
int x = this.Label.CompareTo(o.Label);
if (x != 0)
return x;
if (string.IsNullOrEmpty(this.Value) && string.IsNullOrEmpty(o.Value))
{
return 0;
}
else if (this.Value == null)
{
return 1; // o is bigger
}
else if (o.Value == null)
{
return -1;
}
return this.Value.CompareTo(o.Value);
}
public string Label
{
get;
set;
}
public string Value
{
get;
set;
}
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/GeneralSettingsVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class GeneralSettingsVM : BindableBase
{
public bool TrackRecentlyViewed
{
get
{
return Settings.Instance.TrackRecentlyViewedPosts;
}
set
{
Settings.Instance.TrackRecentlyViewedPosts = value;
}
}
public bool TrackRecentlySearched
{
get
{
return Settings.Instance.TrackRecentSearches;
}
set
{
Settings.Instance.TrackRecentSearches = value;
}
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/Common/PostDataTemplateSelector.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public class PostDataTemplateSelector : DataTemplateSelector
{
public DataTemplate SearchItemPostThumbnail
{
get;
set;
}
public DataTemplate SearchItemPostText
{
get;
set;
}
public DataTemplate SearchItemLoadMore
{
get;
set;
}
public DataTemplate SearchItemPostSimple
{
get;
set;
}
public DataTemplate SearchItemAd
{
get;
set;
}
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
Frame root = Window.Current.Content as Frame;
if (element != null && item != null && item is PostBase)
{
PostBase post = item as PostBase;
if (Settings.Instance.DetailedSearchResults)
{
PostVM p = post as PostVM;
switch (post.Type)
{
case PostBase.PostType.Post:
if (p.HasThumbnail || p.HasPictures || p.HasImages)
return this.SearchItemPostThumbnail;
else
return this.SearchItemPostText;
case PostBase.PostType.LoadMore:
return this.SearchItemLoadMore;
case PostBase.PostType.Ad:
return this.SearchItemAd;
default:
throw new ArgumentOutOfRangeException();
}
}
else
{
switch (post.Type)
{
case PostBase.PostType.Post:
return this.SearchItemPostSimple;
case PostBase.PostType.LoadMore:
return this.SearchItemLoadMore;
case PostBase.PostType.Ad:
return this.SearchItemAd;
default:
throw new ArgumentOutOfRangeException();
}
}
}
return null;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Settings/GeneralSettings.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
namespace WB.Craigslist8X.View
{
public sealed partial class GeneralSettings : UserControl
{
public GeneralSettings()
{
this.InitializeComponent();
this._vm = new GeneralSettingsVM();
this.DataContext = this._vm;
}
GeneralSettingsVM _vm;
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/CraigCity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Streams;
using WB.SDK;
using WB.SDK.Logging;
using WB.SDK.Parsing;
namespace WB.CraigslistApi
{
public class CraigCity : IComparable<CraigCity>, IEquatable<CraigCity>, ICloneable<CraigCity>
{
#region Constructor
private CraigCity()
{
}
public CraigCity(Uri location, string continent, string state, string city)
{
this.Location = location;
this.Continent = continent;
this.State = state;
this.City = city;
this.SubArea = string.Empty;
this.SubAreaName = string.Empty;
}
public CraigCity(Uri location, string continent, string state, string city, Uri subUrl, string sub, string subName)
: this(location, continent, state, city)
{
this.SubArea = sub;
this.SubAreaName = subName;
this.SubLocation = subUrl;
}
#endregion
#region Overrides
public CraigCity Clone()
{
return CraigCity.Deserialize(CraigCity.Serialize(this));
}
public bool Equals(CraigCity o)
{
return (o == null) ? false : this.CompareTo(o) == 0;
}
public int CompareTo(CraigCity o)
{
int result;
result = this.Continent.CompareTo(o.Continent);
if (result != 0)
return result;
result = this.State.CompareTo(o.State);
if (result != 0)
return result;
result = this.City.CompareTo(o.City);
if (result != 0)
return result;
result = this.IsSubArea.CompareTo(o.IsSubArea);
if (result != 0)
return result;
if (!this.IsSubArea)
{
Logger.Assert(!o.IsSubArea, "isSubArea");
return 0;
}
return this.SubArea.CompareTo(o.SubArea);
}
public override string ToString()
{
return CraigCity.Serialize(this);
}
#endregion
#region Serialization
public static CraigCity Deserialize(string line)
{
if (string.IsNullOrEmpty(line))
return null;
List<string> fields = CsvParser.ReadLine(line);
CraigCity city = new CraigCity();
city.Location = new Uri(fields[0]);
city.Continent = fields[1];
city.State = fields[2];
city.City = fields[3];
city.SubArea = fields[4];
city.SubAreaName = fields[5];
city.SubLocation = string.IsNullOrEmpty(city.SubArea) ? null : new Uri(string.Format("{0}{1}", city.Location, city.SubArea));
if (fields.Count == 8)
{
city.Latitude = string.IsNullOrWhiteSpace(fields[6]) ? double.MinValue : double.Parse(fields[6]);
city.Longitude = string.IsNullOrWhiteSpace(fields[7]) ? double.MinValue : double.Parse(fields[7]);
}
else
{
city.Latitude = double.MinValue;
city.Longitude = double.MinValue;
}
return city;
}
public static string Serialize(CraigCity city)
{
string lat = city.Latitude == double.MinValue ? string.Empty : city.Latitude.ToString();
string lon = city.Longitude == double.MinValue ? string.Empty : city.Longitude.ToString();
string result = CsvParser.WriteLine(city.Location.AbsoluteUri, city.Continent, city.State, city.City, city.SubArea, city.SubAreaName, lat, lon);
return result;
}
#endregion
#region Properties
public bool IsSubArea
{
get
{
return !string.IsNullOrEmpty(SubArea);
}
}
public string DisplayName
{
get
{
if (this.IsSubArea)
return this.SubAreaName;
else
return this.City;
}
}
public Uri Location { get; set; }
public string Continent { get; set; }
public string State { get; set; }
public string City { get; set; }
public Uri SubLocation { get; set; }
public string SubArea { get; set; }
public string SubAreaName { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
#endregion
}
public class CraigCityList
{
#region Constructor
public CraigCityList()
{
_cities = new List<CraigCity>();
}
#endregion
#region Methods
public async Task Save(StorageFile file)
{
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
var outStream = stream.GetOutputStreamAt(0);
var writer = new DataWriter(outStream);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (var city in _cities)
sb.AppendLine(city.ToString());
writer.WriteString(sb.ToString());
await outStream.FlushAsync();
}
public void Add(CraigCity city)
{
_cities.Add(city);
}
public bool Contains(CraigCity city)
{
return _cities.Contains(city);
}
public IEnumerable<CraigCity> GetCities()
{
foreach (var city in _cities)
yield return city;
}
public IEnumerable<string> GetContinents()
{
return (from city in _cities select city.Continent).Distinct();
}
public IEnumerable<CraigCity> GetCitiesByContinent(string continent)
{
foreach (CraigCity city in _cities)
{
if (city.Continent.Equals(continent, StringComparison.OrdinalIgnoreCase))
yield return city;
}
}
public IEnumerable<CraigCity> GetCitiesByState(string state)
{
foreach (CraigCity city in _cities)
{
if (city.State.Equals(state, StringComparison.OrdinalIgnoreCase))
yield return city;
}
}
public CraigCity GetCityByName(string name)
{
foreach (var city in _cities)
{
if (!string.IsNullOrEmpty(city.SubAreaName) && city.SubAreaName.Equals(name, StringComparison.OrdinalIgnoreCase))
return city;
else if (string.IsNullOrEmpty(city.SubAreaName) && city.City.Equals(name, StringComparison.OrdinalIgnoreCase))
return city;
}
return null;
}
public CraigCity GetCityByUri(Uri location)
{
foreach (var city in _cities)
{
if (city.Location.Equals(location))
return city;
}
return null;
}
#endregion
#region Properties
public int Count
{
get
{
return _cities.Count;
}
}
#endregion
#region Fields
private List<CraigCity> _cities;
#endregion
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/Query.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Data.Html;
using Windows.Data.Xml.Dom;
using Windows.UI.Core;
using Windows.UI.Xaml.Media;
using HtmlAgilityPack;
using WB.SDK;
using WB.SDK.Logging;
namespace WB.CraigslistApi
{
public class Query : ICloneable<Query>, IEquatable<Query>
{
#region Initialization
public Query(CraigCity city, Category category, string query)
: this(city, category, query, null)
{
}
public Query(CraigCity city, Category category, string query, QueryFilters filters)
{
if (city == null)
throw new ArgumentNullException("city");
if (category == null)
throw new ArgumentNullException("category");
this.City = city;
this.Category = category;
this.Text = query ?? string.Empty;
this.HasImage = false;
this.Type = QueryType.EntirePost;
this.Filters = filters;
}
#endregion
public bool Equals(Query q)
{
bool equal = true;
equal &= this.City.Equals(q.City);
equal &= this.Category.Equals(q.Category);
equal &= this.Text.Equals(q.Text);
equal &= this.HasImage == q.HasImage;
equal &= this.Type == q.Type;
equal &= ((this.Filters != null && q.Filters != null) || this.Filters == null && q.Filters == null);
if (equal)
equal &= this.Filters.ListItemsEqual(q.Filters);
return equal;
}
public Query Clone()
{
Query q = new Query(this.City.Clone(), this.Category.Clone(), this.Text);
q.HasImage = this.HasImage;
q.Type = this.Type;
q.Sort = this.Sort;
if (this.Filters != null)
q.Filters = new QueryFilters(this.Filters.CloneList());
return q;
}
public async Task<QueryResult> Execute(CancellationToken token)
{
ObservableCollection<Post> posts = new ObservableCollection<Post>();
QueryResult qr = null;
Uri uri = await this.ConstructUri();
try
{
using (HttpClient client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(60);
using (HttpResponseMessage response = await client.GetAsync(uri, token))
{
if (response.IsSuccessStatusCode)
{
qr = new QueryResult(this, posts, response);
await QueryResult.ParseRows(token, response, qr);
}
else
{
Logger.LogMessage("CraigslistApi", "Unsuccessful status code '{0}' returned when sending request to Craigslist.", response.StatusCode);
return null;
}
}
}
return qr;
}
catch (HttpRequestException ex)
{
Logger.LogMessage("CraigslistApi", "Exception thrown when sending http request to craigslist.");
Logger.LogException(ex);
return null;
}
}
public Uri GetQueryUrl()
{
return this.ConstructUri().Result;
}
private async Task<Uri> ConstructUri()
{
return await ConstructUri(0);
}
internal async Task<Uri> ConstructUri(int itemsLoaded)
{
if (this.Mode == SearchMode.Query || this.Filters != null || this.HasImage)
{
// Construct the URI
string domain = string.Format("{0}search/", City.Location.AbsoluteUri);
string path = Category.Abbreviation;
if (!string.IsNullOrWhiteSpace(City.SubArea))
path += string.Format("/{0}", City.SubArea);
// Attach query string
string query = string.Format("?query={0}&srchType={1}", this.Text, this.Type == QueryType.EntirePost ? "A" : "T");
if (this.Filters != null)
{
foreach (var filter in Filters)
{
query += "&" + filter.GetQueryField();
}
}
if (this.HasImage)
{
query += "&hasPic=1";
}
if (itemsLoaded > 0)
{
query += string.Format("&s={0}", itemsLoaded);
}
if (this.Sort != SortOrder.Recent)
{
string value = string.Empty;
switch (this.Sort)
{
case SortOrder.Match:
value = "rel";
break;
case SortOrder.LowPrice:
value = "priceasc";
break;
case SortOrder.HighPrice:
value = "pricedsc";
break;
default:
await Logger.AssertNotReached("Unexpected sort order value");
break;
}
query += string.Format("&sort={0}", value);
}
return new Uri(domain + path + query);
}
else
{
// Just browsing
await Logger.Assert(this.Mode == SearchMode.Browsing, "We should only construct this type of Url in browsing mode");
await Logger.Assert(itemsLoaded % 100 == 0, "Results sets are in sets of 100");
string location = City.IsSubArea ? (City.SubLocation.AbsoluteUri + "/") : City.Location.AbsoluteUri;
string catAbbr = string.Format("{0}/", this.Category.Abbreviation);
string index = string.Empty;
if (itemsLoaded > 0)
{
index = string.Format("index{0}.html", itemsLoaded);
}
return new Uri(location + catAbbr + index);
}
}
public static string Serialize(Query q)
{
return string.Format("<q><city>{0}</city><cat>{1}</cat><qt>{2}</qt><i>{3}</i><t>{4}</t>{5}</q>",
q.City.ToString(),
q.Category.ToString(),
q.Text,
q.HasImage,
q.Type,
QueryFilters.Serialize(q.Filters) ?? string.Empty);
}
public static Query Deserialize(string q)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(q);
CraigCity city = CraigCity.Deserialize(doc.SelectSingleNode("q/city").ChildNodes[0].NodeValue.ToString());
Category cat = Category.Deserialize(doc.SelectSingleNode("q/cat").ChildNodes[0].NodeValue.ToString());
string query = null;
IXmlNode qtNode = doc.SelectSingleNode("q/qt");
if (qtNode.ChildNodes.Count == 1)
query = qtNode.ChildNodes[0].NodeValue.ToString();
bool hasImage = false;
IXmlNode i = doc.SelectSingleNode("q/i");
if (i != null && i.ChildNodes.Count > 0 && i.ChildNodes[0].NodeValue != null)
{
bool.TryParse(i.ChildNodes[0].NodeValue.ToString(), out hasImage);
}
QueryType type = QueryType.EntirePost;
IXmlNode t = doc.SelectSingleNode("q/t");
if (t != null && t.ChildNodes.Count > 0 && t.ChildNodes[0].NodeValue != null)
{
Enum.TryParse(t.ChildNodes[0].NodeValue.ToString(), out type);
}
QueryFilters filters = null;
IXmlNode qf = doc.SelectSingleNode("q/qf");
if (qf != null)
{
filters = QueryFilters.Deserialize(qf.GetXml());
}
Query qo = new Query(city, cat, query);
qo.HasImage = hasImage;
qo.Type = type;
qo.Filters = filters;
return qo;
}
#region Properties
public CraigCity City
{
get;
set;
}
public Category Category
{
get;
private set;
}
public string Text
{
get;
private set;
}
public bool HasImage
{
get;
set;
}
public QueryType Type
{
get;
set;
}
public QueryFilters Filters
{
get;
private set;
}
public SearchMode Mode
{
get
{
return string.IsNullOrWhiteSpace(this.Text) ? SearchMode.Browsing : SearchMode.Query;
}
}
public SortOrder Sort
{
get;
set;
}
#endregion
#region Constants
public enum QueryType
{
TitleOnly,
EntirePost,
}
public enum SearchMode
{
Query,
Browsing,
}
public enum SortOrder
{
Recent,
Match,
LowPrice,
HighPrice,
}
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/Common/Converters.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
namespace WB.Craigslist8X.ViewModel
{
/// <summary>
/// Value converter that translates true and false to characters representings favorite status
/// </summary>
public sealed class BooleanToFavoriteConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? new string('\uE0A5', 1) : new string('\uE006', 1);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Value converter that translates true and false to characters representings favorite status
/// </summary>
public sealed class BooleanToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? new SolidColorBrush(TrueColor) : new SolidColorBrush(FalseColor);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return ((SolidColorBrush)value).Color.Equals(TrueColor) ? true : false;
}
public Color TrueColor
{
get;
set;
}
public Color FalseColor
{
get;
set;
}
}
}
<file_sep>/Win8/WB/WB.SDK/Parsing/CsvParser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WB.SDK.Logging;
namespace WB.SDK.Parsing
{
public static class CsvParser
{
public static string WriteLine(params string[] fields)
{
StringBuilder sb = new StringBuilder();
string formatEscaped = @"""{0}"",";
string formatNormal = @"{0},";
foreach (var field in fields)
{
if (string.IsNullOrEmpty(field))
{
sb.Append(",");
}
else if (field.Contains(",") || field.Contains("\""))
{
sb.Append(string.Format(formatEscaped, field.Replace("\"", "\"\"")));
}
else
{
sb.Append(string.Format(formatNormal, field));
}
}
string result = sb.ToString();
return result.Substring(0, result.Length - 1); // remove very last comma
}
public static List<string> ReadLine(string line)
{
List<string> values = new List<string>();
int start = 0, i = 0;
bool openQuote = false;
string field = string.Empty;
while (i <= line.Length)
{
if ((i == line.Length || line[i] == ',') && !openQuote)
{
if (i == start)
{
values.Add(string.Empty);
}
else
{
field = line.Substring(start, i - start);
if (field.StartsWith("\""))
{
field = field.Substring(1, field.Length - 2);
field = field.Replace("\"\"", "\"");
}
values.Add(field);
}
start = i + 1;
}
else if (line[i] == '"')
{
openQuote = !openQuote;
}
++i;
}
return values;
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Panels/PostDetailsPanel.xaml.cs
using System;
using System.Threading.Tasks;
using System.Linq;
using Windows.ApplicationModel.DataTransfer;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Bing.Maps;
using Callisto.Controls;
using WB.Craigslist8X.GeocodeService;
using WB.Craigslist8X.RouteService;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class PostDetailsPanel : UserControl, IPanel
{
public PostDetailsPanel()
{
this.InitializeComponent();
this._geoClient = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
this._routeClient = new RouteServiceClient(RouteServiceClient.EndpointConfiguration.BasicHttpBinding_IRouteService);
}
public async Task AttachContext(object context, IPanel parent)
{
PostVM post = context as PostVM;
this._post = post;
this.DataContext = this._post;
// Hide unused fields
if (string.IsNullOrEmpty(this._post.Email))
{
EmailLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
EmailLink.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (string.IsNullOrEmpty(this._post.Phone))
{
PhoneLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
PhoneLink.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (string.IsNullOrEmpty(this._post.Price))
{
PriceLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
Price.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (string.IsNullOrEmpty(this._post.Location))
{
LocationLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
Location.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
if (string.IsNullOrEmpty(this._post.Timestamp))
{
DateLabel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
Date.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
// Initialize map data
if (Craigslist8XData.Location == null)
{
Geolocator locator = new Geolocator();
locator.DesiredAccuracy = PositionAccuracy.Default;
Craigslist8XData.Location = await locator.GetGeopositionAsync();
}
Bing.Maps.Location currentLocation = null;
if (Craigslist8XData.Location != null)
{
currentLocation = new Bing.Maps.Location(Craigslist8XData.Location.Coordinate.Latitude, Craigslist8XData.Location.Coordinate.Longitude);
this.AddPushpin("A", currentLocation);
}
Bing.Maps.Location postLocation = null;
if (this._post.HasMap)
{
postLocation = new Bing.Maps.Location(this._post.Post.MapCoordinate.Latitude, this._post.Post.MapCoordinate.Longitude);
}
else
{
postLocation = await GetLocationPoint(this._post.Location);
}
if (postLocation != null)
{
this.AddPushpin("B", postLocation);
}
if (currentLocation != null && postLocation != null)
{
RouteService.RouteResult result = await GetRouteResult(currentLocation, postLocation);
if (result != null)
{
this.SetRoute(result);
}
}
}
#region Maps
private void AddPushpin(string label, Bing.Maps.Location loc)
{
Pushpin pp = new Pushpin() { Text = label };
MapLayer.SetPosition(pp, loc);
this.PostMap.Children.Add(pp);
this.PostMap.Center = loc;
}
private void SetRoute(RouteService.RouteResult route)
{
// Trying to map too many points will hang the application
if (!route.RoutePath.Points.Any() || route.RoutePath.Points.Count > 1000)
{
return;
}
Bing.Maps.MapPolyline routeLine = new MapPolyline();
routeLine.Color = Windows.UI.Colors.Blue;
routeLine.Locations = new LocationCollection();
routeLine.Width = 5;
foreach (RouteService.Location loc in route.RoutePath.Points)
{
routeLine.Locations.Add(new Bing.Maps.Location(loc.Latitude, loc.Longitude));
}
this.PostMap.ShapeLayers.Clear();
MapShapeLayer layer = new MapShapeLayer();
this.PostMap.ShapeLayers.Add(layer);
layer.Shapes.Clear();
layer.Shapes.Add(routeLine);
//Set the map view
LocationRect rect = new LocationRect(routeLine.Locations);
this.PostMap.SetView(rect);
}
private async Task<Bing.Maps.Location> GetLocationPoint(string address)
{
if (string.IsNullOrEmpty(address))
return null;
GeocodeRequest request = new GeocodeRequest();
request.ExecutionOptions = new GeocodeService.ExecutionOptions();
request.ExecutionOptions.SuppressFaults = true;
request.Query = address;
request.Credentials = new GeocodeService.Credentials() { Token = BingToken };
GeocodeResponse response = await this._geoClient.GeocodeAsync(request);
if (response.Results.Count() > 0)
{
return new Bing.Maps.Location(response.Results[0].Locations[0].Latitude, response.Results[0].Locations[0].Longitude);
}
return null;
}
private async Task<RouteService.RouteResult> GetRouteResult(Bing.Maps.Location a, Bing.Maps.Location b)
{
if (a == null || b == null)
return null;
RouteRequest request = new RouteRequest();
request.ExecutionOptions = new RouteService.ExecutionOptions();
request.ExecutionOptions.SuppressFaults = true;
request.Options = new RouteOptions();
request.Options.RoutePathType = RoutePathType.Points;
request.Options.TrafficUsage = TrafficUsage.None;
request.Options.Mode = TravelMode.Driving;
request.Credentials = new RouteService.Credentials() { Token = BingToken };
request.Waypoints = new System.Collections.ObjectModel.ObservableCollection<Waypoint>();
request.Waypoints.Add(new Waypoint() { Description = "Current Location", Location = new RouteService.Location() { Latitude = a.Latitude, Longitude = a.Longitude } });
request.Waypoints.Add(new Waypoint() { Description = "Item Location", Location = new RouteService.Location() { Latitude = b.Latitude, Longitude = b.Longitude } });
RouteResponse response = await this._routeClient.CalculateRouteAsync(request);
return response.Result;
}
#endregion
private async void UrlLink_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
if (this._post.Post.Url == null)
{
await Logger.AssertNotReached("Url is null? WTF?");
return;
}
var menu = new Menu();
var copy = new MenuItem { Text = "Copy" };
var browse = new MenuItem { Text = "Browse Link" };
copy.Tapped += (a, b) => { DataPackage pkg = new DataPackage(); pkg.SetText(this._post.Url); Clipboard.SetContent(pkg); };
browse.Tapped += async (a, b) => { await Windows.System.Launcher.LaunchUriAsync(new Uri(this._post.Url)); };
menu.Items.Add(copy);
menu.Items.Add(browse);
this.ShowMenu(sender as UIElement, menu);
}
private async void EmailLink_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
if (string.IsNullOrEmpty(this._post.Post.Email))
{
await Logger.AssertNotReached("Email is null? WTF?");
return;
}
var menu = new Menu();
var copy = new MenuItem { Text = "Copy" };
var send = new MenuItem { Text = "Send Email" };
copy.Tapped += (a, b) => { DataPackage pkg = new DataPackage(); pkg.SetText(this._post.Email); Clipboard.SetContent(pkg); };
send.Tapped += async (a, b) => { await Windows.System.Launcher.LaunchUriAsync(new Uri(string.Format("mailto:?to={0}&subject={1}&body={2}", this._post.Email, this._post.Title, this._post.Post.Url.ToString()))); };
menu.Items.Add(copy);
menu.Items.Add(send);
this.ShowMenu(sender as UIElement, menu);
}
private void PhoneLink_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
if (string.IsNullOrEmpty(this._post.Post.Phone))
return;
var menu = new Menu();
var copy = new MenuItem { Text = "Copy" };
var call = new MenuItem { Text = "Call Phone" };
copy.Tapped += (a, b) => { DataPackage pkg = new DataPackage(); pkg.SetText(this._post.Phone); Clipboard.SetContent(pkg); };
call.Tapped += async (a, b) => { await Windows.System.Launcher.LaunchUriAsync(new Uri(string.Format("callto:+1{0}", this._post.Phone))); };
menu.Items.Add(copy);
menu.Items.Add(call);
this.ShowMenu(sender as UIElement, menu);
}
private void ShowMenu(UIElement context, Menu menu)
{
// Show the menu in a flyout anchored to the header title
var flyout = new Flyout();
flyout.Placement = PlacementMode.Bottom;
flyout.HorizontalAlignment = HorizontalAlignment.Left;
flyout.HorizontalContentAlignment = HorizontalAlignment.Left;
flyout.PlacementTarget = context;
flyout.Content = menu;
flyout.IsOpen = true;
}
PostVM _post;
GeocodeServiceClient _geoClient;
RouteServiceClient _routeClient;
const string BingToken = "<KEY>";
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Settings/SettingsUI.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.System;
using Callisto.Controls;
namespace WB.Craigslist8X.View
{
public static class SettingsUI
{
public static void ShowSearchSettings()
{
MainPage.Instance.ToggleWebView(show: false);
SettingsFlyout settings = new SettingsFlyout();
settings.HeaderText = "Search";
settings.Content = new SearchSettings();
settings.Closed += (s, e) => { MainPage.Instance.ToggleWebView(show: true); };
settings.IsOpen = true;
}
public static void SettingsUI_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
SettingsCommand about = new SettingsCommand(AboutSettings, AboutSettings, GetCommandHandler(AboutSettings));
SettingsCommand general = new SettingsCommand(GeneralSettings, GeneralSettings, GetCommandHandler(GeneralSettings));
SettingsCommand search = new SettingsCommand(SearchSettings, SearchSettings, GetCommandHandler(SearchSettings));
SettingsCommand privacy = new SettingsCommand(PrivacySettings, PrivacySettings, GetCommandHandler(PrivacySettings));
args.Request.ApplicationCommands.Add(about);
args.Request.ApplicationCommands.Add(general);
args.Request.ApplicationCommands.Add(search);
args.Request.ApplicationCommands.Add(privacy);
}
private static UICommandInvokedHandler GetCommandHandler(string setting)
{
return (x) =>
{
SettingsFlyout settings = new SettingsFlyout();
settings.HeaderText = x.Label;
if (setting == AboutSettings)
{
settings.Content = new AboutSettings();
}
else if (setting == GeneralSettings)
{
settings.Content = new GeneralSettings();
}
else if (setting == SearchSettings)
{
settings.Content = new SearchSettings();
}
else if (setting == PrivacySettings)
{
var res = Launcher.LaunchUriAsync(new Uri(PrivacyPolicyUrl));
return;
}
MainPage.Instance.ToggleWebView(show: false);
settings.Closed += (s, e) => { MainPage.Instance.ToggleWebView(show: true); };
settings.IsOpen = true;
};
}
const string AboutSettings = "About";
const string GeneralSettings = "General";
const string SearchSettings = "Search";
const string PrivacySettings = "Privacy Policy";
const string PrivacyPolicyUrl = "http://wbishop.azurewebsites.net/privacy.aspx";
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/AccountVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Credentials;
using WB.Craigslist8X.Model;
namespace WB.Craigslist8X.ViewModel
{
public sealed class AccountVM : AccountVMBase
{
public AccountVM(PasswordCredential account)
{
this._account = account;
}
public override bool ShowDelete
{
get
{
return true;
}
}
public override string Display
{
get { return this._account.UserName; }
}
public override ViewModelType Type
{
get { return ViewModelType.Account; }
}
public PasswordCredential Account
{
get
{
return this._account;
}
}
PasswordCredential _account;
}
public sealed class AnonymousVM : AccountVMBase
{
public override string Display
{
get { return "Post without account"; }
}
public override ViewModelType Type
{
get { return ViewModelType.Anonymous; }
}
}
public sealed class AddAccountVM : AccountVMBase
{
public override bool ShowArrow
{
get
{
return false;
}
}
public override string Display
{
get { return "Add new account"; }
}
public override ViewModelType Type
{
get { return ViewModelType.Add; }
}
}
public abstract class AccountVMBase
{
public virtual bool ShowArrow
{
get
{
return true;
}
}
public virtual bool ShowDelete
{
get
{
return false;
}
}
public abstract string Display
{
get;
}
public abstract ViewModelType Type
{
get;
}
public enum ViewModelType
{
Account,
Anonymous,
Add,
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/ViewModel/Common/PostBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using WB.Craigslist8X.Common;
namespace WB.Craigslist8X.ViewModel
{
public abstract class PostBase : BindableBase
{
public abstract PostType Type
{
get;
}
public enum PostType
{
Post,
LoadMore,
Ad,
}
}
}
<file_sep>/Win8/Craigslist8X/Craigslist8X/App.xaml.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Store;
using Windows.Data.Xml.Dom;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using WinRTXamlToolkit.Tools;
using WB.SDK.Logging;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.View;
namespace WB.Craigslist8X
{
partial class App
{
public App()
{
InitializeComponent();
this.Resuming += AppResuming;
this.Suspending += OnSuspending;
this.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
DebugSettings.IsBindingTracingEnabled = false;
this.RequestedTheme = ApplicationTheme.Light;
}
async void OnResuming(object sender, object e)
{
await SavedSearches.Instance.LoadNotificationsAsync();
}
private async void BackgroundTimer_Tick(object sender, object e)
{
using (new MonitoredScope("Craigslist8X Background Tasks"))
{
await Craigslist8XData.SaveAsync();
await SavedSearches.Instance.LoadNotificationsAsync();
}
}
private async Task InitCraigslist8X()
{
using (new MonitoredScope("Initialize Craigslist8X"))
{
#if DEBUG
LicenseInfo = CurrentAppSimulator.LicenseInformation;
#else
LicenseInfo = CurrentApp.LicenseInformation;
#endif
bool loaded = await Craigslist8XData.LoadAsync();
// Load notification data every time we start the app because background task may have kicked in
await SavedSearches.Instance.LoadNotificationsAsync();
if (loaded)
{
// Hook up settings handlers
SettingsPane.GetForCurrentView().CommandsRequested += SettingsUI.SettingsUI_CommandsRequested;
if (this.BackgroundTimer == null)
{
this.BackgroundTimer = new BackgroundTimer();
this.BackgroundTimer.Interval = TimeSpan.FromSeconds(15);
this.BackgroundTimer.Tick += BackgroundTimer_Tick;
this.BackgroundTimer.IsEnabled = true;
this.BackgroundTimer.Start();
}
}
// Ensure we have a window to look at
if (MainPage.Instance == null)
{
Frame root = await EnsureNavigationFrame();
root.Navigate(typeof(MainPage), null);
DataTransferManager.GetForCurrentView().DataRequested += MainPage.Instance.MainPage_DataRequested;
}
}
}
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
using (new MonitoredScope("Launch Craigslist8X"))
{
await this.InitCraigslist8X();
try
{
if (!string.IsNullOrEmpty(args.Arguments))
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(args.Arguments);
XmlElement xe = doc.DocumentElement;
if (xe.NodeName == "SavedQuery")
{
await MainPage.Instance.ExecuteSavedSearches(null, Uri.UnescapeDataString(xe.GetAttribute("Name")));
}
}
catch
{
}
// It could have been a JSON argument instead of XML
dynamic argObject = JsonConvert.DeserializeObject(args.Arguments);
if (argObject.type == "toast")
{
var webUrl = argObject.clientUrl;
var uri = new Uri(webUrl.ToString());
await Windows.System.Launcher.LaunchUriAsync(uri);
}
}
}
catch (Exception ex)
{
Logger.LogMessage("Exception thrown launching app with the following arguments: {0}", args.Arguments);
Logger.LogException(ex);
}
}
}
protected async override void OnSearchActivated(SearchActivatedEventArgs args)
{
using (new MonitoredScope("Search Activate Craigslist8X"))
{
await this.InitCraigslist8X();
if (!CityManager.Instance.SearchCitiesDefined)
{
MessageDialog dlg = new MessageDialog("Please set the city you want to search and try again.", "Craigslist 8X");
await dlg.ShowAsync();
SettingsUI.ShowSearchSettings();
}
else
{
// As of this writing, this app has two actual pages. The MainPage and the ChooceCitiesPage. We need to ensure that
// we navigate to the MainPage.
Frame frame = await EnsureNavigationFrame();
frame.Content = MainPage.Instance;
Query template = new Query(CityManager.Instance.SearchCities.First(), CategoryManager.Instance.SearchCategory, args.QueryText);
template.HasImage = Settings.Instance.OnlyShowPostsPictures;
template.Type = Settings.Instance.OnlySearchTitles ? Query.QueryType.TitleOnly : Query.QueryType.EntirePost;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High,
async () =>
{
await MainPage.Instance.ExecuteSearchQuery(null, qb);
});
}
}
}
protected async void AppResuming(object sender, object e)
{
await SavedSearches.Instance.LoadNotificationsAsync();
}
protected async void OnSuspending(object sender, SuspendingEventArgs e)
{
using (new MonitoredScope("Suspend Craigslist8X"))
{
SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
await Craigslist8XData.SaveAsync();
deferral.Complete();
}
}
protected async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Logger.LogException(e.Exception);
await Craigslist8XData.SaveAsync();
}
#region Static
public static async Task<Frame> EnsureNavigationFrame()
{
if (Window.Current.Content == null)
{
Window.Current.Content = new Frame();
}
else if (!(Window.Current.Content is Frame))
{
await Logger.AssertNotReached("Why is Window.Current.Content set to a non null type that is not a Frame?");
Window.Current.Content = new Frame();
}
Window.Current.Activate();
return (Frame)Window.Current.Content;
}
public static LicenseInformation LicenseInfo;
#endregion
#region Pro
internal const string Craigslist8XPRO = "Craigslist8XPRO";
public static bool IsPro
{
get
{
#if CRAIGSLIST8XPRO
return true;
#else
return LicenseInfo.ProductLicenses[Craigslist8XPRO].IsActive;
#endif
}
}
#endregion
private BackgroundTimer BackgroundTimer;
}
}
<file_sep>/Win8/Craigslist8X/CraigslistApi/Geography.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Streams;
using HtmlAgilityPack;
using WB.SDK;
using WB.SDK.Logging;
namespace WB.CraigslistApi
{
internal static class Geography
{
internal static async Task<CraigCityList> FindNearbyCities(CraigCityList all, CraigCity city)
{
if (city == null)
throw new ArgumentNullException("city");
if (all == null)
throw new ArgumentNullException("all");
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(city.Location))
{
if (response.IsSuccessStatusCode)
{
CraigCityList cities = new CraigCityList();
HtmlDocument html = new HtmlDocument();
html.LoadHtml(await response.Content.ReadAsStringAsync());
throw new NotImplementedException();
//IXmlNode node = xml.SelectSingleNode("//html/body/table/tr/td/ul/li/h5[@class=\"ban\"]");
//Logger.Assert(node != null, "banner node is null");
//if (node == null)
// return null;
//Logger.Assert(node.GetXml().Contains("nearby"), "did not find nearby node");
//XmlElement ul = node.NextSibling as XmlElement;
//XmlNodeList items = ul.SelectNodes("li[@class=\"s\"]");
//foreach (var item in items)
//{
// Uri uri = new Uri(Uri.UnescapeDataString(item.NextSibling.Attributes[0].NodeValue.ToString()));
// cities.Add(all.GetCityByUri(uri));
//}
//return cities;
}
return null;
}
}
catch (HttpRequestException)
{
// TODO: Log exception
throw;
}
}
internal static Uri ResolveLocation()
{
using (HttpResponseMessage response = Utilities.ExecuteRetryable<HttpResponseMessage>(() => GetResolveLocationResponse(), 3))
{
if (response != null)
{
return response.RequestMessage.RequestUri;
}
}
return null;
}
private static HttpResponseMessage GetResolveLocationResponse()
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync(Craigslist.GeoUrl).GetAwaiter().GetResult();
// Sometimes Craigslist is unable to resolve the correct location so we just need to handle that case.
if (response.IsSuccessStatusCode && !response.RequestMessage.RequestUri.AbsoluteUri.Equals(Craigslist.SitesUrl, StringComparison.OrdinalIgnoreCase))
return response;
else
throw new RetryException();
}
}
internal static async Task<CraigCityList> ScrapeLocations()
{
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(Craigslist.SitesUrl))
{
if (response.IsSuccessStatusCode)
{
HtmlDocument html = new HtmlDocument();
html.LoadHtml(await response.Content.ReadAsStringAsync());
CraigCityList cities = new CraigCityList();
return null;
//XmlNodeList continents = document.SelectNodes(@"//h1[@class=""continent_header""]");
//foreach (var coNode in continents)
//{
// string continent = string.Empty;
// // For some reason the OCEANIA continent is not formatted as the rest
// if (coNode.ChildNodes.Count > 1)
// continent = coNode.ChildNodes[1].ChildNodes[0].NodeValue as string;
// else
// continent = coNode.ChildNodes[0].ChildNodes[0].ChildNodes[0].NodeValue as string;
// foreach (var boxNode in coNode.SelectNodes(@"../div/div/div/div"))
// {
// foreach (var sNode in boxNode.SelectNodes(@"div[@class=""state_delimiter""]"))
// {
// if (sNode.ChildNodes.Count != 1)
// continue;
// string state = sNode.ChildNodes[0].ChildNodes[0].NodeValue as string;
// foreach (var ciNode in sNode.NextSibling.SelectNodes(@"li/a"))
// {
// Uri uri = new Uri(Uri.UnescapeDataString(ciNode.Attributes[0].NodeValue as string));
// string city = ciNode.ChildNodes[0].ChildNodes[0].NodeValue as string;
// CraigCity craigCity = new CraigCity(uri, Uri.UnescapeDataString(continent), Uri.UnescapeDataString(state), Uri.UnescapeDataString(city));
// cities.Add(craigCity);
// }
// }
// }
//}
//await AddSubAreas(cities);
//return cities;
}
}
}
catch (HttpRequestException ex)
{
Logger.LogException(ex);
}
return null;
}
#region Private Methods
private static async Task AddSubAreas(CraigCityList cl)
{
using (HttpClient client = new HttpClient())
{
client.MaxResponseContentBufferSize = 256 * 1024 * 1024; // 256k
using (HttpResponseMessage response = await client.GetAsync(Craigslist.SubAreasUrl))
{
if (response.IsSuccessStatusCode)
{
HtmlDocument html = new HtmlDocument();
html.LoadHtml(await response.Content.ReadAsStringAsync());
throw new NotImplementedException();
//XmlDocument document = html.ToXmlDocument();
//IXmlNode h3 = document.SelectSingleNode("//html/body/h3/text[text()='Areas%20and%20Subareas%3A']");
//XmlNodeList nodes = h3.ParentNode.NextSibling.SelectNodes("table/tr");
//foreach (var row in nodes)
//{
// // skip the headers
// if (row.ChildNodes[0].NodeName == "th")
// continue;
// string cityName = Uri.UnescapeDataString(row.ChildNodes[1].ChildNodes[0].ChildNodes[0].GetXml()).Trim();
// string subArea = Uri.UnescapeDataString(row.ChildNodes[2].ChildNodes[0].ChildNodes[0].GetXml()).Trim();
// string subAreaName = Uri.UnescapeDataString(row.ChildNodes[3].ChildNodes[0].ChildNodes[0].GetXml()).Trim();
// if (subArea != " ")
// {
// CraigCity city = cl.GetCityByName(cityName);
// if (city == null)
// {
// if (cityName.Contains(","))
// cityName = cityName.Split(',')[0].Trim();
// city = cl.GetCityByName(cityName);
// Logger.AssertNotNull(city, "failed to find city by name");
// if (city == null)
// continue;
// }
// // Example:
// // Location: http://seattle.craigslist.com/est
// // Continent: US
// // State: Washington
// // City: seattle-tacoma
// // Sub Area: est
// // Sub Area Name: eastside
// string format = city.Location.AbsoluteUri.EndsWith("/") ? "{0}{1}": "{0}/{1}";
// cl.Add(new CraigCity(new Uri(city.Location.AbsoluteUri),
// city.Continent,
// city.State,
// city.City,
// new Uri(string.Format(format, city.Location.AbsoluteUri, subArea)),
// subArea,
// subAreaName));
// }
//}
}
}
}
}
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/Settings/SearchSettings.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Callisto.Controls;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
public sealed partial class SearchSettings : UserControl
{
public SearchSettings()
{
this.InitializeComponent();
this._vm = new SearchSettingsVM();
this.DataContext = this._vm;
if (CityManager.Instance.SearchCitiesDefined)
{
this.GetStarted.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
#region Cities
private void AddCity_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame root = (Frame)Window.Current.Content;
root.Navigate(typeof(ChooseCategoryPage));
if (this.Parent is SettingsFlyout)
{
SettingsFlyout sf = this.Parent as SettingsFlyout;
sf.IsOpen = false;
}
}
private void RemoveCity_Tapped(object sender, TappedRoutedEventArgs e)
{
CraigCity city = (sender as FrameworkElement).DataContext as CraigCity;
CityManager.Instance.RemoveSearchCity(city);
}
private void MoveCityToTop_Tapped(object sender, TappedRoutedEventArgs e)
{
CraigCity city = (sender as FrameworkElement).DataContext as CraigCity;
CityManager.Instance.PromoteSearchCity(city);
}
#endregion
#region Change Category
private void ChangeCategory_Tapped(object sender, TappedRoutedEventArgs e)
{
if (CategorySelector.Visibility == Windows.UI.Xaml.Visibility.Visible)
{
CategorySelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
ChangeCategory.Content = "Change Category";
}
else
{
CategorySelector.Visibility = Windows.UI.Xaml.Visibility.Visible;
ChangeCategory.Content = "Cancel";
this._category = CategoryHierarchy.Root;
if (Settings.Instance.PersonalsUnlocked)
CategorySelector.ItemsSource = (from x in CategoryManager.Instance.Categories select x.Root).Distinct().OrderBy(x => x);
else
CategorySelector.ItemsSource = (from x in CategoryManager.Instance.Categories select x.Root).Distinct().Where(x => !x.Equals("personals", StringComparison.OrdinalIgnoreCase)).OrderBy(x => x);
}
}
private void Category_Tapped(object sender, TappedRoutedEventArgs e)
{
string context = (sender as FrameworkElement).DataContext as string;
Logger.Assert(!string.IsNullOrEmpty(context), "Category picker context appears to be empty");
if (string.IsNullOrEmpty(context))
return;
switch (this._category)
{
case CategoryHierarchy.Root:
{
CategorySelector.ItemsSource = (from x in CategoryManager.Instance.Categories.Where(x => x.Root == context) select x.Name).Distinct().OrderBy(x => x);
this._category = CategoryHierarchy.Category;
break;
}
case CategoryHierarchy.Category:
{
var cat = (from x in CategoryManager.Instance.Categories.Where(x => x.Name == context) select x).FirstOrDefault();
this.SetCategory(cat);
break;
}
default:
throw new ArgumentException(this._category.ToString());
}
}
private void SetCategory(Category cat)
{
CategorySelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
ChangeCategory.Content = "Change Category";
CategoryManager.Instance.SearchCategory = cat;
this._vm.OnPropertyChanged("SearchCategory");
}
CategoryHierarchy _category;
enum CategoryHierarchy
{
Root,
Category,
}
#endregion
SearchSettingsVM _vm;
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/View/MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows;
using Windows.ApplicationModel.Core;
using Windows.ApplicationModel.DataTransfer;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Input;
using Windows.UI.ViewManagement;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.Security.Credentials;
using Callisto.Controls;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.ViewModel;
using WB.SDK.Controls;
using WB.SDK.Logging;
namespace WB.Craigslist8X.View
{
sealed partial class MainPage : LayoutAwarePage
{
public MainPage()
{
this.InitializeComponent();
MainPage.Instance = this;
this.DataContext = this;
this.Loaded += this.MainPage_Loaded;
this.PanelView = this.MainPanelView;
this.SizeChanged += this.MainPage_SizeChanged;
this.PanelView.ItemsMoved += PanelView_ItemsMoved;
this.PanelView.ItemsArranged += PanelView_ItemsArranged;
this.MainMenu = new MainMenuOptionsPanel();
this.MainMenu.Width = this.MinPanelWidth;
var x = this.MainPanelView.AddPanel(this.MainMenu);
}
void PanelView_ItemsArranged(object sender, IEnumerable<UIElement> e)
{
foreach (UIElement panel in this.MainPanelView.Children)
{
if (panel is MainMenuOptionsPanel)
{
(panel as IWebViewHost).ToggleWebView(!this.MainPanelView.PanelOutOfView(panel));
break;
}
}
}
async void PanelView_ItemsMoved(object sender, PanelMove e)
{
switch (e)
{
case PanelMove.Started:
this.ToggleWebView(false);
break;
case PanelMove.Finished:
this.ToggleWebView(true);
break;
default:
await Logger.AssertNotReached("PanelMove type not recognized.");
break;
}
}
async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
bool gpsLocated = false;
try
{
if (!CityManager.Instance.SearchCitiesDefined)
{
if (Craigslist8XData.Location == null)
{
Geolocator locator = new Geolocator();
locator.DesiredAccuracy = PositionAccuracy.Default;
Craigslist8XData.Location = await locator.GetGeopositionAsync();
}
if (Craigslist8XData.Location != null)
{
CraigCity city = await CityManager.Instance.FindNearestCityGps(Craigslist8XData.Location.Coordinate);
if (city != null)
{
CityManager.Instance.AddSearchCity(city);
gpsLocated = true;
}
}
}
}
catch (UnauthorizedAccessException ex)
{
Logger.LogException(ex);
}
await BackgroundTaskManager.RegisterAccess();
if (Settings.Instance.AppBootCount >= 10 && Settings.Instance.AppBootCount % 10 == 0 && Settings.Instance.PromptForRating)
{
MessageDialog dlg = new MessageDialog(string.Format("It looks like you have used this app over {0} times. We really appreciate your loyalty and would love it if you could take 30 seconds to give us a 5 star rating. Thanks for using Craigslist 8X! ", Settings.Instance.AppBootCount), "Craigslist 8X");
dlg.Commands.Add(new UICommand() { Id = 0, Label = "Sure" });
dlg.Commands.Add(new UICommand() { Id = 1, Label = "Maybe later" });
dlg.Commands.Add(new UICommand() { Id = 2, Label = "Stop bugging me!" });
dlg.DefaultCommandIndex = 0;
UICommand cmd = await dlg.ShowAsync() as UICommand;
if ((int)cmd.Id == 0)
{
// Stop asking because they rated.
Settings.Instance.PromptForRating = false;
await Windows.System.Launcher.LaunchUriAsync(new Uri(string.Format("ms-windows-store:REVIEW?PFN={0}", Windows.ApplicationModel.Package.Current.Id.FamilyName)));
}
else if ((int)cmd.Id == 2)
{
// Never ask again
Settings.Instance.PromptForRating = false;
}
}
if (!CityManager.Instance.SearchCitiesDefined || gpsLocated)
{
SettingsUI.ShowSearchSettings();
}
SettingsSideMenuButton.IsEnabled = !!(ApplicationView.Value != ApplicationViewState.Snapped);
NewsButton.IsEnabled = await NewsManager.Instance.IsNewItem();
// I'm a tricky bastard. We only really need to do this once. Ever.
// The next time a reviewer installs this app it is from a clean slate, so obviously this setting will not be defined.
// If it is set, then it is very very unlikely it is a reviewer. I'm willing to take my chances and make this optimization.
if (!Settings.Instance.PersonalsUnlocked)
{
Settings.Instance.PersonalsUnlocked = await NewsManager.Instance.IsPersonalsAvailable();
}
}
public void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
foreach (var panel in this.MainPanelView.Children)
{
if (panel is ViewPostPanel)
{
(panel as ViewPostPanel).HandleShare(args.Request);
return;
}
}
}
void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
{
SettingsSideMenuButton.IsEnabled = !!(ApplicationView.Value != ApplicationViewState.Snapped);
}
#region Side Menu
private void HomeSideMenu_Tapped(object sender, TappedRoutedEventArgs e)
{
this.MainPanelView.SnapToPanel(panel: 0);
}
private void SettingsSideMenu_Tapped(object sender, TappedRoutedEventArgs e)
{
Windows.UI.ApplicationSettings.SettingsPane.Show();
}
private async void NewsSideMenu_Tapped(object sender, TappedRoutedEventArgs e)
{
MainPage.Instance.ToggleWebView(show: false);
var newsItems = await NewsManager.Instance.GetNews();
if (newsItems == null || newsItems.Count < 1)
{
await new MessageDialog("There was a problem retreiving news updates. Please try again later.", "Craigslist 8X").ShowAsync();
return;
}
NewsContainer news = new NewsContainer();
news.Width = CoreApplication.MainView.CoreWindow.Bounds.Width;
news.Height = CoreApplication.MainView.CoreWindow.Bounds.Height;
news.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center;
news.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
news.SetContext(newsItems);
Canvas sp = new Canvas();
sp.Width = CoreApplication.MainView.CoreWindow.Bounds.Width;
sp.Height = CoreApplication.MainView.CoreWindow.Bounds.Height;
sp.Background = new Windows.UI.Xaml.Media.SolidColorBrush(new Windows.UI.Color() { A = 225, R = 0, G = 0, B = 0 });
sp.Children.Add(news);
Popup popup = new Popup();
popup.HorizontalAlignment = HorizontalAlignment.Center;
popup.VerticalAlignment = VerticalAlignment.Center;
popup.Child = sp;
popup.Width = CoreApplication.MainView.CoreWindow.Bounds.Width;
popup.Height = CoreApplication.MainView.CoreWindow.Bounds.Height;
popup.IsLightDismissEnabled = true;
popup.HorizontalOffset = 0;
popup.VerticalOffset = 0;
popup.IsOpen = true;
sp.Tapped += (s, x) =>
{
NewsButton.IsEnabled = false;
popup.IsOpen = false;
MainPage.Instance.ToggleWebView(show: true);
};
}
private void BackSideMenu_Tapped(object sender, TappedRoutedEventArgs e)
{
if (this.MainPanelView.Children.Count - 1 > 0)
{
this.MainPanelView.RemovePanel(this.MainPanelView.Children.Count - 1, recursive: true);
this.MainPanelView.SnapToPanel(this.MainPanelView.Children.Count - 1);
}
// If we,We removed the Contact Information panel the view post panel should be our last panel
// and we may want to resize it.
this.SetViewPostWidth(this.MainPanelView.Children[this.MainPanelView.Children.Count - 1] as ViewPostPanel);
this.BackSideMenuButton.IsEnabled = this.MainPanelView.Children.Count > 1;
}
#endregion
#region Panels
public async Task ExecuteSearchQuery(UIElement parent, QueryBatch qb)
{
Monitor.Enter(this);
try
{
if (!CityManager.Instance.SearchCitiesDefined)
{
MessageDialog dlg = new MessageDialog("Please set the city you want to search and try again.", "Craigslist 8X");
await dlg.ShowAsync();
SettingsUI.ShowSearchSettings();
return;
}
}
finally
{
Monitor.Exit(this);
}
this.ToggleWebView(false);
// We only care about the text and category of the query. The queries in a QueryBatch are only different
// because there is a different query object for each city. For tracking what we want, the first should be
// sufficient.
RecentlySearched.Instance.AddQuery(qb.Queries.First());
await Logger.AssertNotNull(qb, "QueryBatch object should not be null");
this.RemoveChildPanels(parent);
SearchResultsPanel searchResults = new SearchResultsPanel();
searchResults.Width = Settings.Instance.ExpandSearchResults ? PanelView.ActualWidth : Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(searchResults, qb, parent as IPanel);
await MainPanelView.AddPanel(searchResults);
if (parent is MainMenuOptionsPanel || parent == null)
{
if (qb.Queries.First().Mode == Query.SearchMode.Query)
this.MainMenu.SetSelectionSearch();
else
this.MainMenu.SetSelectionBrowse();
}
this.ToggleWebView(true);
}
public async Task ExecuteSavedQuery(UIElement parent, SavedQuery sq)
{
this.ToggleWebView(false);
if (sq == null)
{
await Logger.AssertNotReached("SavedQuery object should not be null");
this.ToggleWebView(true);
return;
}
this.RemoveChildPanels(parent);
SearchResultsPanel searchResults = new SearchResultsPanel();
searchResults.Width = Settings.Instance.ExpandSearchResults ? PanelView.ActualWidth : Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(searchResults, sq, parent as IPanel);
await MainPanelView.AddPanel(searchResults);
this.ToggleWebView(true);
}
public async Task ExecuteBrowse(UIElement parent, Category category)
{
if (!CityManager.Instance.SearchCitiesDefined)
{
MessageDialog dlg = new MessageDialog("Please set the city you want to browse and try again.", "Craigslist 8X");
await dlg.ShowAsync();
SettingsUI.ShowSearchSettings();
return;
}
this.MainMenu.SetSelectionBrowse();
this.ToggleWebView(false);
this.RemoveChildPanels(parent);
ExploreCategoriesPanel exploreCats = new ExploreCategoriesPanel();
exploreCats.Width = this.MinPanelWidth;
this.AttachContext(exploreCats, category, parent as IPanel);
await MainPanelView.AddPanel(exploreCats);
this.ToggleWebView(true);
}
public async Task ExecuteFavorites(UIElement parent)
{
this.ToggleWebView(false);
this.RemoveChildPanels(parent);
FavoritedPostsPanel favoritesPanel = new FavoritedPostsPanel();
favoritesPanel.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(favoritesPanel, null, parent as IPanel);
await MainPanelView.AddPanel(favoritesPanel);
this.ToggleWebView(true);
}
public async Task ExecuteViewPost(UIElement parent, PostVM post)
{
await Logger.Assert(post != null, "Post is null?");
if (post == null)
return;
this.ToggleWebView(false);
this.RemoveChildPanels(parent);
ViewPostPanel viewPost = new ViewPostPanel();
SetViewPostWidth(viewPost);
this.AttachContext(viewPost, post, parent as IPanel);
await MainPanelView.AddPanel(viewPost);
this.ToggleWebView(true);
}
public async Task ExecutePostDetails(UIElement parent, PostVM post)
{
await Logger.Assert(post != null, "Post is null?");
if (post == null)
return;
this.ToggleWebView(false);
this.RemoveChildPanels(parent);
PostDetailsPanel postDetails = new PostDetailsPanel();
postDetails.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(postDetails, post, parent as IPanel);
await MainPanelView.AddPanel(postDetails);
this.ToggleWebView(true);
}
public async Task ExecuteRecentlyViewed(UIElement parent)
{
this.RemoveChildPanels(parent);
RecentlyViewedPanel recentlyViewed = new RecentlyViewedPanel();
recentlyViewed.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(recentlyViewed, null, parent as IPanel);
await MainPanelView.AddPanel(recentlyViewed);
}
public async Task ExecuteRecentlySearched(UIElement parent)
{
this.RemoveChildPanels(parent);
RecentlySearchedPanel recentlySearched = new RecentlySearchedPanel();
recentlySearched.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(recentlySearched, null, parent as IPanel);
await MainPanelView.AddPanel(recentlySearched);
}
public async Task ExecuteSavedSearches(UIElement parent, string name)
{
this.RemoveChildPanels(parent);
SavedSearchesPanel savedSearches = new SavedSearchesPanel();
savedSearches.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(savedSearches, name, parent as IPanel);
await MainPanelView.AddPanel(savedSearches);
}
public async Task ExecuteUpgrade(UIElement parent)
{
this.RemoveChildPanels(parent);
UpgradePanel upgrade = new UpgradePanel();
upgrade.Width = this.PanelView.ActualWidth - (parent as FrameworkElement).ActualWidth - 1;
this.AttachContext(upgrade, null, parent as IPanel);
await MainPanelView.AddPanel(upgrade);
}
public async Task ExecuteCreatePost(UIElement parent, CreatePostContext context)
{
this.RemoveChildPanels(parent);
CreatePostPanel postsPanel = new CreatePostPanel();
postsPanel.Width = this.PanelView.ActualWidth;
this.AttachContext(postsPanel, context, parent as IPanel);
await MainPanelView.AddPanel(postsPanel);
}
public async Task ExecuteChooseAccount(UIElement parent, ChooseAccountPurpose purpose)
{
this.RemoveChildPanels(parent);
ChooseAccountPanel account = new ChooseAccountPanel();
account.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(account, purpose, parent as IPanel);
await MainPanelView.AddPanel(account);
}
public async Task ExecuteChooseCity(UIElement parent, PasswordCredential account)
{
this.RemoveChildPanels(parent);
ChoosePostCityPanel city = new ChoosePostCityPanel();
city.Width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
this.AttachContext(city, account, parent as IPanel);
await MainPanelView.AddPanel(city);
}
public async Task ExecuteAccountManagement(UIElement parent, PasswordCredential account)
{
this.RemoveChildPanels(parent);
AccountManagementPanel am = new AccountManagementPanel();
am.Width = this.PanelView.ActualWidth;
this.AttachContext(am, account, parent as IPanel);
await this.MainPanelView.AddPanel(am);
}
public async Task ExecuteManagePost(UIElement parent, ManagePostContext posting)
{
this.RemoveChildPanels(parent);
ManagePostPanel mp = new ManagePostPanel();
mp.Width = Math.Min(this.PanelView.ActualWidth, 1000);
this.AttachContext(mp, posting, parent as IPanel);
await this.MainPanelView.AddPanel(mp);
}
private void AttachContext(IPanel panel, object context, IPanel parent)
{
EventHandler<IEnumerable<UIElement>> handler = null;
handler = new EventHandler<IEnumerable<UIElement>>((s, col) =>
{
if (col.Contains(panel as UIElement))
{
var t = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
panel.AttachContext(context, parent);
});
MainPanelView.ItemsArranged -= handler;
}
});
MainPanelView.ItemsArranged += handler;
}
#endregion
#region Global
public void SetViewPostWidth(ViewPostPanel panel)
{
if (panel == null)
return;
double width;
if (Settings.Instance.ExpandPost)
{
width = this.MainPanelView.ActualWidth;
}
else
{
int index = MainPanelView.GetPanelIndex(panel);
double complementWidth = 0;
if (index >= 0 && index + 1 < MainPanelView.Children.Count)
complementWidth = MainPanelView.Children[index + 1].DesiredSize.Width;
else if (index > 0)
complementWidth = MainPanelView.Children[index - 1].DesiredSize.Width;
else if (MainPanelView.Children.Count >= 0)
complementWidth = MainPanelView.Children[MainPanelView.Children.Count - 1].DesiredSize.Width;
width = 1000;
if (complementWidth > 0)
width = this.MainPanelView.ActualWidth - complementWidth;
if (width < 600)
width = this.MainPanelView.ActualWidth;
}
panel.Width = width;
this.PanelView.Measure(this.PanelView.DesiredSize);
}
public void SetSearchResultsWidth(SearchResultsPanel panel, bool max)
{
double width;
if (max)
{
width = this.MainPanelView.ActualWidth;
}
else
{
width = Math.Max(MinSearchResultsWidth, this.MinPanelWidth);
}
panel.Width = width;
this.PanelView.Measure(this.PanelView.DesiredSize);
}
public void RemoveChildPanels(UIElement parent)
{
int index = (parent == null ? 0 : MainPanelView.GetPanelIndex(parent)) + 1;
for (int i = index; i < MainPanelView.Children.Count; ++i)
{
UIElement el = MainPanelView.Children[i];
// If we are removing a child panel that is a SearchResultsPanel, we need to make sure we cancel the current
// execution request if one exists.
if (el as SearchResultsPanel != null)
{
(el as SearchResultsPanel).CancelExecution();
}
}
MainPanelView.RemovePanel(index, recursive: true);
BackSideMenuButton.IsEnabled = MainPanelView.Children.Count > 0;
SetViewPostWidth(parent as ViewPostPanel);
}
public void ToggleWebView(bool show)
{
for (int i = 0; i < MainPanelView.Children.Count; ++i)
{
IWebViewHost wvh = MainPanelView.Children[i] as IWebViewHost;
if (wvh != null)
{
wvh.ToggleWebView(show);
}
}
}
public static MainPage Instance
{
get;
set;
}
#endregion
#region Panel Stuff
const int MinSearchResultsWidth = 450;
internal double MinPanelWidth
{
get
{
return Math.Max(375.0, this.ActualWidth / 4.0);
}
}
internal PanelView PanelView
{
get;
private set;
}
internal MainMenuOptionsPanel MainMenu;
#endregion
}
}<file_sep>/Win8/Craigslist8X/Craigslist8X/Model/SavedSearches.cs
using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Notifications;
using WinRTXamlToolkit.Async;
using WB.CraigslistApi;
using WB.Craigslist8X.Common;
using WB.SDK.Logging;
namespace WB.Craigslist8X.Model
{
public class SavedSearches : BindableBase, IStorageBacked
{
#region Initialization
static SavedSearches()
{
_instanceLock = new object();
}
private SavedSearches()
{
this.Queries = new ObservableCollection<SavedQuery>();
this._listLock = new object();
this._fileLock = new AsyncLock();
this._notificationFileLock = new AsyncLock();
}
#endregion
#region Singleton
public static SavedSearches Instance
{
get
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new SavedSearches();
return _instance;
}
}
}
static SavedSearches _instance;
static object _instanceLock;
#endregion
#region IStorageBacked
public async Task<bool> LoadAsync()
{
StorageFile file = null;
try
{
file = await ApplicationData.Current.RoamingFolder.GetFileAsync(SavedSearchesFileName);
}
catch (System.IO.FileNotFoundException)
{
return false;
}
if (file != null)
{
Logger.LogMessage("SavedSearches", "Loading SavedSearches.xml");
try
{
string content = null;
using (await this._fileLock.LockAsync())
{
content = await file.LoadFileAsync();
}
if (string.IsNullOrEmpty(content))
return false;
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
XmlNodeList queries = doc.SelectNodes("/root/sq");
lock (this._listLock)
{
this.Queries.Clear();
foreach (var qn in queries)
{
SavedQuery sq = SavedQuery.Deserialize(qn.GetXml());
sq.PropertyChanged += SavedQuery_PropertyChanged;
this.Queries.Add(sq);
}
}
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("SavedSearches", "Failed to read SavedSearches.xml");
Logger.LogException(ex);
}
}
return false;
}
public async Task<bool> SaveAsync()
{
Logger.LogMessage("SavedSearches", "Saving SavedSearches.xml");
if (!this.Dirty)
{
Logger.LogMessage("SavedSearches", "No changes to persist to SavedSearches.xml");
return false;
}
try
{
StringBuilder sb = new StringBuilder();
sb.Append("<root>");
lock (_listLock)
{
for (int i = 0; i < _queries.Count; ++i)
{
sb.AppendLine(SavedQuery.Serialize(_queries[i]));
}
}
sb.Append("</root>");
using (await this._fileLock.LockAsync())
{
StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(SavedSearchesFileName, CreationCollisionOption.ReplaceExisting);
await file.SaveFileAsync(sb.ToString());
}
this.Dirty = false;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("SavedSearches", "Failed to save SavedSearches.xml");
Logger.LogException(ex);
}
return false;
}
private bool Dirty
{
get;
set;
}
private AsyncLock _fileLock;
#endregion
#region Notification Data
public async Task<bool> LoadNotificationsAsync()
{
if (this._queries == null || this._queries.Count == 0)
return false;
StorageFile file = null;
try
{
file = await ApplicationData.Current.LocalFolder.GetFileAsync(NotificationsFileName);
}
catch (System.IO.FileNotFoundException)
{
return false;
}
if (file != null)
{
try
{
string content = null;
using (await this._notificationFileLock.LockAsync())
{
content = await file.LoadFileAsync();
}
if (string.IsNullOrEmpty(content))
return false;
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
XmlNodeList notifications = doc.SelectNodes("/root/n");
foreach (var n in notifications)
{
Guid guid = Guid.Parse(n.Attributes.GetNamedItem("tile").InnerText);
SavedQuery sq = null;
foreach (var q in this._queries)
{
if (q.TileId == guid)
{
sq = q;
break;
}
}
if (sq != null)
{
sq.Notifications = int.Parse(n.Attributes.GetNamedItem("count").InnerText);
sq.RssNewDate = DateTime.Parse(n.Attributes.GetNamedItem("time").InnerText);
}
}
int count = 0;
foreach (var q in this.Queries)
{
count += q.Notifications;
}
this.Notifications = count;
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("SavedSearches", "Failed to read NotificationsFileName.xml");
Logger.LogException(ex);
}
}
return false;
}
public async Task<bool> SaveNotificationsAsync()
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<root>");
lock (_listLock)
{
for (int i = 0; i < _queries.Count; ++i)
{
sb.AppendLine(string.Format(@"<n tile=""{0}"" count=""{1}"" time=""{2}""/>",
this._queries[i].TileId.ToString(),
this._queries[i].Notifications,
this._queries[i].RssNewDate
));
}
}
sb.AppendLine("</root>");
using (await this._notificationFileLock.LockAsync())
{
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(NotificationsFileName, CreationCollisionOption.ReplaceExisting);
await file.SaveFileAsync(sb.ToString());
}
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
Logger.LogMessage("SavedSearches", "Failed to save SavedSearches.xml");
Logger.LogException(ex);
}
return false;
}
private AsyncLock _notificationFileLock;
#endregion
#region Methods
void SavedQuery_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "Notifications")
{
int count = 0;
foreach (var q in this.Queries)
{
count += q.Notifications;
}
this.Notifications = count;
return;
}
this.Dirty = true;
}
public void Add(SavedQuery query)
{
if (!Settings.Instance.TrackRecentSearches)
return;
// Add to the top because it is the most recent
lock (_listLock)
{
_queries.Insert(0, query);
}
this.Dirty = true;
}
public void Remove(SavedQuery query)
{
lock (_listLock)
{
this._queries.Remove(query);
}
this.Dirty = true;
}
public bool Contains(string name)
{
foreach (var sq in this._queries)
{
if (sq.Name == name)
return true;
}
return false;
}
public SavedQuery Get(string name)
{
foreach (var sq in this._queries)
{
if (sq.Name == name)
return sq;
}
return null;
}
#endregion
#region Properties
public ObservableCollection<SavedQuery> Queries
{
get
{
return _queries;
}
private set
{
this.SetProperty(ref this._queries, value);
}
}
public int Notifications
{
get
{
return this._notifications;
}
set
{
var x = CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High,
() =>
{
if (this.SetProperty(ref this._notifications, value))
{
try
{
if (value == 0)
{
BadgeUpdater updater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
updater.Clear();
}
else
{
XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", value.ToString());
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdater updater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
updater.Update(badge);
}
}
catch
{
}
}
});
}
}
#endregion
#region Fields
ObservableCollection<SavedQuery> _queries;
object _listLock;
int _notifications;
#endregion
#region Constants
const string SavedSearchesFileName = "SavedSearches.xml";
const string NotificationsFileName = "SavedSearchesNotifications.xml";
#endregion
}
} | 23740ae803d3aa267809256c0396521284848ead | [
"Markdown",
"C#"
] | 80 | C# | wbish/Craigslist-8X | 4a829efda20663072ad294e750d26800fc7c5304 | dbb0c9e7ec9ee75b48ed9df26b1745e4c820339e |
refs/heads/master | <file_sep>'use strict';
describe('basics', function() {
beforeEach(function() {
browser.get('/#/basics')
});
it('lists 3 cohorts', function() {
expect(element.all(by.css('.cohort-list tr')).count()).toBe(4);
})
describe('searching for cohorts', function() {
beforeEach(function() {
element(by.model('searchText')).sendKeys('slugs');
});
it('updates searchText model', function() {
expect(element(by.css('.searching')).getText()).toBe('my model is slugs');
});
it('filters cohorts by searchText', function() {
expect(element.all(by.css('.cohort-list tr')).count()).toBe(2)
});
});
});
<file_sep>'use strict';
angular.module('demoApp')
.controller('ChatCtrl', function ($scope, $firebase, firebaseAuth, $rootScope) {
var ref = new Firebase("https://dbc-workshop.firebaseio.com/messages");
$scope.messages = $firebase(ref)
$scope.addMessage = function(e) {
if (e.keyCode != 13) return;
$scope.messages.$add({from: $rootScope.current_user.displayName, body: $scope.msg});
$scope.msg = "";
};
// listen for user auth events
$rootScope.$on("login", function(event, user) {
$scope.$apply()
})
$rootScope.$on("logout", function(event) {
$scope.$apply()
})
});
<file_sep>[<img src='http://devacademy.co.nz/media/logoEnspiralDevAcademySmallest.png' align='right'/>](http://www.devacademy.co.nz)
### angular-workshop
This is a sample angular app to demonstrate some of the core concepts and tools and is designed to give people familiar with javascript their first introduction to angular.
Each branch introduces a new concept and are designed to be followed sequentually.
#### Setup
* Install node, bower, grunt then
```
npm install
bower install
grunt serve
```
#### Tests
both the grunt server and the selenium server (`webdriver-manager start`) need to be running before you can run your tests with `grunt protractor`
You may need to run `sudo npm install -g webdriver-manager` if you get a permission error when running selenium.
#### Links
* Angular blog http://blog.angularjs.org/ - good for news etc.
* Angular modules directory http://ngmodules.org/
* [Setting up a fresh angular install with Yeoman](http://www.sitepoint.com/kickstart-your-angularjs-development-with-yeoman-grunt-and-bower/) (note you will need `npm install --save karma-jasmine karma-chrome-launcher` for tests to pass)
* [Protractor for e2e tests](https://www.npmjs.org/package/generator-protractor)
* [Protractor syntax](https://github.com/angular/protractor/blob/master/docs/api.md)
* [Restangular](http://ngmodules.org/modules/restangular) - an improved version of
the built-in $resource
* [Angular UI](https://github.com/angular-ui/ui-router) is recommended if you
application has anything other than very basic routing needs
* Angular and Rails: [angular-js-rails-resource](http://ngmodules.org/modules/angularjs-rails-resource)
recommended if you are using rails
* [Conceptual overview of Angular for Jquery folks](http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background)
* [Good Angular style guide](https://github.com/toddmotto/angularjs-styleguide) - note that this differs from how the yeoman angular generator sets up your app.
#### DOM Notes
* If you are touching the DOM, always use a directive - [directive docs](http://docs.angularjs.org/guide/directive), [Simple Diretive](http://jsfiddle.net/A8Vgk/7/), [Directive tutorial](http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/)
* You can get by without understanding the scope digest cycle initially but eventually it will bite you [Simple Overview](http://onehungrymind.com/notes-on-angularjs-scope-life-cycle/) - [Complex Overview](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
* always use [angular.element](http://docs.angularjs.org/api/angular.element) to access the DOM
* Gotchya: [ng-include expects an expression, strings must be explicit](http://stackoverflow.com/questions/12521905/angularjs-ng-include-does-not-include-view-unless-passed-in-scope)
#### Auth
* hosted services can save you a ton of time when prototyping but be ready to switch them out for your own backend [Firebase](https://www.firebase.com/) would be our main pick though [Hoist](http://hoistapps.com/) is a local alternative
* if rolling your own consider [token based authentication](http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/)
#### Contributors
* [<NAME>](http://github.com/joshuavial)
| e17c355c98eb60bf7025f56c0b5e6337a9c95b5f | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | enspiral-dev-academy/angular-workshop | fa1180e26eee9a691b4da07e6ab507bea73d7867 | d78b5e321f107a64bf944ee0ed4cbc4234b283ec |
refs/heads/main | <file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LayoutRoutingModule } from './layout-routing.module';
import { BaseModule } from '../base/base.module';
import { PostJobComponent } from './post-job/post-job.component';
import { LayoutComponent } from './layout.component';
@NgModule({
declarations: [LayoutComponent, PostJobComponent],
imports: [
CommonModule,
BaseModule,
LayoutRoutingModule
]
})
export class LayoutModule { }
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {
AuthGuardService as AuthGuard
} from './services/auth-guard.service'
const routes: Routes = [
{
path: 'auth', loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
},
{
path: 'base', loadChildren: () => import('./base/base.module').then(m => m.BaseModule),
canActivate: [AuthGuard]
// component:BaseComponent
},
{
path: 'layout', loadChildren: () => import('./layout/layout.module').then(m => m.LayoutModule),
canActivate: [AuthGuard]
// component:BaseComponent
},
{
path: '',
redirectTo: '/auth/user/signin',
pathMatch: 'full'
},
{
path: '**',
redirectTo: '/auth/user/signin'
}
// {
// path: '',
// redirectTo: '/',
// pathMatch: 'full'
// },
// {
// path: '**',
// redirectTo: '/'
// }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit {
form: FormGroup;
loading = false;
submitted = false;
constructor(
private formBuilder: FormBuilder,
private _router: Router,
private _authService: AuthService,
private _toastrService: ToastrService, private SpinnerService: NgxSpinnerService
) { }
ngOnInit() {
this.form = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
// convenience getter for easy access to form fields
get f() { return this.form.controls; }
onSubmit() {
this.submitted = true;
console.log(this.form)
if (this.form.valid) {
const json = {};
json['email'] = this.form.controls.email.value;
json['password'] = this.form.controls.password.value;
this._authService.candidateLogin(json).subscribe(response => {
if (response.result !== 'fail') {
this.submitted = false;
sessionStorage.setItem('_ud', JSON.stringify(response.data))
this._router.navigate(['/layout/post-job'])
this.form.reset();
this._toastrService.success(
'User LoggedIn successfully', response.result,
{ toastClass: 'toast ngx-toastr', closeButton: true }
);
} else {
this._toastrService.error(
response.message, response.result
)
}
})
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ExpertRoutingModule } from './expert-routing.module';
import { ReactiveFormsModule } from '@angular/forms';
import { NgxSpinnerModule } from 'ngx-spinner';
import { SignUpComponent } from './sign-up/sign-up.component';
import { SignInComponent } from './sign-in/sign-in.component';
import { ExpertComponent } from './expert.component';
@NgModule({
declarations: [ExpertComponent, SignInComponent, SignUpComponent],
imports: [
CommonModule,
ExpertRoutingModule,
ReactiveFormsModule,
NgxSpinnerModule
]
})
export class ExpertModule { }
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class AuthService {
// userToken = sessionStorage.getItem('_ud') !== undefined && sessionStorage.getItem('_ud') !== null && sessionStorage.getItem('_ud') !== '' ? JSON.parse(sessionStorage.getItem('_ud'))[0].token : ''
constructor(private _httpClient: HttpClient) { }
userLogin(body) {
return this._httpClient.post<any>(`${environment.apiUrl}/user/login`, body).pipe(
map(response => {
return response;
})
);
}
userRegister(body) {
return this._httpClient.post<any>(`${environment.apiUrl}/user/registration`, body).pipe(
map(response => {
return response;
})
);
}
candidateLogin(body) {
return this._httpClient.post<any>(`${environment.apiUrl}/candidate/login`, body).pipe(
map(response => {
return response;
})
);
}
candidateRegister(body) {
return this._httpClient.post<any>(`${environment.apiUrl}/candidate/registration`, body).pipe(
map(response => {
return response;
})
);
}
expertLogin(body) {
return this._httpClient.post<any>(`${environment.apiUrl}/expert/login`, body).pipe(
map(response => {
return response;
})
);
}
expertRegister(body) {
return this._httpClient.post<any>(`${environment.apiUrl}/expert/registration`, body).pipe(
map(response => {
return response;
})
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import { LayoutService } from 'src/app/services/layout.service';
@Component({
selector: 'app-post-job',
templateUrl: './post-job.component.html',
styleUrls: ['./post-job.component.scss']
})
export class PostJobComponent implements OnInit {
specializationData: any;
locationData: any;
graduationData: any;
constructor(private _layoutService: LayoutService, private _toastrService: ToastrService) { }
ngOnInit(): void {
this.getLocationData();
this.getGraduationData();
this.getSpecializationData();
}
getLocationData() {
this._layoutService.getLocationList().subscribe(response => {
if (response.result !== 'fail') {
this.locationData = response.data;
} else {
this._toastrService.error(
response.message, response.result
)
}
})
}
getSpecializationData() {
this._layoutService.getSpecializationList().subscribe(response => {
if (response.result !== 'fail') {
this.specializationData = response.data;
} else {
this._toastrService.error(
response.message, response.result
)
}
})
}
getGraduationData() {
this._layoutService.getGraduationList().subscribe(response => {
if (response.result !== 'fail') {
this.graduationData = response.data;
} else {
this._toastrService.error(
response.message, response.result
)
}
})
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CandidateRoutingModule } from './candidate-routing.module';
import { ReactiveFormsModule } from '@angular/forms';
import { NgxSpinnerModule } from 'ngx-spinner';
import { SignUpComponent } from './sign-up/sign-up.component';
import { SignInComponent } from './sign-in/sign-in.component';
import { CandidateComponent } from './candidate.component';
@NgModule({
declarations: [CandidateComponent, SignInComponent, SignUpComponent],
imports: [
CommonModule,
CandidateRoutingModule,
ReactiveFormsModule,
NgxSpinnerModule
]
})
export class CandidateModule { }
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class LayoutService {
userToken = sessionStorage.getItem('_ud') !== undefined && sessionStorage.getItem('_ud') !== null && sessionStorage.getItem('_ud') !== '' ? JSON.parse(sessionStorage.getItem('_ud'))[0].token : ''
constructor(private _httpClient: HttpClient) { }
getSpecializationList() {
return this._httpClient.get<any>(`${environment.apiUrl}/specialization`).pipe(
map(response => {
return response;
})
);
}
getLocationList() {
return this._httpClient.get<any>(`${environment.apiUrl}/location`).pipe(
map(response => {
return response;
})
);
}
getGraduationList() {
return this._httpClient.get<any>(`${environment.apiUrl}/graduation`).pipe(
map(response => {
return response;
})
);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UserRoutingModule } from './user-routing.module';
import { ReactiveFormsModule } from '@angular/forms';
import { NgxSpinnerModule } from 'ngx-spinner';
import { SignUpComponent } from './sign-up/sign-up.component';
import { SignInComponent } from './sign-in/sign-in.component';
import { UserComponent } from './user.component';
@NgModule({
declarations: [UserComponent, SignInComponent, SignUpComponent],
imports: [
CommonModule,
UserRoutingModule,
ReactiveFormsModule,
NgxSpinnerModule
]
})
export class UserModule { }
| 65760a0a367b86d49f1b9a1877768575fd50c5cd | [
"TypeScript"
] | 9 | TypeScript | LeenaPatel96/Rekonnect-webapp | 2a219803335224cdbf91ec62ec5cb758cbe59e20 | b85ec74ffc2416c41f7396523123af8847a276ad |
refs/heads/master | <file_sep>// Copyright (c) 2019 <NAME> All rights reserved.
//
// Created by: <NAME>
// Created on: December 2019
// This program calculates your average grade
#include <iostream>
#include <list>
float calculate(std::list<int> listOfMarks) {
// This function calculates the average of the user's grades
// Variables
float markAverage = 0;
int averageDivider = 0;
// Process
for (int counter : listOfMarks) {
markAverage = markAverage + counter;
averageDivider += 1;
}
markAverage = markAverage/averageDivider;
// Output
return markAverage;
}
int main() {
// This function outputs the users grades and average
// Variables
std::list<int> listOfMarks;
int mark;
float average;
// Input
std::cout << "I will be calculating your overall average." << std::endl;
std::cout << "Enter all of your marks, enter -1 when you're done."
<< std::endl;
std::cout << "" << std::endl;
std::cout << "Enter your mark:" << std::endl;
std::cin >> mark;
listOfMarks.push_back(mark);
while (mark != -1) {
std::cout << "Enter your mark:" << std::endl;
std::cin >> mark;
listOfMarks.push_back(mark);
}
// Process
listOfMarks.pop_back();
average = calculate(listOfMarks);
// Output
std::cout << "" << std::endl;
std::cout << "Your average is " << average << "%" <<std::endl;
}
<file_sep># ICS3U-6-05-CPP
calculates the average of a list of grades
| 442db26825ceaca1bee3e21298b552d4ad7687fe | [
"Markdown",
"C++"
] | 2 | C++ | Trinity-Armstrong/ICS3U-6-05-CPP | ae99cb55c23296ddf3053687a045de422aae2711 | a942c9d5c2bce29d0fa22e3bece64f493a2cf008 |
refs/heads/master | <file_sep>extern void fnADC (void);
<file_sep>#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MKL27Z644.h"
#include "fsl_debug_console.h"
#include "GPIO.h"
#include "LCD_DISPLAY.h"
#include "ADC.h"
int main(void) {
while(1)
{
fnMuestreoCO2();
}
return 0 ;
}
<file_sep># Practice-6
This code does the function of a carbon dioxide detector whose values are obtained by an MQ-135 sensor. The values obtained are averaged against a standard and a percentage, of the carbon dioxide that is reaching the sensor, is shown on an 16x2 LCD screen.
<file_sep>#define AA 0x41
#define BB 0x42
#define CC 0x43
#define DD 0x44
#define EE 0x45
#define F 0x46
#define G 0x47
#define H 0x48
#define I 0x49
#define J 0x4A
#define K 0x4B
#define L 0x4C
#define M 0x4D
#define N 0x4E
#define O 0x4F
#define P 0x50
#define Q 0x51
#define RR 0x52
#define S 0x53
#define T 0x54
#define U 0x55
#define V 0x56
#define W 0x57
#define X 0x58
#define Y 0x59
#define Z 0x5A
#define DOSPUNTOS 0x3A
#define ESPACIO 0x20
#define PRIMERALINEA 0x80
#define SEGUNDALINEA 0xC0
#define PORCIENTO 0x25
#define CERO 0x30
#define UNO 0x31
#define DOS 0x32
#define TRES 0x33
#define CUATRO 0x34
#define CINCO 0x35
#define SEIS 0x36
#define SIETE 0x37
#define OCHO 0x38
#define NUEVE 0x39
#define NUMEROBASE 0x30
#define SEGUNDO 925926 /*La duración de un segundo*/
#define NUMERO 2 /*Define durante cuanto tiempo se quiere visualizar el resultado*/
#define CONVERSION_ADC 0x4003b010
extern void fnDelay(void);
extern void fnLCD_Enable(int bPulso);
extern void fnRS_DATAorINSTRUCTION (int bModo);
extern void fnLCD_Inicializacion(void);
extern void fnClearScreen (void);
extern void fnLCD_CambiardeFila(int bLinea);
extern void fnMensaje(void);
extern void fnPorcentaje(int bResultado);
extern void fnSeg(void);
extern void fnMuestreoCO2(void);
extern void fnErrordeMuestreo(void);
<file_sep>#ifndef TURNON_CLKS_H_
#define TURNON_CLKS_H_
extern void fnTurnOn_Clks (void);
#endif /* TURNON_CLKS_H_ */
<file_sep>#include "MKL27Z644.h"
void fnTurnOn_Clks (void)
{
SIM->SCGC5=0x3E00;
}
<file_sep>#include "ADC.h"
#include "MKL27Z644.h"
#include "GPIO.h"
void fnADC (void)
{
SIM -> SCGC6 |= SIM_SCGC6_ADC0(ON); /*Activo el reloj para el ADC*/
PORTE->PCR[20] |= PORT_PCR_MUX(OFF); /*Activo el Puerto E20 como opción de ADC*/
ADC0->CFG1 |= ADC_CFG1_MODE(0b00);
ADC0->SC3 |= ADC_SC3_ADCO(0b0);
ADC0->SC1[0] = ADC_SC1_ADCH(0b00000);
}
//REGISTRO DE SOP PARA VER QUE RELOJ LE VOY A PROVEER.
//PINES CON LOS ENABLE
<file_sep>#include "board.h"
#include "clock_config.h"
#include "MKL27Z644.h"
#include "LCD_DISPLAY.h"
#include "GPIO.h"
#include <stdio.h>
#include "ADC.h"
void fnLCD_Enable(int bPulso) /*Función para habilitar el ENABLE*/
{
if (bPulso == 1)
{
fnDigitalwrite (E, 0, ON); /*Manda el pulso positivo*/
fnDelay(); /*Hace un Delay para alcanzar a tomar el pulso*/
fnDigitalwrite (E, 0, OFF);/*Manda el pulso negativo*/
}
}
void fnRS_DATAorINSTRUCTION(int bModo) /*Función capaz de configurar el RS para mandar comandos o datos*/
{
if(bModo == 1) /*Para mandarle un dato*/
{
fnDigitalwrite (E, 1, ON);
}
else if (bModo == 0) /*Para mandarle comando*/
{
fnDigitalwrite (E, 1, OFF);
}
}
void fnClearScreen (void) /*Función para limpiar la Pantalla*/
{
fnDigitalwrite (E, 1, OFF);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= 0x01;
fnLCD_Enable(1);
}
void fnLCD_Inicializacion(void) /*Inicialización de los puertos*/
{
long *dwgpClockenabled; /*Apuntador para habilitar los relojes de los puertos*/
dwgpClockenabled = (long *) SIM5; /*Se da para activar los relojes de los puertos*/
*dwgpClockenabled = CLOCK_ON;
fnPinMODE (E, 0, OUTPUT); /*Se selecciona los pines que seran RS (E1) y los de ENABLE (E0)*/
fnPinMODE (E, 1, OUTPUT);
fnPinMODE (D, 0, OUTPUT); /*Se seleccionan los pines que van a ser los 8 bits para controlar el LCD*/
fnPinMODE (D, 1, OUTPUT);
fnPinMODE (D, 2, OUTPUT);
fnPinMODE (D, 3, OUTPUT);
fnPinMODE (D, 4, OUTPUT);
fnPinMODE (D, 5, OUTPUT);
fnPinMODE (D, 6, OUTPUT);
fnPinMODE (D, 7, OUTPUT);
fnDigitalwrite (E, 1, OFF); /*Prende la pantalla en el modo de 8-bits*/
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= 0x38; /*Manda instruccion para modo de 8-bits*/
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= 0x0F; /*Display on, cursor blinking para modo de 8-bits*/
fnLCD_Enable(1);
}
void fnMensaje(void) /*Función para enviar mensaje en la primera linea sobre medición de CO2*/
{
/*Escribo mensaje de la distancia es y me coloco en la segunda línera*/
fnDigitalwrite (E, 1, ON);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= P;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= O;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= RR;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= CC;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= EE;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= N;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= T;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= AA;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= J;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= EE;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= ESPACIO;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= DD;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= EE;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= CC;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= O;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= DOS;
fnLCD_Enable(1);
}
void fnLCD_CambiardeFila(int bLinea) /*Función capaz de determinar en que fila quiere escribir*/
{
fnDigitalwrite (E, 1, OFF);
if(bLinea == 1)
{
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= PRIMERALINEA; /*Manda instruccion para modo de 8-bits*/
fnLCD_Enable(1);
}
else if(bLinea == 2)
{
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= SEGUNDALINEA; /*Manda instruccion para modo de 8-bits*/
fnLCD_Enable(1);
}
}
void fnPorcentaje(int bResultado) /*Función donde se lleva a cabo el procesamiento del dato para mostrarlo*/
{
int bMillares= bResultado/1000;
int bCentenas= (bResultado-(bMillares*1000))/100;
int bDecenas= (bResultado-(bMillares*1000+bCentenas*100))/10;
int bUnidades= (bResultado-(bMillares*1000+bCentenas*100+bDecenas*10));
fnDigitalwrite (E, 1, ON);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= NUMEROBASE + bMillares;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= NUMEROBASE + bCentenas;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= NUMEROBASE + bDecenas;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= NUMEROBASE + bUnidades;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= PORCIENTO;
fnLCD_Enable(1);
}
void fnMuestreoCO2(void) /*Función donde se va tomando el muestreo*/
{
long *pdwResultado;
int bgResultado;
fnLCD_Inicializacion();
fnLCD_CambiardeFila(1);
fnMensaje();
fnLCD_CambiardeFila(2);
fnADC();
pdwResultado = (long *) CONVERSION_ADC;
printf("%d\n", *pdwResultado);
bgResultado = 0 + (*pdwResultado * 5.5);
if(bgResultado >= 500)
{
fnPorcentaje(bgResultado);
}
else if(bgResultado < 500)
{
fnErrordeMuestreo();
}
fnSeg();
fnClearScreen();
}
void fnErrordeMuestreo(void)
{
/*Escribo mensaje de que el rango de medicion es muy bajo y me coloco en la segunda línera*/
fnDigitalwrite (E, 1, ON);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= M;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= U;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= EE;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= S;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= T;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= RR;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= AA;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= ESPACIO;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= EE;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= RR;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= RR;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= O;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= N;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= EE;
fnLCD_Enable(1);
GPIOD->PDOR &= ~(0xFF); /*Limpia mis salidas*/
GPIOD->PDOR |= AA;
fnLCD_Enable(1);
}
void fnDelay() /*Delay para que el LCD alcance a detectar el pulso del ENABLE*/
{
long dwDelay = 29000;
for (long dwCuenta=0; dwCuenta < dwDelay; dwCuenta++)
dwCuenta += 1;
}
void fnSeg(void)
{
long dwDelay = NUMERO * SEGUNDO;
for (long dwCuenta=0; dwCuenta < dwDelay; dwCuenta++) /*Realiza una cuenta hasta 925926, que es igual a esperar un segundo*/
dwCuenta += 1;
return;
}
| 8c60faf430a5a46c30b1ac5b120d716ca4061e5e | [
"Markdown",
"C"
] | 8 | C | PauloDGL/Practice-6 | 59b6f4dfc799e13b3775de7ced6f2913b5b206c3 | ab4f792afba45fffc1902c08ade851c09e566eea |
refs/heads/master | <repo_name>klevec/fluid-future-studios<file_sep>/dist/js/mobile-menu.js
$(document).ready(function(){
var obj = $('#touch-menu');
var offset = obj.offset();
var topOffset = offset.top;
var marginTop = obj.css("marginTop");
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
if (scrollTop >= topOffset){
obj.css({
marginTop: -245,
position: 'fixed',
});
}
if (scrollTop < topOffset){
obj.css({
marginTop: 0,
position: 'relative',
});
}
});
});
$(document).ready(function(){
var obj = $('nav');
var offset = obj.offset();
var topOffset = offset.top;
var marginTop = obj.css("marginTop");
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
if (scrollTop >= topOffset){
obj.css({
marginTop: -190,
position: 'fixed',
});
}
if (scrollTop < 440){
obj.css({
marginTop: 0,
position: 'relative',
});
}
});
});<file_sep>/dist/about-ffs.php
<?php
/*
Template Name: Our story
*/
?>
<?php get_header(); ?>
<div class="heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-about-ffs.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Our Story</h1>
</div>
</div>
</div>
<div class="design-text">
<div class="container">
<h3 align="center" style="margin: 20px 0"><p><b>Fluid Future believes the music industry shouldn't control artistry.</b></p></h3>
<div class="col-md-6" style="margin-left: 0; padding-left: 0">
<p>With a handful of companies controlling over 80% of the music space - it's been harder than ever to get the perfect sound and monetize your passion: music.</p>
<p>No one pays for music anymore. Still musicians seem to come from everywhere these days. This larger market of artists created a new need for music related services (djing/recording studios).</p>
<p><b>We build solutions for aspiring musicians, and hope to create a new market of jobs available to musicians.</b></p>
<p>To create a recording revolution, we designed an entry level studio with a super smooth learning curve allowing anyone with a laptop to operate a studio in their basement, garage, in home studio, etc. and fits in the back seat of a car.</p>
<p>Our studios, the Evergreen Omnibooth and Bandstand, are recording booths made for beginner artists and seasoned pros trying to get a great sound. And it doesn't stop there.</p>
</div>
<div class="col-md-6">
<img class="img-responsive" style="margin: 10px auto" src="<?php bloginfo('template_directory'); ?>/images/our-story.jpg" alt="fluid future company">
</div>
<div class="clearfix"></div>
<p>It sets up in 15 minutes the first time, and turns on with a flip of a switch after that. You can take it to your friends house, use it on the street, all without tearing up the closet in your guest bedroom.</p>
<p>This is great for recording artist who already own equipment as well. Having your core setup already intact when you arrive at the venue can easily save 30 minutes in setup time at the beginning and end of gigs. The case also functions as your road gear, with simple sliding in and out of cars.</p>
<p><b>We believe creating music is an essential part of the human experience.</b></p>
<p>Studios should not be contained to just professionals.</p>
<p>We created an entirely portable studio with a built in sound booth.</p>
<p><b>The best part: our low end model comes fully loaded for $750.</b></p>
<p>This is the lowest entry price into recording studios ever. And with mainstream studios charging 50-100 an hour, we want to start a home studio revolution: moving recording to individual studios that allow artist to make more money and customers to save money and collaborate with other artists.</p>
</div>
</div>
<?php get_footer(); ?><file_sep>/dist/design.php
<?php
/*
Template Name: Design
*/
?>
<?php get_header(); ?>
<div class="small-heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-design.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Design</h1>
</div>
</div>
</div>
<div class="design-text">
<div class="container">
<p>We started with the philosophy that less is more. The less stuff you need to record, the more places you can take it. The weight and portability of the unit was the first thing we focused on when constructing our vocal booth. Once we found a rugged, portable solution we then used extensive feedback and testing with our focus group to create the only cutting edge studio that can be delivered to your house and set up in under 30 minutes.</p>
<p><b>Radiobooth:</b></p>
<p>Coming Soon!</p>
<p>Perfect for podcasters and radio broadcasters that want to record on-the-go. Check out our current prototype!</p>
<p>Click <a data-toggle="modal" href="#responsive">“Subscribe”</a> to stay up to date about studio development.</p>
<p><b>Omnibooth Pro:</b></p>
<p>Coming Soon!</p>
<p>With the Omnibooth Pro, you’ll be able to get a good sound anywhere you go. This is our most versatile model. Perfect for anyone that wants to record but does not want to pay professional recording studio fees.</p>
<p>Click <a data-toggle="modal" href="#responsive">“Subscribe”</a> to stay up to date about studio development.</p>
<p><b>Bandstand:</b></p>
<p>Coming Soon!</p>
<p>The Bandstand is currently in the works! Imagine everything you need for an entire band to setup and record anywhere. <p>The Bandstand will be our most substantial studio.</p>
<p>Click <a data-toggle="modal" href="#responsive">“Subscribe”</a> to stay up to date about studio development.</p>
<p><i>*Every studio comes with an allen wrench and encouragement to get creative*</i></p>
</div>
</div>
<?php get_footer(); ?>
<file_sep>/dist/js/animation.js
$('.secondLeft').waypoint( function() {
$(this).addClass('fadeInLeft');
}, {
offset: '95%'
});
$('.secondRight').waypoint( function() {
$(this).addClass('fadeInRight');
}, {
offset: '95%'
});
$('.evergreen').waypoint( function() {
$(this).addClass('fadeInUp');
}, {
offset: '90%'
});
$('.light').waypoint( function() {
$(this).addClass('fadeIn');
}, {
offset: '90%'
});
$('.price').waypoint( function() {
function countnumb(id,from,to,duration){var element=document.getElementById(id);var start=new Date().getTime();setTimeout(function(){var now=(new Date().getTime())-start;var progress=now/duration;var result=Math.floor((to-from)*progress+from);element.innerHTML=progress<1?result:to;if(progress<1)setTimeout(arguments.callee,10)},10)}
$(this).addClass('pricenow');
countnumb("count1", 0, 1000, 2000);
countnumb("count2", 0, 750, 2000);
countnumb("count3", 0, 2000, 2000);
}, {
offset: '95%'
});
$(document).ready(function() {
$(".text-preview").dotdotdot({
ellipsis: '... ',
wrap: 'word',
fallbackToLetter: true,
after: null,
watch: false,
height: 145,
tolerance: 0,
callback: function( isTruncated, orgContent ) {},
lastCharacter : {
remove : [ ' ', ',', ';', '.', '!', '?' ],
noEllipsis : []
}
});
});
$(document).ready(function() {
$(".preview-header").dotdotdot({
ellipsis: '... ',
wrap: 'word',
fallbackToLetter: true,
after: null,
watch: false,
height: 50,
tolerance: 0,
callback: function( isTruncated, orgContent ) {},
lastCharacter : {
remove : [ ' ', ',', ';', '.', '!', '?' ],
noEllipsis : []
}
});
});
<file_sep>/dist/404.php
<?php get_header(); ?>
<div class="heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-404.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">404. Nothing here!</h1>
<h2 class="subtitle">There’s better stuff on <a href="<?php bloginfo('url'); ?>/blog/">the blog</a> anyway!</h2>
</div>
</div>
</div>
<?php get_footer(); ?><file_sep>/dist/index.php
<?php get_header(); ?>
<div class="heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-blog.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Blog</h1>
</div>
</div>
</div>
<div class="container">
<?php while ( have_posts() ) : the_post(); ?>
<article class="news <?php post_class(); ?>" id="post-<?php the_ID(); ?>">
<div class="col-md-4">
<?php $thumbnail_attributes = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium' ); ?>
<img src="echo $thumbnail_attributes[0];" class="img-responsive" alt="fluid future studios">
</div>
<div class="col-md-8">
<h3><a title="<?php printf( esc_attr__( 'Permalink to %s', 'striped' ), the_title_attribute( 'echo=0' ) ); ?>" href="<?php the_permalink(); ?>" rel="bookmark">
<?php the_title(); ?></a></h3>
<i><?php the_date('Y-m-d', '<h2>', '</h2>'); ?></i>
<?php the_content(); ?>
<a href="<?php the_permalink(); ?>"><button>Read more...</button></a>
<div class="clearfix"></div>
</div>
</article>
<?php endwhile; ?>
</div>
<?php get_footer(); ?>
<file_sep>/dist/footer.php
<footer>
<div class="container">
<div class="row">
<div class="col-md-2">
<a href="<?php bloginfo('url'); ?>"><img class="img-responsive" src="<?php bloginfo('template_directory'); ?>/images/footer-logo.jpg" alt="fluid future studios"></a>
</div>
<div class="col-md-2">
<h3>Company</h3>
<ul>
<li><a href="<?php bloginfo('url'); ?>/our-story/">About FFS</a></li>
<li><a href="<?php bloginfo('url'); ?>/meet-the-team/">Our team</a></li>
<li><a href="<?php bloginfo('url'); ?>/contact/">Contact us</a></li>
<li><a href="<?php bloginfo('url'); ?>/blog/">Our blog</a></li>
</ul>
</div>
<div class="col-md-2">
<h3>Our studios</h3>
<ul>
<li><a href="<?php bloginfo('url'); ?>/design/">Design</a></li>
<li><a href="<?php bloginfo('url'); ?>/omnibooth-pro/">Omnibooth Pro</a></li>
<li><a href="<?php bloginfo('url'); ?>/radiobooth/">Radiobooth</a></li>
<li><a href="<?php bloginfo('url'); ?>/bandstand/">Bandstand</a></li>
</ul>
</div>
<div class="col-md-3">
<h3>Contact us</h3>
<ul>
<li><a href="tel:+13048253371">(304) 825-3371</a></li>
<li><a href="mailto:<EMAIL>"><EMAIL></a></li>
</ul>
</div>
<div class="col-md-3 social">
<a class="btn btn-social-icon btn-lg btn-fluid" href="https://facebook.com/fluidfuture" target="_blank" rel="nofollow">
<i class="fa fa-facebook"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-fluid" href="https://twitter.com/fluidfuture" target="_blank" rel="nofollow">
<i class="fa fa-twitter"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-fluid" href="https://instagram.com/fluidfuture" target="_blank" rel="nofollow">
<i class="fa fa-instagram"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-fluid" href="https://soundcloud.com/fluidfuture" target="_blank" rel="nofollow">
<i class="fa fa-soundcloud"></i>
</a>
</div>
</div>
</div>
<div class="copywright"><a href="<?php bloginfo('url'); ?>">Fluid Future Studios © 2015</a></div>
</footer>
</body>
</html>
<file_sep>/dist/home.php
<?php
/*
Template Name: Homepage
*/
?>
<?php get_header(); ?>
<div class="homepage-heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-homepage.jpg')">
<div class="container">
<h1>Really Simple Studios</h1>
<div class="quote">
<p class="animated zoomInRight delay">Made with recording artist, onstage performers, and podcasters in mind: We are a community of DIY recording enthusiasts. Join us, share, and start making your own sounds to join the revolution.</p>
<b class="animated zoomInLeft delay">We’ll hear you on the other side</b>
</div>
</div>
</div><div class="row secondblock">
<div class="container">
<div class="col-md-6 animated secondLeft boxhidden">
<h2>Millions of aspiring musicians</h2>
<p>Give up on their musical ambitions every year. We want to make learning about audio one of the most enjoyable parts of becoming a musician. Learn faster. </p>
</div>
<div class="col-md-6 animated secondRight boxhidden delay">
<h2>The Evergreen was designed</h2>
<p>To give portable, stylish options to the prosumer (professional consumer) audio market. Our development goal is to create the easiest way to get started and take control of your own sound!</p>
</div>
</div>
</div>
<div class="row thirdblock">
<div class="container">
<div class="col-md-2 solution animated evergreen boxhidden">
<p>Our</p>
<p>Solution</p>
<p><b>The Evergreen</b></p>
</div>
<div class="col-md-5 animated evergreen boxhidden">
<img src="<?php bloginfo('template_directory'); ?>/images/fluidfuture1.jpg" class="img-responsive" alt="fluid future studios">
</div>
<div class="col-md-5 animated evergreen boxhidden">
<img src="<?php bloginfo('template_directory'); ?>/images/fluidfuture2.jpg" class="img-responsive" alt="fluid future studios">
</div>
</div>
</div>
<div class="row fourthblock">
<div class="container">
<div class="col-md-6 animated light boxhidden">
<h4 style="margin-bottom: 22px"><b>We are the future</b></h4>
<p>We’re passionate about advancing the personal recording market by providing all-in-one audio solutions to satisfy a growing need of artists eager to create music, make money, and go professional in a fraction of the time, in any city, no matter how small, all with an affordable upfront investment.</p>
</div>
<div class="col-md-6 animated light boxhidden">
<p>Fluid Future was created by musicians who believe the next generation of music should be recorded by you whenever life hits with some musical inspiration.</p>
<p>Our first project, Evergreen portable studios, is a stepping stone into music technology. Our next works aims to change the way artists monetize their hobby through the web.</p>
</div>
</div>
</div>
<div class="subscribe">
<div class="subscribeform">
<h2>Join our Journey</h2>
<form class="form-inline" name="subscribe" method="post" action="<?php bloginfo('template_directory'); ?>/subscribe.php">
<div class="form-group">
<input type="text" class="form-control" id="exampleInputName2" placeholder="Name" name="fullname">
</div>
<div class="form-group">
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email" name="email">
</div>
<button type="submit" class="btn hvr-sweep-to-right">Subcscribe</button>
</form>
<p>Sign up in the boxes above for email updates on our journey! We promise to never spam you!</p>
</div>
</div>
<!-- <div class="row fifthblock"> -->
<div class="container fifthblock">
<h2>Our studio models</h2>
<div class="col-md-4 model">
<div class="tableline"></div>
<table class="table table-striped table-bordered">
<tr><td class="thead">Evergreen Radiobooth</td></tr>
<tr><td><br><span class="price boxhidden">$ <span id="count1">1000</span></span><p>One time</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2x Radio Microphones</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2x Radio Mic Arms</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2 Channel Interface</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Single Cabinet</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dome Workstation</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dedicated FFS rep to ensure satisfaction</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> All the Cords You Need</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Weighs Under 20 pounds</p></td></tr>
<tr><td class="buy"><a class="btn hvr-grow" href="#"><i class="fa fa-shopping-cart fa-lg"></i> Buy now</a>
<p class="learnmore"><a href="<?php bloginfo('url'); ?>/radiobooth/">Learn more</a></p>
</td></tr>
</table>
</div>
<div class="col-md-4">
<table class="table table-green-striped table-bordered">
<tr><td class="topthead">Evergreen Omnibooth Pro
<p>(most popular)</p>
</td></tr>
<tr><td><br><span class="price boxhidden">$ <span id="count2">750</span></span><p>One time</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 1x Vocal Microphone</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Pop Out Vocal Booth</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2 Channel Interface</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Single Cabinet</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dome Workstation</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dedicated FFS rep to ensure satisfaction</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> All the Cords You Need</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Weighs Under 20 pounds</p></td></tr>
<tr><td class="buy"><a class="btn hvr-grow" href="#"><i class="fa fa-shopping-cart fa-lg"></i> Buy now</a>
<p class="learnmore"><a href="<?php bloginfo('url'); ?>/omnibooth-pro/">Learn more</a></p>
</td></tr>
</table>
</div>
<div class="col-md-4 model">
<div class="tableline"></div>
<table class="table table-striped table-bordered">
<tr><td class="thead">Evergreen Bandstand</td></tr>
<tr><td><br><span class="price boxhidden">$ <span id="count3">2000</span></span><p>One time</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 4x Live Microphones</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2x Pop Out Vocal Booth</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 4 Channel Interface</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dual Cabinet</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dome Workstation</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dedicated FFS rep to ensure satisfaction</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> All the Cords You Need</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Weighs Under 30 pounds</p></td></tr>
<tr><td class="buy"><a class="btn hvr-grow" href="#"><i class="fa fa-shopping-cart fa-lg"></i> Buy now</a>
<p class="learnmore"><a href="<?php bloginfo('url'); ?>/bandstand/">Learn more</a></p>
</td></tr>
</table>
</div>
</div>
</div>
<div class="ebookblock">
<div class="container">
<div class="col-md-4">
<img src="<?php bloginfo('template_directory'); ?>/images/sticker.png" alt="sticker" class="img-responsive">
</div>
<div class="col-md-8 animated evergreen boxhidden">
<h2>Get started on your studio</h2>
<span>now</span>
<button>Get our FREE eBook</button>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="videoblock">
<div class="container">
<h2 class="animated secondLeft boxhidden">The Future of Portable Sound
<span class="animated light longdelay boxhidden"><i class="fa fa-level-down"></i></span></h2>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="http://player.vimeo.com/video/74013667"></iframe>
</div>
</div>
</div>
<div class="sixthblock">
<div class="container">
<h2>Visit our blog</h2>
<div class="row">
<?php $posts = get_posts ("category=1&orderby=date&numberposts=3"); ?>
<?php if ($posts) : ?>
<?php foreach ($posts as $post) : setup_postdata ($post); ?>
<div class="col-md-4 animated light boxhidden">
<div class="blogpreview">
<a href="<?php the_permalink() ?>"><h3 class="preview-header"><?php the_title(); ?></h3></a>
<a href="<?php the_permalink() ?>"><?php echo the_post_thumbnail(array (150,150), array('class' => 'img-responsive')); ?></a>
<div class="text-preview">
<?php the_content(); ?>
</div>
<a href="<?php the_permalink(); ?>"><button>Read more</button></a>
<div class="clearfix"></div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</div>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/waypoints.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/animation.js"></script>
<?php get_footer(); ?>
<file_sep>/dist/header.php
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
<title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' |'; } ?> <?php bloginfo('name'); ?></title>
<link rel="icon" href="<?php bloginfo('template_directory'); ?>/favicon/favicon.png" type="image/x-icon"/>
<link rel="shortcut icon"<?php bloginfo('template_directory'); ?>/href="favicon/favicon.png" type="image/x-icon"/>
<link rel="apple-touch-icon" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon.png">
<link rel="apple-touch-icon" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="57x57" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="72x72" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="<?php bloginfo('template_directory'); ?>/favicon/apple-touch-icon-152x152.png">
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/css/bootstrap.css" type="text/css" media="screen">
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/css/bootstrap.social.css" type="text/css" media="screen">
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/css/font-awesome.css" type="text/css" media="screen">
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/css/animate.css" type="text/css" media="screen">
<link href="<?php bloginfo('template_directory'); ?>/css/bootstrap-modal-bs3patch.css" rel="stylesheet" />
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/css/bootstrap-modal.css" type="text/css" media="screen">
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/style.css" type="text/css" media="screen">
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.js" ></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/touch-menu.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/sticky-menu.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/dotdotdot.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/bootstrap-modal.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/bootstrap-modalmanager.js"></script>
<!--[if lt IE 9]>
<script src="http://css3-mediaqueries-js.googlecode.com/files/css3-mediaqueries.js"></script>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-md-7">
<a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/logo.png" alt="Fluid Future Studios"></a>
</div>
<div class="col-md-5 social">
<div class="phone"><a href="tel:+13048253371">(304) 825-3371</a></div>
<div class="email"><a href="mailto:<EMAIL>"><EMAIL></a></div><br>
<button class="demo btn btn-primary" data-toggle="modal" href="#responsive">Subscribe</button>
<a href="<?php bloginfo('url'); ?>/opt-in/">
<button class="demo btn btn-primary">Learn more</button>
</a>
<!-- Popup -->
<div id="responsive" class="modal fade" tabindex="-1" data-width="500" style="display: none;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Subscribe now</h4>
</div>
<div class="modal-body">
<form class="form-inline" name="subscribe" method="post" action="<?php bloginfo('template_directory'); ?>/subscribe.php">
<div class="form-group">
<input type="text" class="form-control name" id="exampleInputName2" placeholder="Name" name="fullname">
</div>
<div class="form-group">
<input type="email" class="form-control email" id="exampleInputEmail2" placeholder="Email" name="email">
</div>
<button type="submit" class="btn">Subscribe</button>
</form>
</div>
</div>
<script type="text/javascript" src="http://getbootstrap.com/2.3.2/assets/js/google-code-prettify/prettify.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.js"></script>
<!-- Popup -->
</div>
</div>
</div>
</header>
<div id="sticky">
<a href="#" id="touch-menu"><i class="fa fa-bars"></i> <span style="margin-left:10px;"></span>Menu</a>
<nav id="nav">
<div class="container">
<div class="col-md-10">
<ul>
<li><a href="<?php bloginfo('url'); ?>">Home</a></li>
<li class="drop"><span class="dropdown">About us <i class="fa fa-caret-down"></i></span>
<ul>
<li><a href="<?php bloginfo('url'); ?>/meet-the-team/">Meet the Team</a></li>
<li><a href="<?php bloginfo('url'); ?>/our-story/">Our Story</a></li>
</ul>
</li>
<li class="drop"><span class="dropdown">Our studios <i class="fa fa-caret-down"></i></span>
<ul style="width: 181px">
<li><a href="<?php bloginfo('url'); ?>/design/">Design</a></li>
<li><a href="<?php bloginfo('url'); ?>/omnibooth-pro/">Omnibooth Pro</a></li>
<li><a href="<?php bloginfo('url'); ?>/radiobooth/">Radiobooth</a></li>
<li><a href="<?php bloginfo('url'); ?>/bandstand/">Bandstand</a></li>
</ul>
</li>
<li><a href="<?php bloginfo('url'); ?>/contact/">Contact</a></li>
<li><a href="<?php bloginfo('url'); ?>/blog/" class="last">Blog</a></li>
</ul>
</div>
</div>
</nav>
</div>
<file_sep>/dist/contact.php
<?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class="small-heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-contact.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Contact us</h1>
</div>
</div>
</div>
<div class="contact-forms">
<div class="container">
<div class="row">
<div class="col-md-6" style="margin: 50px 0; padding: 0 25px">
<h3>Contact us now</h3><br>
<p>Get in touch!</p>
<p>We would love to chat with you.</p>
<p><b>E-mail:</b> <a href="mailto:<EMAIL>"><EMAIL></a></p>
<p><b>Phone:</b> <a href="tel:+13048253371">+1 (304) 825-3371</a></p>
</div>
<div class="col-md-6">
<form class="form-horizontal" name="feedback" method="post" action="<?php bloginfo('template_directory'); ?>/feedback.php">
<h3>Feedback</h3>
<input type="text" class="form-control" placeholder="<NAME>" name="fullname">
<input type="email" class="form-control" placeholder="Email" name="email">
<textarea class="form-control" rows="4" name="message" id="message" placeholder="Questions, comments, ideas and other feedback"></textarea>
<button type="submit">Submit</button>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
<file_sep>/dist/thankyou.php
<?php
/*
Template Name: Thank you
*/
?>
<?php get_header(); ?>
<div class="heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-thankyou.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Thank you for your interest!</h1>
</div>
</div>
</div>
<?php get_footer(); ?><file_sep>/dist/category.php
<?php get_header(); ?>
<div class="small-heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-blog.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Blog</h1>
</div>
</div>
</div>
<div class="container">
<?php while ( have_posts() ) : the_post(); ?>
<article class="news <?php post_class(); ?>" id="post-<?php the_ID(); ?>">
<div class="col-md-4">
<a href="<?php the_permalink() ?>"><?php echo get_the_post_thumbnail( $post_id, 'full', array( 'class' => 'img-responsive' ) ); ?></a>
</div>
<div class="col-md-8">
<h3><a title="<?php printf( esc_attr__( 'Permalink to %s', 'striped' ), the_title_attribute( 'echo=0' ) ); ?>" href="<?php the_permalink(); ?>" rel="bookmark">
<?php the_title(); ?></a></h3>
<?php the_date('Y-m-d', '<i>', '</i>'); ?>
<div class="text-preview">
<?php the_content(); ?>
</div>
<a href="<?php the_permalink(); ?>"><button>Read more</button></a>
<div class="clearfix"></div>
</div>
</article>
<div class="clearfix"></div>
<?php endwhile; ?>
<div class="blogline"></div>
<div class="navigation">
<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".text-preview").dotdotdot({
ellipsis: '... ',
wrap: 'word',
fallbackToLetter: true,
after: null,
watch: false,
height: 145,
tolerance: 0,
callback: function( isTruncated, orgContent ) {},
lastCharacter : {
remove : [ ' ', ',', ';', '.', '!', '?' ],
noEllipsis : []
}
});
});
</script>
<?php get_footer(); ?>
<file_sep>/dist/functions.php
<?php
add_theme_support( 'post-thumbnails', array( 'post' ) );
function get_posts_5_st( $query ) {
if ( !is_admin() && $query->is_main_query() && is_category(1) ) {
$query->set( 'posts_per_page', 5 );
}
}
add_action( 'pre_get_posts', 'get_posts_5_st' );
?>
<file_sep>/dist/feedback.php
<?php
$headers= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: Fluid Future Studios <<EMAIL>>\r\n";
header("Location: http://ffs.webtm.ru/thankyou/");
if (isset($_POST['fullname'])) {$firstName = $_POST['fullname'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
if (isset($_POST['message'])) {$message = $_POST['message'];}
$message = "New feedback from Fluid Future Studios website: <br><br>
<b>Name:</b> $fullname <br>
<b>Email:</b> $email <br>
<b>Message:</b> $message <br><br>
Have a nice day!";
$subject = "$fullname sent a feedback";
mail('<EMAIL>', $subject, $message, $headers);
?><file_sep>/dist/single.php
<?php get_header(); ?>
<div class="container">
<article class="news <?php post_class(); ?>" id="post-<?php the_ID(); ?>">
<div class="col-md-3">
<a href="<?php the_permalink() ?>"><?php echo get_the_post_thumbnail( $post_id, 'full', array( 'class' => 'img-responsive' ) ); ?></a>
</div>
<div class="col-md-9">
<h3><a title="<?php printf( esc_attr__( 'Permalink to %s', 'striped' ), the_title_attribute( 'echo=0' ) ); ?>" href="<?php the_permalink(); ?>" rel="bookmark">
<?php the_title(); ?></a></h3>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_date('Y-m-d', '<i>', '</i>'); ?>
<?php endwhile; ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<br>
<script type="text/javascript" src="//yastatic.net/share/share.js" charset="utf-8"></script><div class="yashare-auto-init" data-yashareL10n="en" data-yashareType="big" data-yashareQuickServices="facebook,twitter,gplus" data-yashareTheme="counter"></div>
<?php endwhile; ?>
</div>
</article>
</div>
<br><br>
<?php get_footer(); ?><file_sep>/dist/optin.php
<?php
/*
Template Name: Opt in
*/
?>
<?php get_header(); ?>
<div class="small-heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-thankyou.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Opt In</h1>
</div>
</div>
</div>
<div class="container">
<div class="video">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="http://player.vimeo.com/video/74013667"></iframe>
</div>
</div>
</div>
<div class="optsubscribe">
<div class="container">
<h2>Subscribe for our eBook FREE</h2>
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<div class="container fifthblock">
<h2>Our studio models</h2>
<div class="col-md-4 model">
<div class="tableline"></div>
<table class="table table-striped table-bordered">
<tr><td class="thead">Evergreen Radiobooth</td></tr>
<tr><td><br><span class="price">$ <span id="count1">1000</span></span><p>One time</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2x Radio Microphones</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2x Radio Mic Arms</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2 Channel Interface</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Single Cabinet</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dome Workstation</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dedicated FFS rep to ensure satisfaction</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> All the Cords You Need</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Weighs Under 20 pounds</p></td></tr>
<tr><td class="buy"><a class="btn hvr-grow" href="#"><i class="fa fa-shopping-cart fa-lg"></i> Buy now</a>
<p class="learnmore"><a href="<?php bloginfo('url'); ?>/radiobooth/">Learn more</a></p>
</td></tr>
</table>
</div>
<div class="col-md-4">
<table class="table table-green-striped table-bordered">
<tr><td class="topthead">Evergreen Omnibooth Pro
<p>(most popular)</p>
</td></tr>
<tr><td><br><span class="price">$ <span id="count2">750</span></span><p>One time</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 1x Vocal Microphone</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Pop Out Vocal Booth</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2 Channel Interface</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Single Cabinet</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dome Workstation</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dedicated FFS rep to ensure satisfaction</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> All the Cords You Need</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Weighs Under 20 pounds</p></td></tr>
<tr><td class="buy"><a class="btn hvr-grow" href="#"><i class="fa fa-shopping-cart fa-lg"></i> Buy now</a>
<p class="learnmore"><a href="<?php bloginfo('url'); ?>/omnibooth-pro/">Learn more</a></p>
</td></tr>
</table>
</div>
<div class="col-md-4 model">
<div class="tableline"></div>
<table class="table table-striped table-bordered">
<tr><td class="thead">Evergreen Bandstand</td></tr>
<tr><td><br><span class="price">$ <span id="count3">2000</span></span><p>One time</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 4x Live Microphones</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 2x Pop Out Vocal Booth</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> 4 Channel Interface</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dual Cabinet</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dome Workstation</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Dedicated FFS rep to ensure satisfaction</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> All the Cords You Need</p></td></tr>
<tr><td><p><i class="fa fa-check"></i> Weighs Under 30 pounds</p></td></tr>
<tr><td class="buy"><a class="btn hvr-grow" href="#"><i class="fa fa-shopping-cart fa-lg"></i> Buy now</a>
<p class="learnmore"><a href="<?php bloginfo('url'); ?>/bandstand/">Learn more</a></p>
</td></tr>
</table>
</div>
</div>
<!-- <div class="container">
<h2>Follow us</h2>
<div class="col-md-4">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-page" data-href="https://www.facebook.com/fluidfuture" data-width="460" data-height="600" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/fluidfuture"><a href="https://www.facebook.com/fluidfuture">Fluid Future Studios</a></blockquote></div></div>
</div>
<div class="col-md-4">
<a class="twitter-timeline" href="https://twitter.com/FluidFuture" data-widget-id="633246805220794368">Tweets by @FluidFuture</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div>
<div class="col-md-4">
Instagram
</div>
</div> -->
<?php get_footer(); ?>
<file_sep>/dist/about.php
<?php
/*
Template Name: Meet the Team
*/
?>
<?php get_header(); ?>
<div class="small-heading" style="background-image: url('<?php bloginfo('template_directory'); ?>/images/bg-about.jpg')">
<div class="container">
<div class="page-heading">
<h1 class="title">Meet the Team</h1>
</div>
</div>
</div>
<div class="about">
<div class="container">
<div class="row">
<div class="col-md-4">
<img class="img-responsive userpic" src="<?php bloginfo('template_directory'); ?>/images/george.jpg" alt="<NAME>">
<h3>George</h3>
<div class="team-social">
<a href="http://georgekellas.com" class="btn btn-social-icon btn-openid" target="_blank">
<i class="fa fa-heart"></i>
</a>
<a href="https://www.facebook.com/george.kellas" class="btn btn-social-icon btn-facebook" target="_blank">
<i class="fa fa-facebook"></i>
</a>
<a href="https://twitter.com/georgekellas" class="btn btn-social-icon btn-twitter" target="_blank">
<i class="fa fa-twitter"></i>
</a>
<a href="https://plus.google.com/+notquitenews" class="btn btn-social-icon btn-google" target="_blank">
<i class="fa fa-google-plus"></i>
</a>
<a href="https://instagram.com/georgekellas" class="btn btn-social-icon btn-instagram" target="_blank">
<i class="fa fa-instagram"></i>
</a>
</div>
<p>George is not only the face of the business but the thing behind it, the brains, yes, the brains of the operation. He built his first studio with his friends early in high school in attempt to record songs with his friends. George used parts from the hardware store to build “Evergreen1” a room-sized studio wall that is foldable, collapsible, and entirely portable. The portable sound wall satisfied their need for a studio that George’s mom wouldn’t kill him over, and gave him something he could take to college (via truck).</p>
<p>Unfortunately he didn’t own a truck.</p>
<p>This led him to the same conclusion once again:</p>
<p><i>The music technology industry offers no portable recording solutions for aspiring musicians</i></p>
<p>Even this portable studio didn’t fulfill his wish of having a completely portable option. This monster would not be allowed in the dorm rooms, and could barely fit up the stairs of his apartment.</p>
<p>That led him to create <b>the Evergreen Mk2</b>: a completely portable studio.</p>
<img class="img-responsive" src="<?php bloginfo('template_directory'); ?>/images/photo-george.jpg" alt="<NAME>">
</div>
<div class="col-md-4">
<img class="img-responsive userpic" src="<?php bloginfo('template_directory'); ?>/images/colter.jpg" alt="Colter">
<h3>Colter</h3>
<div class="team-social">
<a href="https://www.facebook.com/colter.fragale" class="btn btn-social-icon btn-facebook" target="_blank">
<i class="fa fa-facebook"></i>
</a>
<a href="https://instagram.com/colterfragale" class="btn btn-social-icon btn-instagram" target="_blank">
<i class="fa fa-instagram"></i>
</a>
</div>
<p>Colter opted to go down a non-traditional route after high school, George met him in high school in business classes where they became friends over a mutual interest in 3D printing. Colter went from building scale construction models at trade shows to make extra cash for tools in high school, to building his own garage with his college savings and going into business for himself working full time on digital modeling and design.</p>
<p>He joined the Evergreen project after hearing of our ambitions to change the world’s access to sound.</p>
<p>He is our lead designer and runs studio construction from the designers’ perspective.</p>
<img class="img-responsive" src="<?php bloginfo('template_directory'); ?>/images/photo-colter.jpg" alt="Colter">
</div>
<div class="col-md-4">
<img class="img-responsive userpic" src="<?php bloginfo('template_directory'); ?>/images/zac.jpg" alt="Zac">
<h3>Zac</h3>
<div class="team-social">
<a href="https://www.facebook.com/zac.marra" class="btn btn-social-icon btn-facebook" target="_blank">
<i class="fa fa-facebook"></i>
</a>
<a href="https://twitter.com/zmarra47" class="btn btn-social-icon btn-twitter" target="_blank">
<i class="fa fa-twitter"></i>
</a>
<a href="https://instagram.com/zmarra" class="btn btn-social-icon btn-instagram" target="_blank">
<i class="fa fa-instagram"></i>
</a>
</div>
<p>Zac is enrolled at The University of Wisconsin -- Madison studying entrepreneurship and biomedical engineering. A life-long love for music and the recording progress inspired him to join the Fluid Future Studios team.</p>
<p>He concentrates on managing the group and keeping all of our systems in check, and also leads our Public Relations by working with . This interest in both process and relationships drove him to spearhead the customer management side of the business by focusing on what makes musicians tick.</p>
<p>Zac loves business management and runs the behind the scenes magic that keeps everything on the business side running smoothly. He loves analytics and keeps a close eye on the way advances in technology have affected interaction between people and machines.</p>
<p>He monitors customer happiness and uses lean business mindsets to best serve our customer.</p>
<img class="img-responsive" src="<?php bloginfo('template_directory'); ?>/images/photo-zac.jpg" alt="Zac">
</div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-4">
<img class="img-responsive userpic" src="<?php bloginfo('template_directory'); ?>/images/konstantinos.jpg" alt="Konstantinos">
<h3>Konstantinos</h3>
<div class="team-social">
<a href="https://www.facebook.com/KostaOrJordan" class="btn btn-social-icon btn-facebook" target="_blank">
<i class="fa fa-facebook"></i>
</a>
</div>
<p>Konstantinos is a Greek-American musician and bouzouki artist from Cleveland, Ohio. He has performed alongside and collaborated with many talented singers, musicians, and artists both locally and internationally.</p>
<p>Currently he performs with OLYMPUS, a Greek band centered in Cleveland that performs at festivals, concerts, taverns, and private/corporate events. As a child Konstantinos was inspired musically by his family. With a background in classical violin, he moved on to learning traditional and modern Hellenic music on the bouzouki and guitar, and eventually developed a new passion for the blues, jazz, rock ‘n’ roll, and progressive forms of fusion music. Konstantinos is currently majoring in International Business at Cleveland State University and is additionally studying Music Composition & Theory. Each new component of the Evergreen is first tested by Konstantinos. His years of experience performing live onstage made him our prime candidate for the leader of the musician design team.</p>
<p>Lastly, he leads our vast online community of resources, ranging from studio design and customization to artist branding.</p>
<img class="img-responsive" src="<?php bloginfo('template_directory'); ?>/images/photo-konstantinos.jpg" alt="Konstantinos">
</div>
<div class="col-md-4">
<img class="img-responsive userpic" src="<?php bloginfo('template_directory'); ?>/images/nate.jpg" alt="Nate">
<h3>Nathan</h3>
<div class="team-social">
<a href="https://www.facebook.com/nkwaya.scott" class="btn btn-social-icon btn-facebook" target="_blank">
<i class="fa fa-facebook"></i>
</a>
<a href="https://plus.google.com/117485056350598700994" class="btn btn-social-icon btn-google" target="_blank">
<i class="fa fa-google-plus"></i>
</a>
</div>
<p>Nathan is a self taught guitarist, pianist, and singer originally from Rwanda, Africa. By singing American songs on the radio, he was able to learn English at a young age, and his passion for music has only grown since. He proceeded to learn basic programming skills including C, C++, Visual Basic, Html, CSS, and PHP. After high school, he gathered some of his colleagues and started a local nonprofit organization for teaching preschoolers to read and write in English.</p>
<p>After a lot of hard work, he was accepted into West Virginia University where he is currently pursuing a degree in Mining and Civil Engineering with a Chinese Language minor. His vision and passion for engineering and business drew him to the FFS group where he is helping with marketing strategies and content creation.</p>
<img class="img-responsive" src="<?php bloginfo('template_directory'); ?>/images/photo-nate.jpg" alt="Nate">
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<?php get_footer(); ?>
| 82d423e47b8f85c691047a33a4fb4bb72afffd68 | [
"JavaScript",
"PHP"
] | 17 | JavaScript | klevec/fluid-future-studios | 085f944c7b09d0ec2dca421389aaf5e6a8e2fc39 | bbfd327e003225875a88ba3796ef3a027dca39df |
refs/heads/master | <repo_name>StevenKim1994/Baekjoon-Judge<file_sep>/Baekjoon-Judge-Project/11866.cpp
#include <bits/stdc++.h>
int main()
{
std::list<int> input;
std::list<int> result;
int N, K, end;
std::cin >> N >> K;
for (int i = 1; i <= N; ++i)
input.push_back(i);
auto temp = input.begin();
while(true)
{
if (input.empty() == true)
break;
for(int i =0; i< K -1; ++i)
{
temp++;
if (temp == input.end())
temp = input.begin();
}
result.push_back(*temp);
temp = input.erase(temp);
if (temp == input.end())
temp = input.begin();
}
end = result.back();
result.pop_back();
std::cout << "<";
for (auto i = result.begin(); i != result.end(); ++i)
std::cout << *i << ", ";
std::cout << end << ">";
return 0;
}<file_sep>/Baekjoon-Judge-Project/1152.cpp
#include <iostream>
#include <cstring>
int main()
{
int count = 0;
char input[1000100]; // string 클래스로 받으니까 a b c공백 이 경우 c 뒤에 있는 공백이 입력이 안됨.
std::cin.getline(input, 1000100, '\n');
for (int i = 0; i < strlen(input); ++i)
{
if ((input[i] == '\n') || (input[i] == ' '))
count++;
else
continue;
}
if (strlen(input) == 1 && (input[0] == '\n' || input[0] == ' '))
count = 0;
else if (strlen(input) == 1)
count = 1;
else
{
count++;
if (input[strlen(input) - 1] == ' ')
count--;
if (input[0] == ' ')
count--;
}
std::cout << count;
return 0;
}<file_sep>/Baekjoon-Judge-Project/1946(timelimitexceeded).cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
vector<pair<int,int> > Applicant;
bool Applicant_Pass[1000000];
bool compare(pair<int,int> _a, pair<int,int> _b)
{
if (_a.first < _b.first)
return true;
else
return false;
}
int main()
{
int T;
int N;
int Pass_Num;
pair<int, int> temp;
cin >> T;
for (int testcase = 0; testcase < T; testcase++)
{
int non_pass = 0;
Applicant.clear();
cin >> N;
Pass_Num = N;
for (int i = 0; i < N; i++)
{
cin >> temp.first;
cin >> temp.second;
Applicant.push_back(temp);
}
sort(Applicant.begin(), Applicant.end(), compare);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < Applicant[i].first-1; j++)
{
if (i == j)
continue;
if ((Applicant[i].second > Applicant[j].second) && (Applicant[i].first > Applicant[j].first))
{
Applicant_Pass[i] = true;
non_pass++;
break;
}
else
{
Applicant_Pass[i] = false;
}
}
}
cout << Pass_Num - non_pass << endl;
}
// 왜 시간초과가 뜰까 ? 19.08.06...
return 0;
}<file_sep>/2839.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int bag3[2000];
int bag5[2000];
int main()
{
int N;
int bag5cnt = 0;
int bag3cnt = 0;
int answer = 0;
int answer2 = -999999;
int temp_plus = 0;
int cnt = 0;
bool check = false;
bool check2 = false;
int memo1= 0;
cin >> N;
if (N % 5 == 0)
{
answer = N / 5;
memo1 = answer;
check = true;
}
else if (N % 3 == 0)
{
answer = N / 3;
memo1 = answer;
check = true;
}
while (true)
{
bag5cnt++;
temp_plus = 0;
temp_plus += (5 * bag5cnt);
if (temp_plus > N)
{
check2 = true;
break;
}
if (temp_plus == N)
{
bag3[cnt] = bag3cnt;
bag5[cnt] = bag5cnt;
if (memo1 > bag3[cnt] + bag5[cnt])
answer2 = memo1;
else
answer2 = bag3[cnt] + bag5[cnt];
break;
}
while (true)
{
bag3cnt++;
temp_plus += 3;
if (temp_plus == N)
{
bag3[cnt] = bag3cnt;
bag5[cnt] = bag5cnt;
memo1 = bag3[cnt] + bag5[cnt];
break;
}
else if (temp_plus > N)
{
temp_plus = 0;
bag3cnt = 0;
break;
}
}
cnt++;
}
if ((answer > answer2) && (answer2 > 0) && (answer != 0))
{
cout << answer2 << endl;
}
else if (answer == 0 && answer2 == 0)
{
cout << "-1" << endl;
}
else if ((answer > answer2) && (answer2 < 0) && (answer != 0))
{
if ((memo1 > answer) && (answer != 0) )
cout << answer << endl;
else
cout << memo1 << endl;
}
else if ((answer > answer2) && (answer2 > 0) && (answer != 0))
{
cout << answer2 << endl;
}
else if ((answer < answer2) && (answer2 > 0) && (answer != 0))
{
if ((memo1 > answer) && (answer != 0))
cout << answer << endl;
else
cout << memo1 << endl;
}
else if (answer == 0 && answer2 > 0)
{
cout << answer2 << endl;
}
else if ((memo1 > answer) && (answer != 0))
cout << answer << endl;
else if ((memo1 > answer) && (answer == 0))
cout << memo1 << endl;
else if ((memo1 == answer) && (answer != 0))
{
cout << memo1 << endl;
}
else
{
cout << "-1" << endl;
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/9095.cpp
#include <bits/stdc++.h>
int dp[20];
int main()
{
int n , t;
std::cin >> t;
dp[0] = 0;
dp[1] = 1; // 1 - > 1 °³
dp[2] = 2;// 1 + 1 / 2 - > 2 °³
dp[3] = 4; //1 + 1 + 1 / 2 + 1 / 1 + 2 / 3 - > 4 °³
for (int i = 4; i <= 11; ++i)
dp[i] = dp[i - 3] + dp[i - 2] + dp[i - 1];
for (int i = 0; i < t; ++i)
{
std::cin >> n;
std::cout << dp[n] << '\n';
}
return 0;
}<file_sep>/7568.cpp
#include <iostream>
using namespace std;
#define FOR(i,n) for(int i=0; i<(n); i++)
int main()
{
int Person[50][3]; // Person[index][0] = 몸무게, [1] = 키, [2] = 덩치등수
int N; // 전체사람의 수 최대 N<=50
cin >> N;
FOR(i, N)
{
FOR(j, 2)
{
cin >> Person[i][j];
Person[i][2] = 1;
}
}
FOR(i, N)
{
FOR(j, N)
{
if (i == j) // 자기자신과 비교할때 무시
{
continue;
}
if ((Person[i][0] < Person[j][0]) && (Person[i][1] < Person[j][1]))
{
Person[i][2]++;
}
}
}
FOR(i, N)
{
cout << Person[i][2] << " ";
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2875.cpp
#include <bits/stdc++.h>
int main()
{
int N, M, K;
int t1, t2;
std::cin >> N >> M >> K;
t1 = N / 2;
t2 = N % 2;
if (t2 >= K)
N -= K;
return 0;
}<file_sep>/Baekjoon-Judge-Project/3052.cpp
#include <iostream>
#include <set>
int main()
{
std::set<short> arr;
for (int i = 0; i < 10; ++i)
{
short t;
std::cin >> t;
t = t % 42;
arr.insert(t);
}
std::cout << arr.size();
return 0;
}<file_sep>/Baekjoon-Judge-Project/10828.cpp
#include <bits/stdc++.h>
int main()
{
std::stack<int> st;
std::string input;
int N;
int in;
std::cin >> N;
for(int i = 0; i < N; ++i)
{
std::cin >> input;
if (input == "push")
{
std::cin >> in;
st.push(in);
}
else if (input == "top")
{
if (st.size() <= 0)
std::cout << "-1" << '\n';
else
std::cout << st.top() << '\n';
}
else if (input == "size")
std::cout << st.size() << '\n';
else if(input == "empty")
{
if (st.empty())
std::cout << '1' << '\n';
else
std::cout << '0' << '\n';
}
else if(input == "pop")
{
if(!st.empty())
{
int a = st.top();
std::cout << a << '\n';
st.pop();
}
else
{
std::cout << "-1" << '\n';
}
}
}
return 0;
}<file_sep>/11399.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int N; // ATM앞에 기다리는 사람들의 명수
vector<int> Person_WaitTime; // 각자의 인출하는데 걸리는 시간
int Result_WaitTime = 0; // 총 기다리는 시간
int _input;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> _input;
Person_WaitTime.push_back(_input);
}
sort(Person_WaitTime.begin(), Person_WaitTime.end());
for (int i = 0; i < N; i++)
{
Result_WaitTime += Person_WaitTime.at(i);
for (int j = 0; j < i; j++)
{
if (j == i)
{
continue;
}
Result_WaitTime += Person_WaitTime.at(j);
}
}
cout << Result_WaitTime;
return 0;
}<file_sep>/Baekjoon-Judge-Project/recursion_PICNIC(6.2).cpp
#include <iostream>
#include <utility>
#include <vector>
#include <tuple>
using namespace std;
vector<pair<int, int> > Friends; // 친구쌍...
vector<pair<int, bool> > Person; // first : 사람번호, second : true면 선택된지 확인...
int main()
{
int C;
int N;
int M;
cin >> C;
for (int testcase = 0; testcase < C; testcase++)
{
if(Friends.size() != 0)
Friends.clear();
if (Person.size() != 0)
Person.clear();
cin >> N;
cin >> M;
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
pair<int, bool> person_temp; // 0부터 N-1 까지 만큼 사람 리스트에 넣음 초기는 선택안됬으니 bool값은 false임.
person_temp.first = j;
person_temp.second = false;
Person.push_back(person_temp);
pair<int, int> person_set; // 친구쌍 입력
cin >> person_set.first;
cin >> person_set.second;
Friends.push_back(person_set);
}
if (Friends.size() == 1 && N == 2) // 학생이 2명이고 친구쌍이 1쌍이면 무조건 경우의 수는 1
{
cout << "1" << endl;
}
else // 완탐ㄱㄱ 19.08.06 ...
{
for (int j = 0; j < N; j++)
{
}
}
}
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2293.cpp
#include <bits/stdc++.h>
#define INF 99999
std::vector<int> coins;
int dp[1000001];
bool ready[1000001];
//int solve(int _in)
//{
// dp[0] = 0;
//
/*
if (_in < 0)
return INF;
if (_in == 0)
return 0;
if (ready[_in])
return dp[_in];
int best = INF;
for(int c : coins)
best = std::min(best, solve(_in - c) + 1);
ready[_in] = true;
dp[_in] = best;
if (best > _in)
return -1;
return best;*/
//}
int main()
{
int n, k;
int count = 0;
int temp = 0;
std::cin >> n >> k;
for (int i = 0; i < n; ++i)
{
std::cin >> temp;
coins.push_back(temp);
}
dp[0] = 0;
for(int i =1; i<=k; ++i)
{
dp[i] = INF;
for(int c : coins)
{
if (i - c >= 0)
{
dp[i] = std::min(dp[i], dp[i - c] + 1);
ready[i] = true;
}
}
}
count = dp[k];
if (k == 0)
std::cout << "0";
else if (ready[k] != true || count == INF) // count == INF를 안하면 왜 오답이 뜨는지 분석하기... 일단 이거 처리하니까 답나옴... // INF면 초기값 즉 경우의 수를 찾지 못했다는의미였당
std::cout << "-1";
else
std::cout << count;
return 0;
}<file_sep>/Baekjoon-Judge-Project/11728.cpp
#include <bits/stdc++.h>
std::vector<int> input;
int main()
{
int N, M,temp;
std::cin >> N >> M;
for (int i = 0; i < N + M; ++i)
{
std::cin >> temp;
input.push_back(temp);
}
std::stable_sort(input.begin(), input.end());
for (auto i : input)
std::cout << i << " ";
return 0;
}<file_sep>/Baekjoon-Judge-Project/1541.cpp
#include <bits/stdc++.h>
int main()
{
std::string temp = "";
std::string input_data;
bool check = false;
int result = 0;
std::cin >> input_data;
for(int i =0; i <=input_data.size(); ++i)
{
if(input_data[i] == '+' || input_data[i] == '-' || input_data[i] =='\0')
{
if(check == true)
{
result -= std::stoi(temp);
temp = "";
//check = false;
}
else
{
result += std::stoi(temp);
temp = "";
//check = false;
}
if(input_data[i] == '-')
{
check = true;
continue;
}
}
temp += input_data[i];
}
std::cout << result;
return 0;
}
// 60+30-60+10+50-60
// 90-(60+10+50)-(60)<file_sep>/Baekjoon-Judge-Project/1018.cpp
#include <bits/stdc++.h>
char matrix[100][100];
char W_matrix[100][100];
char B_matrix[100][100];
int main()
{
int N, M, w_min_value = 0, b_min_value= 0;
std::cin >> N >> M;
for(int i =0; i < N; ++i)
{
for (int j = 0; j < M ; ++ j)
{
std::cin >> matrix[i][j];
}
}
for(int i = 0; i< N ; ++i)
{
for(int j = 0 ; j< M; ++j)
{
if (i % 2 == 0 && j % 2 == 0)
{
B_matrix[i][j] = 'B';
W_matrix[i][j] = 'W';
}
else if (i % 2 == 1 && j % 2 == 1)
{
B_matrix[i][j] = 'B';
W_matrix[i][j] = 'W';
}
else
{
B_matrix[i][j] = 'W';
W_matrix[i][j] = 'B';
}
}
}
for(int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
if (B_matrix[i][j] != matrix[i][j])
b_min_value++;
if (W_matrix[i][j] != matrix[i][j])
w_min_value++;
}
}
if (matrix[0][0] == 'B')
{
if (b_min_value > N * M)
std::cout << N*M-b_min_value;
else
std::cout << b_min_value;
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/1932.cpp
#include <bits/stdc++.h>
long long triangle[1000][1000];
long long dp[1000][1000];
int main()
{
int n;
long long max = -1;
std::cin >> n;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
std::cin >> triangle[i][j];
}
}
dp[2][1] += triangle[1][1] + triangle[2][1];
dp[2][2] += triangle[1][1] + triangle[2][2];
for(int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
if (i == 1 && j == 1)
continue;
if (dp[i + 1][j] < triangle[i + 1][j] + dp[i][j])
dp[i + 1][j] = triangle[i + 1][j] + dp[i][j];
if (dp[i + 1][j + 1] < triangle[i + 1][j + 1] + dp[i][j])
dp[i + 1][j + 1] = triangle[i + 1][j + 1] + dp[i][j];
}
}
for(int i = 1; i <=n; ++i)
{
if (max <= dp[n][i])
max = dp[n][i];
}
if (n == 1)
max = triangle[1][1];
std::cout << max;
return 0;
}<file_sep>/2231.cpp
#include <iostream>
using namespace std;
#define FOR1(i, val, n) for(int i =val; i<n; i++)
#define FOR2(i,val, n) for(int i =val; i<=n; i++)
int main()
{
int N;
int Create_Number_Position[10];
int Create_Number = 1000000;
int Position_Count = 0;
int result;
int answer;
int temp;
cin >> N;
FOR2(i, 1, N)
{
temp = i;
while (temp != 0)
{
Create_Number_Position[Position_Count] = (temp % 10);
temp /= 10;
Position_Count++;
}
result = i;
FOR1(j, 0, Position_Count)
{
result += Create_Number_Position[j];
}
if (N == result)
{
answer = i;
break;
}
else
{
answer = 0;
}
Position_Count = 0;
FOR1(j, 0, 10)
{
Create_Number_Position[j] = 0;
}
}
cout << answer;
return 0;
}<file_sep>/Baekjoon-Judge-Project/1931.cpp
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
int main()
{
vector<pair<int, int>> reserve;
int N;
int First, Second;
int Max = 0;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> First;
cin >> Second;
reserve.push_back(make_pair(First, Second));
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
}
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/15596.cpp
#include <iostream>
#include <vector>
long long sum(std::vector<int> &a)
{
long long _sum = 0;
for(int i : a)
{
_sum += i;
}
return _sum;
}
int main()
{
return 0;
}<file_sep>/Baekjoon-Judge-Project/1330.cpp
#include <iostream>
int main()
{
short int point;
std::cin >> point;
if (point >= 90 && point <= 100)
std::cout << 'A';
else if (point >= 80 && point <= 89)
std::cout << 'B';
else if (point >= 70 && point <= 79)
std::cout << 'C';
else if (point >= 60 && point <= 69)
std::cout << 'D';
else
std::cout << 'F';
return 0;
}<file_sep>/Baekjoon-Judge-Project/2775.cpp
#include <bits/stdc++.h>
int dp[20][20]; // 범위 제한 14,14 이지만 여유 부림... 초기화 귀찬아서 전역으로 뺌 기본값 0 으로 자동초기화...
int main()
{
int T, k, n;
std::cin >> T;
for(int i = 0; i<20; ++i)
{
dp[0][i] = i;
}
for(int i = 1; i < 20; ++i)
{
for(int j =1; j<20; ++j)
{
for(int z =1; z <= j; ++z)
{
dp[i][j] += dp[i-1][z];
}
}
}
for(int i = 0; i < T; i++)
{
std::cin >> k >> n;
std::cout << dp[k][n] << '\n';
}
/*for (int i = 0; i < T; ++i)
{
std::cin >> k >> n;
for(int j = 1; j <= k; ++j)
{
for(int l = 1; l <=n; ++l)
{
for(int z =1; z <= l; ++z)
{
dp[j][l] += dp[j][z];
}
}
}
std::cout << dp[k][n] << '\n';
}*/
return 0;
}<file_sep>/9012.cpp
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main()
{
stack<char> data_stack; // 괄호 정보를 입력
int T; // 입력 case 수
char in_data[50];
bool isVPS = true; // VPS 체크
int point = 0;
int open_cnt = 0; // ( 의 수
int close_cnt = 0; // ) 의 수;
cin >> T;
for (int i = 0; i < T; i++)
{
cin >> in_data;
isVPS = true;
point = 0;
open_cnt = 0;
close_cnt = 0;
while (false == data_stack.empty())
{
data_stack.pop();
}
while (true)
{
if (in_data[point] == '(')
{
data_stack.push(in_data[point]);
open_cnt++;
}
else if (in_data[point] == ')')
{
close_cnt++;
if (data_stack.size() == 0)
{
isVPS = false;
break;
}
if (data_stack.size() != 0)
{
if (data_stack.top() == '(')
{
data_stack.pop();
}
else
{
isVPS = false;
}
}
}
else
break;
point++;
}
if (open_cnt != close_cnt)
{
cout << "NO" << endl;
}
else if (isVPS == true)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/1712.cpp
#include <bits/stdc++.h>
int main()
{
int A, B, C, product;
std::cin >> A >> B >> C;
if(B >= C)
{
product = -1;
}
else
{
product = (A/(C-B))+1;
}
std::cout << product;
return 0;
}<file_sep>/Baekjoon-Judge-Project/2503.cpp
#include <bits/stdc++.h>
int main()
{
int number;
std::vector<std::string> numbers;
std::string temp;
int count = 0;
for(int i =1; i <=9; ++i)
{
for(int j = 1; j<=9; ++j)
{
for(int k= 1; k <= 9; ++k)
{
if (i == j || j == k || k == i)
{
continue;
}
number = (i * 100) + (j * 10) + (k * 1);
temp = std::to_string(number);
numbers.push_back(temp);
}
}
}
for (auto i : numbers)
{
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2675.cpp
#include <iostream>
#include <string>
int main()
{
int T;
int R;
std::string input;
std::cin >> T;
for(int i = 0; i < T; ++i)
{
std::cin >> R;
std::cin >> input;
for(int j =0; j < input.length(); ++j)
{
for (int k = 0; k < R; ++k)
std::cout << input[j];
}
std::cout << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/4344.cpp
#include <iostream>
#include <vector>
int main()
{
int C;
int N;
int temp;
double avg = 0.0;
double persent = 0.0;
double result = 0.0;
std::vector<int> student;
std::cin >> C;
for(int i =0; i< C; ++i)
{
std::cin >> N;
for(int j = 0; j < N; ++j)
{
std::cin >> temp;
student.push_back(temp);
avg += temp;
}
avg = avg / N;
persent = (double)100 / (double)N;
for(int j = 0; j<N ;++j)
{
if (avg < student.at(j))
result += persent;
}
std::cout.precision(3);
std::cout << std::fixed << result <<'%' << '\n';
result = 0.0;
student.clear();
avg = 0.0;
persent = 0.0;
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/11944.cpp
#include <bits/stdc++.h>
int main()
{
std::string collection;
std::string N_string;
int N, M;
std::cin >> N >> M;
N_string = std::to_string(N);
for(int i=0; i < N; ++i)
{
collection += N_string;
if(collection.length() >= M)
{
for (int j = 0; j < M; ++j)
std::cout << collection[j];
break;
}
}
if (collection.length() < M)
{
for (int j = 0; j < collection.length(); ++j)
std::cout << collection[j];
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/10950.cpp
#include <iostream>
int main()
{
short T, A, B;
std::cin >> T;
for(int i = 0; i<T; ++i)
{
std::cin >> A >> B;
std::cout << A + B << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/1924.cpp
#include <bits/stdc++.h>
int main()
{
/*2007.1.1 == MON..
1,3,5,8,10,12 -> ~ 31day
4,6,9,11 -> ~ 30day
2 -> ~ 28day
*/
int x, y;
int sum_day = 0;
std::string days[7] = { "MON","TUE","WED", "THU", "FRI", "SAT", "SUN" };
std::string today;
std::cin >> x >> y;
for(int i =1; i <x; ++i)
{
switch(i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
sum_day += 31;
break;
case 4:
case 6:
case 9:
case 11:
sum_day += 30;
break;
case 2:
sum_day += 28;
break;
}
}
if (x == 1)
{
//sum_day -= 31;
sum_day += y-1;
}
else if (x != 1)
sum_day += y-1;
int count = 0;
today = days[count];
for(int i = 0; i<= sum_day; ++i)
{
if (count == 7)
{
count = 0;
today = days[count];
}
else
{
today = days[count];
}
count++;
}
std::cout << today;
return 0;
}<file_sep>/Baekjoon-Judge-Project/소스.cpp
#include <bits/stdc++.h>
int main()
{
int T;
int bb, pp, ff; // bb : 빵 개수 , pp, 쇠고기 개수 , ff 치킨개수
int hh, cc; // hh : 햄버거 가격, cc : 치킨버거 가격
int result = 0;
std::cin >> T;
for (int i = 0; i < T; ++i)
{
std::cin >> bb >> pp >> ff;
std::cin >> hh >> cc;
result = 0;
if (cc >= hh) // 치킨이 더비살떄
{
while (true)
{
if (ff >= 1 && bb >= 2)
{
result += cc;
ff -= 1;
bb -= 2;
}
else
break;
}
while (true)
{
if (pp >= 1 && bb >= 2)
{
result += hh;
pp -= 1;
bb -= 2;
}
else
break;
}
}
else if (cc < hh) //햄버거가 더비살때
{
while (true)
{
if (pp >= 1 && bb >= 2)
{
result += hh;
pp -= 1;
bb -= 2;
}
else
break;
}
while (true)
{
if (ff >= 1 && bb >= 2)
{
result += cc;
ff -= 1;
bb -= 2;
}
else
break;
}
}
std::cout << result << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2753.cpp
#include <iostream>
int main()
{
short year;
std::cin >> year;
if (year % 4 == 0)
{
if (year >= 100)
{
if (year % 400 == 0)
std::cout << '1';
else if (year % 100 != 0 && year % 4 == 0)
std::cout << '1';
else
std::cout << '0';
}
else
std::cout << '1';
}
else
std::cout << '0';
return 0;
}<file_sep>/Baekjoon-Judge-Project/4673.cpp
#include <iostream>
bool check[10001]; // 1~10000번까지 만약 해당 인덱스가 생성자 (해당수와 자리수를 하나씩 더해서 만들수 있는 수) 가 될수 있는 수면 해당 인덱스 True시킴
int d(int _idx)
{
int sum = _idx;
sum += _idx / 10000;
_idx = _idx % 10000;
sum += _idx / 1000;
_idx = _idx % 1000;
sum += _idx / 100;
_idx = _idx % 100;
sum += _idx / 10;
_idx = _idx % 10;
sum += _idx / 1;
_idx = _idx % 1;
return sum;
}
int main()
{
int idx;
for(int i = 1; i <=10000; i++)
{
idx = d(i);
if(idx > 0)
{
check[idx] = true;
}
}
for(int i =1; i <=10000; i++)
{
if(check[i] == false)
{
std::cout << i << '\n';
}
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/1076.cpp
#include <iostream>
#include <string>
int main()
{
long long sum = 0;
int num = 0;
long long temp = 0;
std::string input[3];
for (int i = 0; i < 3; ++i)
{
std::cin >> input[i];
if (input[i] == "black")
num = 0;
else if (input[i] == "brown")
num = 1;
else if (input[i] == "red")
num = 2;
else if (input[i] == "orange")
num = 3;
else if (input[i] == "yellow")
num = 4;
else if (input[i] == "green")
num = 5;
else if (input[i] == "blue")
num = 6;
else if (input[i] == "violet")
num = 7;
else if (input[i] == "grey")
num = 8;
else if (input[i] == "white")
num = 9;
if (i == 0)
sum = num * 10;
else if (i == 1)
sum += num;
else if(i == 2)
{
temp = 1;
for(int j = 0; j < num; ++j)
temp *= 10;
sum *= temp;
}
}
std::cout << sum;
return 0;
}<file_sep>/11066.cpp
#include <iostream>
using namespace std;
int dp[501][501];
int input[501];
int main()
{
int T;
int K;
cin >> T;
cin >> K;
for (int testcase = 0; testcase < T; testcase++)
{
for (int i = 1; i <= K; i++)
{
cin >> input[i];
}
for (int i = 1; i <= K; i++)
{
for (int j = 1; j <= K; j++)
{
if (j > K) {
break;
}
if (i == j)
{
dp[i][j] = 0;
continue;
}
dp[i][j] = input[i] + input[j];
}
}
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2562.cpp
#include <iostream>
int main()
{
short arr[10];
short max = 0;
short max_arr = 0;
for(int i = 1; i <= 9; ++i)
{
std::cin >> arr[i];
if(arr[i] >= max)
{
max = arr[i];
max_arr = i;
}
}
std::cout << max << '\n' << max_arr;
return 0;
}<file_sep>/Baekjoon-Judge-Project/11365.cpp
#include <iostream>
#include <stack>
#include <string>
int main()
{
std::stack<char> decoder;
std::string password;
while (true)
{
std::getline(std::cin, password);
if (password == "END")
break;
for (char i : password)
{
decoder.push(i);
}
for (char i : password)
{
std::cout << decoder.top();
decoder.pop();
}
std::cout << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2579.cpp
#include <bits/stdc++.h>
int dp[1000];
int floors[1000];
int main()
{
int num;
int sum = 0;
std::cin >> num;
for(int i = 1; i<=num; ++i)
std::cin >> floors[i];
dp[1] = floors[1];
if (num == 1)
std::cout << dp[1];
if (num >= 2)
{
dp[2] = dp[1] + floors[2];
if(num == 2)
std::cout << dp[2];
}
for(int i=3; i<=num; ++i)
dp[i] = std::max(dp[i - 2] + floors[i], dp[i - 3] + floors[i - 1] + floors[i]);
std::cout << dp[num];
return 0;
}<file_sep>/Baekjoon-Judge-Project/11053.cpp
#include <bits/stdc++.h>
int dp[1010][1010];
int main()
{
int A_length;
std::cin >> A_length;
for(int i = 1; i <= A_length; ++i)
{
std::cin >> dp[0][i];
dp[i][0]= dp[0][i];
}
//getchar();
return 0;
}<file_sep>/Baekjoon-Judge-Project/15649.cpp
#include <iostream>
#include <vector>
bool visit[9]; // 1~8까지의 수니까
std::vector<int> data;
void dfs(int _n, int _m)
{
if(data.size() == _m)
{
for(int i=0;i <_m; ++i)
{
std::cout << data.at(i) << " ";
}
std::cout << '\n';
}
for(int i =1; i<=_n; ++i)
{
if(visit[i] == false)
{
visit[i] = true;
data.push_back(i);
dfs(_n, _m);
data.pop_back();
visit[i] = false;
}
}
}
int main()
{
int n, m;
std::cin >> n >> m;
dfs(n, m);
return 0;
}<file_sep>/Baekjoon-Judge-Project/1149.cpp
#include <bits/stdc++.h>
int dp[1000][5];
int main()
{
int N;
int red = 0, blue = 0, green = 0;
int result = 0;
std::cin >> N;
for (int i = 1; i <= N; ++i)
dp[0][i] = 0;
for (int i = 1; i <= N; ++i)
{
std::cin >> dp[i][1];
std::cin >> dp[i][2];
std::cin >> dp[i][3]; // 1 : »¡° 2 :ÆÄ¶û 3 : ÃÊ·Ï
}
for (int i = 1; i <= N; ++i)
{
for (int j = 1; j <= 3; ++j)
{
if (j == 1)
{
dp[i][1] = std::min(dp[i - 1][2], dp[i - 1][3]) + dp[i][1];
}
else if (j == 2)
{
dp[i][2] = std::min(dp[i - 1][1], dp[i - 1][3]) + dp[i][2];
}
else
{
dp[i][3] = std::min(dp[i - 1][2], dp[i - 1][1]) + dp[i][3];
}
}
}
std::cout << std::min(dp[N][1], std::min(dp[N][2], dp[N][3]));
return 0;
}<file_sep>/2263.cpp
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main()
{
map<int, int> m_tree;
vector<int> input_data;
int in_buffer;
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> in_buffer;
input_data.push_back(in_buffer);
}
return 0;
}<file_sep>/1021.cpp
#include <iostream>
#include <deque>
#include <queue>
using namespace std;
int main()
{
deque<int> input_data;
queue<int> pick_data;
int N;
int M;
int pick;
int cnt = 0;
int position = 0;
cin >> N;
cin >> M;
for (int i = 0; i < M; i++)
{
cin >> pick;
pick_data.push(pick);
}
for (int i = 1; i <= N; i++)
input_data.push_back(i);
while (true)
{
position = 0;
if (pick_data.size() == 0)
{
cout << cnt << endl;
break;
}
while (true)
{
if (input_data.at(position) == pick_data.front())
{
break;
}
else
{
position++;
}
}
if (position > (input_data.size() / 2))
{
while (true)
{
if (input_data.front() == pick_data.front())
{
input_data.pop_front();
pick_data.pop();
break;
}
else
{
input_data.push_front(input_data.back());
input_data.pop_back();
cnt++;
}
}
}
else
{
while (true)
{
if (input_data.front() == pick_data.front())
{
input_data.pop_front();
pick_data.pop();
break;
}
else
{
input_data.push_back(input_data.front());
input_data.pop_front();
cnt++;
}
}
}
}
return 0;
}<file_sep>/1100.cpp
#include <iostream>
using namespace std;
#define FOR(i,n) for(int i = 0; i<(n);i++)
int main()
{
char CHESS_BOARD[8][8];
int count = 0;
FOR(i,8)
{
FOR(j,8)
{
cin >> CHESS_BOARD[i][j];
if (((i % 2 == 0) && (j % 2 == 0)) || ((i%2 ==1) &&(j %2 ==1)) )
{
if (CHESS_BOARD[i][j] == 'F')
{
count++;
}
}
}
}
cout << count;
return 0;
}<file_sep>/Baekjoon-Judge-Project/15552.cpp
#include <iostream>
int main()
{
std::cin.tie(NULL);
std::ios_base::sync_with_stdio(false);
long T, A,B;
std::cin >> T;
for(int i =0; i<T; ++i)
{
std::cin >> A >> B;
std::cout << A + B << '\n';
}
return 0;
}<file_sep>/1541.cpp
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> Num_vec;
int _Number;
char _Oper;
while (true)
{
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/15483.cpp
#include <bits/stdc++.h>
int dp[1010][1010];
int main()
{
std::string input_A;
std::string input_B;
int min;
std::cin >> input_A >> input_B;
for(int i =0; i <= input_A.length(); ++i)
dp[i][0] = i;
for (int i = 0; i <= input_B.length(); ++i)
dp[0][i] = i;
min = std::min(input_A.length(), input_B.length());
for(int i = 1; i<= input_A.length(); ++i)
{
for(int j = 1; j<= input_B.length() ; ++j)
{
if (input_A[i - 1] == input_B[j - 1])
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = std::min(dp[i-1][j-1],std::min(dp[i][j-1],dp[i-1][j]))+1;
}
}
std::cout << dp[input_A.length()][input_B.length()];
return 0;
}<file_sep>/Baekjoon-Judge-Project/1011.cpp
#include <iostream>
using namespace std;
int main()
{
int T;
int X;
int Y;
int isUsedCNT = 0;
int SelectPoint[3] = { -1, 0, 1 };
int Position;
cin >> T;
for (int testcase = 1; testcase <= T; testcase++)
{
isUsedCNT = 0;
cin >> X;
cin >> Y;
Position = X;
while (true)
{
if (Position == Y)
break;
if (isUsedCNT == 0)
{
Position += SelectPoint[2];
SelectPoint[0] = Position - 1;
SelectPoint[1] = Position;
SelectPoint[2] = Position + 1;
isUsedCNT++;
}
}
cout << isUsedCNT<< endl;
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/9251.cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int dp[3000][3000]; // LCS (Longest Common Substring != Longest Common Subsequence) 여기서는 후자의 문제이다.
int main()
{
string input_string1;
string input_string2;
int max_lcs = 0;
cin >> input_string1;
cin >> input_string2;
for (int i = 0; i < input_string1.size(); i++)
{
dp[i][0] = 0;
}
for (int i = 0; i < input_string2.size(); i++)
{
dp[0][i] = 0;
}
for (int i = 0; i < input_string1.size(); i++)
{
for (int j = 0; j < input_string2.size(); j++)
{
dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1]);
if (input_string1[i] == input_string2[j])
{
dp[i+1][j+1] = dp[i][j]+1;
}
if (max_lcs <= dp[i+1][j+1])
{
max_lcs = dp[i+1][j+1];
}
}
}
cout << max_lcs << endl;
return 0;
}<file_sep>/Baekjoon-Judge-Project/2884.cpp
#include <iostream>
int main()
{
short hour, minute, temp;
std::cin >> hour >> minute;
minute -= 45;
if (minute < 0)
{
hour--;
if(hour < 0)
{
hour = 23;
}
temp = minute;
minute = 60;
minute += temp;
}
std::cout << hour << " " << minute;
return 0;
}<file_sep>/11047.cpp
#include <iostream>
using namespace std;
#define FOR(i,n,m) for(int i = m; i <= n; i++)
#define FOR_Minus(i,n,m) for(int i = m; i>n; i--)
int main()
{
int Coin_kind[15]; // 동전 종류 저장배열
int N; // 동전의 종류의 수
int K; // 입력된 금액
int RESULT_COIN = 0;
cin >> N;
cin >> K;
FOR(i, N, 1)
{
cin >> Coin_kind[i];
}
FOR_Minus(i, 0, N)
{
if (K >= Coin_kind[i])
{
RESULT_COIN += (K / Coin_kind[i]);
K %= Coin_kind[i];
}
}
cout << RESULT_COIN;
return 0;
}<file_sep>/Baekjoon-Judge-Project/recursion_bubble(6.2).cpp
#include <array>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int x, y;
array<char, 1000> matrix[1000];
/*
x
0:[-1, 1] 1:[-1, 0] 2:[-1, 1]
3:[0, -1] [point] 4:[0, 1]
5:[1, -1] 6:[1, 0] 7:[1, 1]
y
*/
array<int, 8> tX = { -1,-1,-1,0,0,1,1,1 };
array<int, 8> tY = { 1,0,1,-1,1,-1,0,1 };
vector<char> temp;
bool search(int _x, int _y, string _input)
{
if ((_x >= x) || (_y >= y) || (_y < 0) || (_x < 0)) // 입력된 좌표가 범위를 벗어나면 무조건 false (이는 재귀호출을 위함임)
{
return false;
}
if (matrix[_x][_y] != _input[0]) // 첫 문자가 아니면 무조건 아니니 false
{
return false;
}
if (_input.length() == 1) // 위에서 첫문자가 아닌지 확인했고 입력 문자의 길이가 1이면 하나만 맞으면 무조건 true임
{
return true;
}
for (int i = 0; i < 8; i++)
{
int nextX = _x + tX[i];
int nextY = _y + tY[i];
if (search(nextX, nextY, _input.substr(1)))// 재귀 함수 호출부분 _input.substr(1)의 의미는 호출될떄마다 앞자리가 사라지고 그 값을 다시 재귀함수 인자에 넣는다는 의미다.
{
temp.push_back(matrix[nextX][nextY]);
return true;
}
}
return false; // 위에서 걸러지지 않으면 matrix에 원하는 문자들이 없는 것이다.
if(1){cout << endl; }
}
int main()
{
string input;
vector<char> answer;
cin >> x;
cin >> y;
bool check = false;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cin >> matrix[i][j];
}
}
cin >> input;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (search(i, j, input))
{
check = true;
break;
}
}
if (check == true)
{
break;
}
}
if (check == true)
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
return 0;
}<file_sep>/1436.cpp
#include <iostream>
#include <string>
using namespace std;
#define FOR(i, n) for(int i = 0; i <= n; i++)
int main()
{
int N;
int CNT = 0;
string int_to_string;
int answer = 0;
int i = 666;
int N_count = 0;
cin >> N;
while(true)
{
int_to_string = to_string(i);
CNT = 0;
N_count = 0;
FOR(j, int_to_string.size() - 1)
{
if (j + 1 < int_to_string.size() && int_to_string[j] == '6')
{
if (int_to_string[j] == int_to_string[j + 1])
{
CNT++;
}
else
{
CNT = 0;
}
if (CNT == 3)
{
CNT = 0;
N_count++;
break;
}
}
}
if (N_count == N)
{
i--;
answer = i;
break;
}
i++;
}
cout << answer;
return 0;
}<file_sep>/Baekjoon-Judge-Project/1003.cpp
#include <bits/stdc++.h>
int dp[1001];
bool check[1001];
int zero_cnt[1001];
int one_cnt[1001];
int main()
{
int T, N;
dp[0] = 0;
dp[1] = 1;
check[0] = true;
check[1] = true;
zero_cnt[0] = 1, zero_cnt[1] = 0;
one_cnt[1] = 1, one_cnt[0] = 0;
for(int i = 2; i <=40 ; ++i)
{
dp[i] = dp[i - 1] + dp[i-2];
check[i] = true;
zero_cnt[i] = zero_cnt[i - 1] + zero_cnt[i - 2];
one_cnt[i] = one_cnt[i - 1] + one_cnt[i - 2];
}
std::cin >> T;
for (int t = 1; t <=T ; ++t)
{
std::cin >> N;
std::cout << zero_cnt[N] << " " << one_cnt[N] << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/1157.cpp
#include <iostream>
int main()
{
char input[1000000] = { NULL };
int alphabet[26] = {0};
int i = 0;
int max = -1;
bool isTop = true;
std::cin >> input;
int check = 0;
while(true)
{
if (input[i] == NULL)
break;
switch(input[i])
{
case 65:
case 97:
alphabet[0]++;
break;
case 66:
case 98:
alphabet[1]++;
break;
case 67:
case 99:
alphabet[2]++;
break;
case 68:
case 100:
alphabet[3]++;
break;
case 69:
case 101:
alphabet[4]++;
break;
case 70:
case 102:
alphabet[5]++;
break;
case 71:
case 103:
alphabet[6]++;
break;
case 72:
case 104:
alphabet[7]++;
break;
case 73:
case 105:
alphabet[8]++;
break;
case 74:
case 106:
alphabet[9]++;
break;
case 75:
case 107:
alphabet[10]++;
break;
case 76:
case 108:
alphabet[11]++;
break;
case 77:
case 109:
alphabet[12]++;
break;
case 78:
case 110:
alphabet[13]++;
break;
case 79:
case 111:
alphabet[14]++;
break;
case 80:
case 112:
alphabet[15]++;
break;
case 81:
case 113:
alphabet[16]++;
break;
case 82:
case 114:
alphabet[17]++;
break;
case 83:
case 115:
alphabet[18]++;
break;
case 84:
case 116:
alphabet[19]++;
break;
case 85:
case 117:
alphabet[20]++;
break;
case 86:
case 118:
alphabet[21]++;
break;
case 87:
case 119:
alphabet[22]++;
break;
case 88:
case 120:
alphabet[23]++;
break;
case 89:
case 121:
alphabet[24]++;
break;
case 90:
case 122:
alphabet[25]++;
break;
}
i++;
}
for(int i =0 ; i<26; ++i)
{
if(alphabet[i] >= max)
{
max = alphabet[i];
check = i;
}
}
int count = 0;
for(int i = 0; i<26; ++i)
{
if (alphabet[i] == max)
count++;
}
if (count >= 2)
std::cout << '?';
else
{
switch(check)
{
case 0:
std::cout << 'A';
break;
case 1:
std::cout << 'B';
break;
case 2:
std::cout << 'C';
break;
case 3:
std::cout << 'D';
break;
case 4:
std::cout << 'E';
break;
case 5:
std::cout << 'F';
break;
case 6:
std::cout << 'G';
break;
case 7:
std::cout << 'H';
break;
case 8:
std::cout << 'I';
break;
case 9:
std::cout << 'J';
break;
case 10:
std::cout << 'K';
break;
case 11:
std::cout << 'L';
break;
case 12:
std::cout << 'M';
break;
case 13:
std::cout << 'N';
break;
case 14:
std::cout << 'O';
break;
case 15:
std::cout << 'P';
break;
case 16:
std::cout << 'Q';
break;
case 17:
std::cout << 'R';
break;
case 18:
std::cout << 'S';
break;
case 19:
std::cout << 'T';
break;
case 20:
std::cout << 'U';
break;
case 21:
std::cout << 'V';
break;
case 22:
std::cout << 'W';
break;
case 23:
std::cout << 'X';
break;
case 24:
std::cout << 'Y';
break;
case 25:
std::cout << 'Z';
break;
}
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2920.cpp
#include <iostream>
int main()
{
short arr[8];
bool check[3] = { false, false, false };
for (int i = 0; i < 8; ++i)
{
std::cin >> arr[i];
if(i >0 && i<9)
{
if ((arr[i]) - (arr[i - 1]) == 1)
check[0] = true;
else if ((arr[i-1]) - (arr[i]) == 1)
check[1] = true;
else
check[2] = true;
}
}
if (check[0] == true && check[2] == false)
std::cout << "ascending";
else if (check[1] == true && check[2] == false)
std::cout << "descending";
else if(check[2] == true)
std::cout << "mixed";
return 0;
}<file_sep>/Baekjoon-Judge-Project/10952.cpp
#include <iostream>
int main()
{
std::cin.tie(NULL);
std::ios_base::sync_with_stdio(false);
short A, B;
while (true)
{
std::cin >> A >> B;
if (A == 0 && B == 0)
break;
std::cout << A + B << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/2908.cpp
#include <iostream>
#include <string>
#include <stack>
int main()
{
std::string A, B;
std::stack<char> reverse;
int A_integer, B_integer;
std::cin >> A >> B;
for(int i=0; i<A.length(); i++)
{
reverse.push(A[i]);
}
for(int i=0; i<A.length();i++)
{
A[i] = reverse.top();
reverse.pop();
}
for(int i=0; i<B.length(); i++)
{
reverse.push(B[i]);
}
for(int i =0; i<B.length(); i++)
{
B[i] = reverse.top();
reverse.pop();
}
A_integer = std::stoi(A);
B_integer = std::stoi(B);
if (A_integer > B_integer)
{
std::cout << A_integer << '\n';
}
else
{
std::cout << B_integer << '\n';
}
return 0;
}<file_sep>/CodingSpace.cpp
#include <iostream>
#include <list>
class Node
{
Node* Next;
};
using namespace std;
int main()
{
cout << "Hello World!\n";
return 0;
}<file_sep>/Baekjoon-Judge-Project/1629.cpp
#include <bits/stdc++.h>
int main()
{
long long A, B, C;
long long result = 0;
std::cin >> A >> B >> C;
result = 1;
while(true)
{
if (B == 0)
break;
if (B % 2 == 1)
{
result *= A;
result %= C;
}
A = ((A%C) * (A%C))%C;
B /= 2;
}
std::cout << result << '\n';
return 0;
}<file_sep>/1158.cpp
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int main()
{
int N;
int K;
int v_check_point = 0;
int check_point = 0;
vector<int> input_arr;
vector<int> answer_arr;
stack<int> st;
cin >> N;
cin >> K;
cout << st.size();
st.push(3);
for (int i = 1; i <= N; i++)
input_arr.push_back(i);
while (true)
{
if (input_arr.size() == 0)
break;
else
{
v_check_point = (check_point + K - 1) % input_arr.size();
answer_arr.push_back(input_arr.at(v_check_point));
input_arr.erase(input_arr.begin() + v_check_point);
check_point = v_check_point;
}
}
cout << "<";
for (int i = 0; i < answer_arr.size()-1; i++)
{
cout << answer_arr.at(i) << ", ";
}
cout << answer_arr.back();
cout << ">";
return 0;
}
<file_sep>/Baekjoon-Judge-Project/1065.cpp
#include <iostream>
#include <vector>
int main()
{
int N;
int temp;
int count = 0;
int diff = 0;
bool check = false;
std::vector<int> number_div;
std::cin >> N;
for(int i =1 ; i <= N; i++)
{
diff = 0;
check = false;
number_div.clear();
temp = i;
while(true)
{
if (temp == 0)
break;
number_div.push_back(temp % 10);
temp = temp / 10;
}
if (number_div.size() == 1)
count++;
else
{
diff = number_div[1] - number_div[0];
for (int j = 0; j < number_div.size(); ++j)
{
if (j != number_div.size() - 1)
{
if (diff == (number_div[j + 1] - number_div[j]))
check = true;
else
check = false;
}
}
if(check == true)
count ++;
}
}
std::cout << count << '\n';
return 0;
}<file_sep>/Baekjoon-Judge-Project/2798.cpp
#include <bits/stdc++.h>
int CARD[100];
int main()
{
int N, M;
int max = -1;
int sum = 0;
std::cin >> N >> M;
for(int i =0 ; i< N; ++i)
std::cin >> CARD[i];
for(int i = 0; i< N; ++i)
{
for(int j = 0; j < N; ++j)
{
for(int k = 0; k < N; ++k)
{
if (i == j || i == k || j == k)
continue;
else
{
sum = CARD[i] + CARD[j] + CARD[k];
if(sum <= M)
{
max = std::max(sum, max);
}
}
}
}
}
std::cout << max;
return 0;
}<file_sep>/Baekjoon-Judge-Project/5598.cpp
#include <bits/stdc++.h>
int main()
{
std::string input;
std::cin >> input;
for(int i = 0; i <input.length(); ++i)
{
if(input[i] >= 64 && input[i] <=90)
{
input[i] -= 3;
if (input[i] == 64)
input[i] = 90;
else if(input[i] == 63)
input[i] = 89;
else if(input[i] == 62)
input[i] = 88;
}
}
std::cout << input;
return 0;
}<file_sep>/Baekjoon-Judge-Project/2010.cpp
#include <bits/stdc++.h>
int main()
{
int N , temp, result = 0;
std::cin >> N;
for(int i =0 ; i< N; ++i)
{
std::cin >> temp;
result += temp;
}
std::cout << result - (N - 1);
return 0;
}<file_sep>/Baekjoon-Judge-Project/1546.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
int main()
{
std::vector<double> arr;
std::vector<double> res;
double temp = 0.0;
double max = 0.0;
double max_f = 0.0;
short N;;
double avg = 0.0;
std::cin >> N;
for(int i = 0; i < N; ++i)
{
scanf("%lf", &temp);
arr.push_back(temp);
}
max = *std::max_element(arr.begin(), arr.end());
max_f = max;
res.push_back(max_f);
for(int i= 0; i < N; ++i)
{
temp = arr.at(i) / max * 100;
res.push_back(temp);
avg += temp;
}
double N_f = 0.0;
N_f = N;
//std::cout << avg / N_f << '/n';
printf("%.2lf", avg/N_f);
return 0;
}<file_sep>/Baekjoon-Judge-Project/1110.cpp
#include <iostream>
int main()
{
std::cin.tie(NULL);
std::ios_base::sync_with_stdio(false);
short N, a, b, c, count = 0;
short answer = 0, d, e =0,f =0;
std::cin >> N;
c = N;
if (c < 10)
{
a = 0;
b = c;
}
else
{
a = N / 10;
b = N % 10;
}
while (true)
{
if (N == 0)
{
count = 1;
break;
}
if (N == f)
break;
if (count > 0)
{
if(f < 10)
{
a = 0;
b = f;
}
else
{
a = f / 10;
b = f % 10;
}
}
count++;
c = a + b;
d = c % 10;
answer = b + d;
f = b * 10;
f += d;
}
std::cout << count;
return 0;
}<file_sep>/Baekjoon-Judge-Project/10989.cpp
#include <bits/stdc++.h>
short collection[10001];
int main()
{
std::ios_base::sync_with_stdio(false);
int N, input;
int max = -1;
std::cin >> N;
for(int i = 0 ; i < N; ++i)
{
std::cin >> input;
collection[input]++;
if (input >= max)
max = input;
}
for (int i = 0; i < max; ++i)
{
if (collection[i] == 0)
continue;
for (int j = 0; j < collection[i]; ++j)
std::cout << i << '\n';
}
return 0;
}<file_sep>/Baekjoon-Judge-Project/11943.cpp
#include <bits/stdc++.h>
int main()
{
int buckets[2][2];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
std::cin >> buckets[i][j];
std::cout << std::min(buckets[0][0] + buckets[1][1], buckets[0][1] + buckets[1][0]);
return 0;
}<file_sep>/2309.cpp
#include <bits/stdc++.h>
int main()
{
int dwarf[10];
std::vector<int> answer;
int sum = 0;
for (int i = 1; i <= 9; ++i)
std::cin >> dwarf[i];
for (int a =1; a <= 9; ++a)
{
for (int b = 1; b <= 9; ++b)
{
if (a == b)
continue;
for (int c = 1; c <= 9; ++c)
{
if (b == c || a == c || a == b)
continue;
for (int d = 1; d <= 9; ++d)
{
if (a == b || a == c || a == d || b == c || b == d || c == d )
continue;
for (int e = 1; e <= 9; ++e)
{
if (a == b || a == c || a == d || a == e|| b == c || b == d || b == e || c == d || c == e || d == e)
continue;
for (int f = 1; f <= 9; ++f)
{
if (a == b || a == c || a == d || a == e || a==f || b == c || b == d || b == e || b == f || c == d || c == e || c ==f || d == e || d==f ||e == f)
continue;
for (int g = 1; g <= 9; ++g)
{
if(a == b || a == c || a == d || a == e || a == f || a == g || b == c || b == d || b == e || b == f || b == g || c == d || c == e || c == f || c == g || d == e || d == f || d == g || e == f || e == g || f == g)
continue;
sum = dwarf[a] + dwarf[b] + dwarf[c] + dwarf[d] + dwarf[e] + dwarf[f] + dwarf[g];
if (sum == 100)
{
answer.push_back(dwarf[a]);
answer.push_back(dwarf[b]);
answer.push_back(dwarf[c]);
answer.push_back(dwarf[d]);
answer.push_back(dwarf[e]);
answer.push_back(dwarf[f]);
answer.push_back(dwarf[g]);
goto END;
}
}
}
}
}
}
}
}
END:
std::sort(answer.begin(), answer.end());
for (auto i : answer)
std::cout << i << '\n';
return 0;
}<file_sep>/Baekjoon-Judge-Project/2588.cpp
#include <iostream>
int main()
{
int A, B;
int Divide_B[3];
int Middle[3];
int Result = 0;
std::cin >> A >> B;
Divide_B[0] = B / 100;
B = B % 100;
Divide_B[1] = B / 10;
B = B % 10;
Divide_B[2] = B / 1;
for(int i = 0 ; i <3; ++i)
Middle[i] = A * Divide_B[i];
for(int i = 2; i >= 0 ; --i)
std::cout << Middle[i] << '\n';
Middle[1] *= 10;
Middle[0] *= 100;
for (int i = 2; i >= 0; --i)
Result += Middle[i];
std::cout << Result << '\n';
return 0;
}<file_sep>/Baekjoon-Judge-Project/10773.cpp
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<unsigned long long> input_stack;
int K;
unsigned long long input_data;
unsigned long long SUM_RESULT = 0;
cin >> K;
for (int i = 0; i < K; i++)
{
cin >> input_data;
if (input_data == 0)
{
if (input_stack.size() != 0)
{
input_stack.pop();
}
}
else
{
input_stack.push(input_data);
}
}
while (true)
{
if (input_stack.size() == 0)
break;
SUM_RESULT += input_stack.top();
if(input_stack.size() != 0)
input_stack.pop();
}
cout << SUM_RESULT << endl;
return 0;
} | a9931d6ad4d99ed9458b11ee4ce95f6a5de5d4aa | [
"C++"
] | 71 | C++ | StevenKim1994/Baekjoon-Judge | 7ed646455a85987199776533fa411c3ea2f2f69a | 919498c9e1fd0b617078a7cfcada2ec4a54f0b93 |
refs/heads/main | <file_sep>#!/bin/bash
#this blasts againts the Q9S.fasta sequence
./blastp -db nr -query Q9S.fasta -out results_01.out -outfmt '6 sseqid sseq' -remote
# this is a python script that trims the output from above and makes it into a fasta file format that the makeblastdb can work with.
python Output2DatabaseV-03.py -i results_01.fsa -o outV-04.fsa
#this makes a database using the outV-04.fsa as an input sequence
makeblastdb -in outV-04.fsa -blastdb_version 5 -title "Cookbook demo" -dbtype prot
echo "There are the following number of lines in the output blast search results file"
echo wc -l $results_01.out
echo "There are the following no. lines in the output cleaned fasta format file"
echo wc -l $outV-04.fsa
<file_sep>#!/usr/bin/python
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print('Output2DatabaseV-03.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('Output2DatabaseV-03.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print('Input file is "', inputfile)
print('Output file is "', outputfile)
a_file = open(inputfile, "r")
lines = a_file.readlines()
a_file.close()
outputfile = open(outputfile, "w")
barcount = 0
for line in lines:
count = 0
#barcount = 0
for character in line:
print(barcount)
if count == 0:
lineTotal = character
count = count + 1
if count != 0:
lineTotal = lineTotal + character
count = count + 1
if character == "|":
barcount = barcount + 1
elif barcount == 2:
lineTotal = lineTotal + "\n"
barcount = 0
nextline = "> " + lineTotal
outputfile.write(nextline)
outputfile.close()
if __name__ == "__main__":
main(sys.argv[1:])
<file_sep># Bioinformatics-tools
This is a library to help in the development of bioinformatics libraries.
Official documentation on NCBI BLAST database creation can be found here:
https://www.ncbi.nlm.nih.gov/books/NBK279688/
And the blast github page can be found here, with step by step instructions on how to make a database (db):
https://ncbi.github.io/magicblast/cook/blastdb.html
To run this python script:
1. open a terminal
2. copy an input file and the python code into your CWD.
3. type the following into your terminal:
python Output2DatabaseV-01.py -i <input_file> -o <output_file>
This will create a new file named what you refer to as the output file.
If you name the output file the same thing as another file that already exsists in your CWD,
then the program will write over that file. Please be careful to not write over other
data that you need when running this script.
______________________
If you copy into the ~/ncbi-blast-2.11.0+/bin folder two files:
1. Get_Output2.sh
2. Q9S.fasta (Your query, this was mine for the example)
Then you need to give you .sh script executable permissions.
Make sure you are in root and type:
$chmod 755 Get_Output2.sh
or
$chmod +x Get_Output2.sh
then
$./Get_Output2.sh
And this will make a local blast database on your machine.
| 7261fc504863e1b4091afbc66268383498b0e1b0 | [
"Markdown",
"Python",
"Shell"
] | 3 | Shell | therealjacobbrauer/Bioinformatics-tools | ba31d7acb3c39dd4384ba065ed1c8c65ef60f628 | fb2ad62b76f60ecc0a8ad5c57672f0c1b5090900 |
refs/heads/master | <file_sep><?php
// Add custom menu controller to ContentController
ContentController::add_extension('CustomMenu');
SiteTree::add_extension('CustomMenuExtension');
LeftAndMain::add_extension('CustomMenu_LeftAndMain');
// Enable Subsite Support if needed
if(class_exists('Subsite')) {
CustomMenuHolder::add_extension('CustomMenuHolder_SubsiteExtension');
CustomMenuAdmin::add_extension('SubsiteMenuExtension');
}
| a098a826a2cbbacc69d8f561eef3078dc2ef1ff0 | [
"PHP"
] | 1 | PHP | tardinha/silverstripe-custommenus | 46f4736c957cb983f39efb43a0fb7ee4e5d7c243 | 4361e171c089497614b52644eb57be73ed5cc70c |
refs/heads/master | <repo_name>rodrigof23/pucmg-tccpos<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/util/AWSUtil.java
package com.controlevendas.controlevendas.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.controlevendas.controlevendas.model.Pedido;
import com.controlevendas.controlevendas.model.PedidoMenssagemAWS;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@Component
public final class AWSUtil {
private static final Logger log = LogManager.getLogger(AWSUtil.class);
private static String accessKey;
private static String secretKey;
private AWSUtil() { }
@Value("${cloud.aws.credentials.accessKey}")
public void initializeAccessKey(String accessKey) {
AWSUtil.setAccessKey(accessKey);
}
private static void setAccessKey(String accessKey) {
AWSUtil.accessKey = accessKey;
}
@Value("${cloud.aws.credentials.secretKey}")
public void initializeSecretKey(String secretKey) {
AWSUtil.setSecretKey(secretKey);
}
private static void setSecretKey(String secretKey) {
AWSUtil.secretKey = secretKey;
}
/**
* Metodo que faz a autenticacao da AWS
*
* @return Inteface para acessar o SNS da AWS
*
* @author <NAME>
*/
private static AmazonSNS retornaSNSClienteAWS(){
BasicAWSCredentials awsCreds = new BasicAWSCredentials(AWSUtil.accessKey, AWSUtil.secretKey);
return AmazonSNSClientBuilder.standard().withRegion(Regions.US_EAST_2)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}
/**
* Metodo que envia a notificacao da AWS
*
* @param topico Nome do topico da notificacao
* @param message Mensagem que sera enviada
* @throws JsonProcessingException
*
* @author <NAME>
*/
public static void enviaNotificacaoAWS(String topico, Pedido pedido) throws JsonProcessingException {
String menssagem = AWSUtil.criaMensagemNotificacaoAWS(pedido);
AWSUtil.retornaSNSClienteAWS().publish(topico, menssagem);
log.info("Notificação de pedido enviada com sucesso.");
}
/**
* Metodo responsavel por montar a mensagem que sera enviada para AWS
*
* @param pedido Objeto pedido
* @return String com a menssagem que sera enviada
* @throws JsonProcessingException
*
* @author <NAME>
*/
private static String criaMensagemNotificacaoAWS(Pedido pedido) throws JsonProcessingException {
PedidoMenssagemAWS pedidoMenssagem = new PedidoMenssagemAWS();
pedidoMenssagem.setIdPedido(pedido.getIdPedido());
pedidoMenssagem.setQuantidade(pedido.getNrQuantidade());
pedidoMenssagem.setNome(pedido.getFkCartao().getNmTitularNome());
pedidoMenssagem.setCpf(pedido.getFkCartao().getNrTitularCpf());
pedidoMenssagem.setEndereco(pedido.getFkEndereco());
pedidoMenssagem.setProduto(pedido.getFkProduto());
List<PedidoMenssagemAWS> pedidos = new ArrayList<>();
pedidos.add(pedidoMenssagem);
ObjectMapper mapper = new ObjectMapper();
ArrayNode array = mapper.valueToTree(pedidos);
JsonNode node = mapper.createObjectNode().set("pedidos", array);
return mapper.writeValueAsString(node);
}
}
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/util/DeserializadorUtil.java
package com.controlevendas.controlevendas.util;
import com.controlevendas.controlevendas.model.Produto;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.List;
public class DeserializadorUtil {
private ObjectMapper mapper;
public DeserializadorUtil() {
this.mapper = new ObjectMapper();
this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* Metodo responsavel por realizar a deserializacao dos produtos recebidos na mensagem
*
* @param menssagem Mensagem a ser deserializada
* @return Lista dos produto recebidos
* @throws IOException
*
* @author <NAME>
*/
public List<Produto> deserializarProdutos(String menssagem) throws IOException {
ObjectNode node = this.mapper.readValue(menssagem, ObjectNode.class);
ObjectReader reader = this.mapper.readerFor(new TypeReference<List<Produto>>() {});
return reader.readValue(node.get("produtos"));
}
}
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/dao/CartaoDao.java
package com.controlevendas.controlevendas.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.controlevendas.controlevendas.model.Cartao;
@Repository
public interface CartaoDao extends CrudRepository<Cartao, Long> {
}
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/dao/UsuarioDao.java
package com.controlevendas.controlevendas.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.controlevendas.controlevendas.model.Usuario;
@Repository
public interface UsuarioDao extends CrudRepository<Usuario, Long> {
Usuario findByNmEmailAndNmSenha(String nmEmail, String nmSenha);
}
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/dao/PedidoDao.java
package com.controlevendas.controlevendas.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.controlevendas.controlevendas.model.Pedido;
@Repository
public interface PedidoDao extends CrudRepository<Pedido, Long> {
}
<file_sep>/README.md
# pucmg-tccpos
Repositório para postagem da POC desenvolvida no TCC da pós graduação em Arquitetura de Software Distruibuído pela PUC - MG com o tema Sistema de Controle de Vendas com a Modalidade de Entrega Dropshipping.
Para execução do serviço "vendasweb" é preciso criar o arquivo .env conforme o arquivo .env.exemple, preenchendo os campos com as informações solicitadas.
Feito isso é necessário instalar as dependências (npm i) e depois iniciar a aplicação (npm start).
Para execução do serviço "controlevendas" é preciso criar um banco de dados (MySQL) com o nome pucmg_tcc.
Feito isso é necessário alterar o arquivo de properties da aplicação com as informações do banco de dados e da AWS (SNS e SQS) e iniciar a aplicação (mvn spring-boot:run).
Também pode-se buildar o projeto com o maven (mvn clean install) e executar o jar gerado.
PS: No projeto também existe um arquivo json com exemplo de menssagem para realizar o cadastro de produtos.
Para execução do serviço "spring-admin" basta alterar o arquivo de properties da aplicação com as informações de e-mail (origem e destino) e iniciar a aplicação (mvn spring-boot:run).
Também pode-se buildar o projeto com o maven (mvn clean install) e executar o jar gerado.
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/model/Endereco.java
package com.controlevendas.controlevendas.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "endereco")
public class Endereco implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id_endereco", unique = true, nullable = false)
private Long idEndereco;
@Column(name = "nr_cep", nullable = false)
private Long nrCep;
@Column(name = "nm_rua", nullable = false)
private String nmRua;
@Column(name = "nr_numero", nullable = false)
private Long nrNumero;
@Column(name = "nm_bairro", nullable = false)
private String nmBairro;
@Column(name = "ds_complemento", nullable = true)
private String dsComplemento;
@Column(name = "ds_referencia", nullable = true)
private String dsReferencia;
public Endereco() {
// Constructor
}
public Long getIdEndereco() {
return idEndereco;
}
public void setIdEndereco(Long idEndereco) {
this.idEndereco = idEndereco;
}
public Long getNrCep() {
return nrCep;
}
public void setNrCep(Long nrCep) {
this.nrCep = nrCep;
}
public String getNmRua() {
return nmRua;
}
public void setNmRua(String nmRua) {
this.nmRua = nmRua;
}
public Long getNrNumero() {
return nrNumero;
}
public void setNrNumero(Long nrNumero) {
this.nrNumero = nrNumero;
}
public String getNmBairro() {
return nmBairro;
}
public void setNmBairro(String nmBairro) {
this.nmBairro = nmBairro;
}
public String getDsComplemento() {
return dsComplemento;
}
public void setDsComplemento(String dsComplemento) {
this.dsComplemento = dsComplemento;
}
public String getDsReferencia() {
return dsReferencia;
}
public void setDsReferencia(String dsReferencia) {
this.dsReferencia = dsReferencia;
}
}
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/service/UsuarioService.java
package com.controlevendas.controlevendas.service;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.controlevendas.controlevendas.dao.UsuarioDao;
import com.controlevendas.controlevendas.model.Usuario;
@Service
public class UsuarioService {
private static final Logger log = LogManager.getLogger(UsuarioService.class);
@Autowired
private UsuarioDao usuarioDao;
/**
* Metodo responsavel por buscar um usuario por e-maill e senha
*
* @param email E-mail do usuario
* @param senha Senha do usuario
* @return usuario encontrado
*
* @<NAME>
*/
public Usuario retornaUsuario(String email, String senha) {
Usuario usuario = usuarioDao.findByNmEmailAndNmSenha(email, senha);
log.info("Usuário autenticado: " + usuario.getNmEmail());
return usuario;
}
/**
* Metodo responsavel por buscar um usuario pelo ID
*
* @param usuarioId ID do usuario
* @return usuario encontrado
*
* @author <NAME>
*/
public Usuario retornaUsuario(Long usuarioId) {
Optional<Usuario> usuario = usuarioDao.findById(usuarioId);
if (usuario.isPresent()) {
log.info("Usuário autorizado: " + usuario.get().getNmEmail());
return usuario.get();
}
return null;
}
}
<file_sep>/vendasweb/app/components/ProdutoItem/ProdutoItem.js
/**
* Componente que exibe um item produto para venda
*
* @author <NAME>
*/
import React from 'react';
import PropTypes from 'prop-types';
import CompraModal from 'components/CompraModal';
import './style.scss';
class ProdutoItem extends React.PureComponent {
render() {
return (
<div className="ct_produto_item" >
<img className="produto_imagem" src={this.props.produto.urlImagem} alt={this.props.produto.nmNome} />
<div className="produto_titulo">{this.props.produto.nmNome}</div>
<div className="produto_descricao">{this.props.produto.dsDescricao}</div>
<div className="ct_comprar">
<div className="produto_valor">{`R$ ${this.props.produto.nrValor}`}</div>
<CompraModal
produto={this.props.produto}
realizarPedido={this.props.realizarPedido}
pedido={this.props.pedido}
/>
</div>
</div>
);
}
}
ProdutoItem.propTypes = {
produto: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object,
]),
realizarPedido: PropTypes.func,
pedido: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object
])
};
export default ProdutoItem;
<file_sep>/vendasweb/app/containers/HomePage/constants.js
/**
* Constantes utilizadas para identificar um evento da HomePage
*
* @author <NAME>
*/
export const LOAD_PRODUTO_LIST = 'home/LOAD_PRODUTO_LIST';
export const LOAD_PRODUTO_LIST_SUCCESS = 'home/LOAD_PRODUTO_LIST_SUCCESS';
export const LOAD_PRODUTO_LIST_ERROR = 'home/LOAD_PRODUTO_LIST_ERROR';
export const REGISTRAR_PEDIDO = 'home/REGISTRAR_PEDIDO';
export const REGISTRAR_PEDIDO_SUCCESS = 'home/REGISTRAR_PEDIDO_SUCCESS';
export const REGISTRAR_PEDIDO_ERROR = 'home/REGISTRAR_PEDIDO_ERROR';
<file_sep>/vendasweb/app/containers/HomePage/actions.js
/**
* Arquivo com as ações que podem ser disparadas na HomePage
*
* @author <NAME>
*/
import {
LOAD_PRODUTO_LIST,
LOAD_PRODUTO_LIST_SUCCESS,
LOAD_PRODUTO_LIST_ERROR,
REGISTRAR_PEDIDO,
REGISTRAR_PEDIDO_SUCCESS,
REGISTRAR_PEDIDO_ERROR
} from './constants';
export function loadProdutoList() {
return {
type: LOAD_PRODUTO_LIST
};
}
export function loadProdutoListSuccess(data) {
return {
type: LOAD_PRODUTO_LIST_SUCCESS,
data
};
}
export function loadProdutoListError(error) {
return {
type: LOAD_PRODUTO_LIST_ERROR,
error
};
}
export function registrarPedido(pedido) {
return {
type: REGISTRAR_PEDIDO,
pedido
};
}
export function registrarPedidoSuccess(data) {
return {
type: REGISTRAR_PEDIDO_SUCCESS,
data
};
}
export function registrarPedidoError(error) {
return {
type: REGISTRAR_PEDIDO_ERROR,
error
};
}
<file_sep>/vendasweb/app/containers/HomePage/HomePage.js
/**
* Página que renderiza as informações exibidas na HomePage
*
* @author <NAME>
*/
import React from 'react';
import PropTypes from 'prop-types';
import LoadingIndicator from 'components/LoadingIndicator';
import ProdutoItem from 'components/ProdutoItem';
import './style.scss';
export default class HomePage extends React.PureComponent {
componentDidMount() {
this.props.loadProdutoList();
}
render() {
return (
<article className="app_page" >
<section>
<div className="ct_table_title">Produtos</div>
</section>
<section>
{this.props.produtoList && !this.props.produtoList.loading ?
<div className="ct_produtos">
{this.props.produtoList.data.map((produto) =>
(<ProdutoItem
produto={produto}
realizarPedido={this.props.realizarPedido}
pedido={this.props.pedido}
key={produto.idProduto}
/>)
)}
</div>
: <LoadingIndicator />
}
</section>
</article>
);
}
}
HomePage.propTypes = {
loadProdutoList: PropTypes.func,
produtoList: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object
]),
realizarPedido: PropTypes.func,
pedido: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object
])
};
<file_sep>/vendasweb/app/containers/HomePage/saga.js
/**
* Métodos que fazem as requisições para o backend da HomePage
*
* @author <NAME>
*/
import { call, put, takeLatest } from 'redux-saga/effects';
import request from 'utils/request';
import {
loadProdutoListSuccess,
loadProdutoListError,
registrarPedidoSuccess,
registrarPedidoError
} from './actions';
import { LOAD_PRODUTO_LIST, REGISTRAR_PEDIDO } from './constants';
/**
* Retorna a lista de produtos registrados
*
* @returns Lista de produtos
*
* @author <NAME>
*/
export function* getProdutoList() {
const requestURL = '/api/produto/listar';
const requestOpts = {
method: 'GET',
headers: {
'Content-type': 'application/json'
}
};
try {
const response = yield call(request, requestURL, requestOpts);
if (response.data.error) {
throw response.data;
}
yield put(loadProdutoListSuccess(response.data));
} catch (error) {
yield put(loadProdutoListError(error));
}
}
export function* insertPedido(action) {
const requestURL = '/api/pedido/cadastrar';
const requestOpts = {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(action.pedido),
};
try {
const response = yield call(request, requestURL, requestOpts);
if (response.data.error) {
throw response.data;
}
yield put(registrarPedidoSuccess(response.data));
} catch (error) {
yield put(registrarPedidoError(error));
}
}
export default function* retrievestoHomePage() {
yield takeLatest(LOAD_PRODUTO_LIST, getProdutoList);
yield takeLatest(REGISTRAR_PEDIDO, insertPedido);
}
<file_sep>/controlevendas/src/main/java/com/controlevendas/controlevendas/model/Cartao.java
package com.controlevendas.controlevendas.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "cartao")
public class Cartao implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id_cartao", unique = true, nullable = false)
private Long idCartao;
@Column(name = "nm_titular_nome", nullable = false)
private String nmTitularNome;
@Column(name = "nr_titular_cpf", nullable = false)
private Long nrTitularCpf;
@Column(name = "nr_numero_cartao", nullable = false)
private Long nrNumeroCartao;
@Column(name = "nr_codigo_seguranca", nullable = false)
private Long nrCodigoSeguranca;
@Column(name = "nr_validade_mes", nullable = false)
private Long nrValidadeMes;
@Column(name = "nr_validade_ano", nullable = false)
private Long nrValidadeAno;
public Cartao() {
// Constructor
}
public Long getIdCartao() {
return idCartao;
}
public void setIdCartao(Long idCartao) {
this.idCartao = idCartao;
}
public String getNmTitularNome() {
return nmTitularNome;
}
public void setNmTitularNome(String nmTitularNome) {
this.nmTitularNome = nmTitularNome;
}
public Long getNrTitularCpf() {
return nrTitularCpf;
}
public void setNrTitularCpf(Long nrTitularCpf) {
this.nrTitularCpf = nrTitularCpf;
}
public Long getNrNumeroCartao() {
return nrNumeroCartao;
}
public void setNrNumeroCartao(Long nrNumeroCartao) {
this.nrNumeroCartao = nrNumeroCartao;
}
public Long getNrCodigoSeguranca() {
return nrCodigoSeguranca;
}
public void setNrCodigoSeguranca(Long nrCodigoSeguranca) {
this.nrCodigoSeguranca = nrCodigoSeguranca;
}
public Long getNrValidadeMes() {
return nrValidadeMes;
}
public void setNrValidadeMes(Long nrValidadeMes) {
this.nrValidadeMes = nrValidadeMes;
}
public Long getNrValidadeAno() {
return nrValidadeAno;
}
public void setNrValidadeAno(Long nrValidadeAno) {
this.nrValidadeAno = nrValidadeAno;
}
}
<file_sep>/vendasweb/app/containers/HomePage/selectors.js
/**
* Funções para selecionar os states da HomePage
*
* @author <NAME>
*/
import { createSelector } from 'reselect';
const selectHome = (state) => state.get('home');
const makeSelectProdutoList = () => createSelector(
selectHome,
(homeState) => homeState.get('produtoList')
);
const makeSelectPedido = () => createSelector(
selectHome,
(homeState) => homeState.get('pedido')
);
export {
selectHome,
makeSelectProdutoList,
makeSelectPedido
};
<file_sep>/vendasweb/app/containers/HomePage/index.js
/**
* Arquivo de incialização da HomePage, com configuração e definição dos states e das funções utilizados
*
* @author <NAME>
*/
import { connect } from 'react-redux';
import { compose } from 'redux';
import { createStructuredSelector } from 'reselect';
import injectReducer from 'utils/injectReducer';
import injectSaga from 'utils/injectSaga';
import { loadProdutoList, registrarPedido } from './actions';
import { makeSelectProdutoList, makeSelectPedido } from './selectors';
import reducer from './reducer';
import saga from './saga';
import HomePage from './HomePage';
const mapDispatchToProps = (dispatch) => ({
loadProdutoList: () => { dispatch(loadProdutoList()); },
realizarPedido: (pedido) => { dispatch(registrarPedido(pedido)); }
});
const mapStateToProps = createStructuredSelector({
produtoList: makeSelectProdutoList(),
pedido: makeSelectPedido()
});
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({ key: 'home', reducer });
const withSaga = injectSaga({ key: 'home', saga });
export default compose(withReducer, withSaga, withConnect)(HomePage);
export { mapDispatchToProps };
<file_sep>/vendasweb/app/containers/NotFoundPage/index.js
/**
* Arquivo de incialização da NotFoundPage, com configuração e definição dos states e das funções utilizados
*
* @author <NAME>
*/
export { default } from './NotFoundPage';
| bef26564ed22c95b90c9bbd764e3ba89664daaea | [
"Markdown",
"Java",
"JavaScript"
] | 17 | Java | rodrigof23/pucmg-tccpos | 9763eff79ffaae9ea35ee4a011892ddb802f7259 | 0401a39cfaff7b09be8a89532cc326174a965e16 |
refs/heads/master | <file_sep>package com.txx;
public class txx {
public static void main(String[] args){
System.out.println("txx");
System.out.println("bbb");
}
}
| cd18d6e111e9362bd2ec84bb156abcdb73a51c11 | [
"Java"
] | 1 | Java | txxgit/test | 3e84a098d8037fd32df3bf05183fee5a4f38169d | 81fac4bc0b205eade71f2ad725c5300ca4e25fb4 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Dropbox.Api;
using Dropbox.Api.Auth;
using Nemiro.OAuth;
using Nemiro.OAuth.LoginForms;
using System.IO;
using System.Net;
using Dropbox.Api.Files;
using Microsoft.Win32;
using System.Data;
namespace FileMIApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Variables
private string strAppKey = "<KEY>";
private string strAppSecret = "<KEY>";
private string strAccessToken = string.Empty;
private string strAuthenticationURL = string.Empty;
private DropBoxIntegration DBB;
private HttpAuthorization Authorization = null;
private NewOAuthUtility NewOAuthUtility;
private string CurrentPath = "";
private Stream DownloadReader = null;
private FileStream DownloadFileStream = null;
private BinaryWriter DownloadWriter = null;
private byte[] DownloadReadBuffer = new byte[4096];
#endregion
#region Constructor
public MainWindow()
{
InitializeComponent();
}
#endregion
#region Private Methods
public void Authenticate()
{
try
{
if (string.IsNullOrEmpty(strAppKey))
{
MessageBox.Show("Please enter valid App Key !");
return;
}
if (DBB == null)
{
DBB = new DropBoxIntegration(strAppKey, strAppSecret, "FileMI");
strAuthenticationURL = DBB.GeneratedAuthenticationURL(); // This method must be executed before generating Access Token.
strAccessToken = DBB.GenerateAccessToken();
gbDropBox.IsEnabled = true;
this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, DBB.AccessTocken);
}
else gbDropBox.IsEnabled = false;
}
catch (Exception)
{
throw;
}
this.Getfiles();
}
#endregion
private void btnApiKey_Click(object sender, RoutedEventArgs e)
{
try
{
strAppKey = txtApiKey.Text.Trim();
Authenticate();
}
catch (Exception)
{
throw;
}
}
private void btnCreateFolder_Click(object sender, RoutedEventArgs e)
{
OAuthUtility.PostAsync
(
"https://api.dropboxapi.com/2/files/create_folder",
new HttpParameterCollection
{
new
{
path = ((String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") +
System.IO.Path.Combine(this.CurrentPath, this.MyTextBox.Text).Replace("\\", "/"))
}
},
contentType: "application/json",
authorization: this.Authorization,
callback: this.CreateFolder_Result
);
}
private void CreateFolder_Result(RequestResult result)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new Action<RequestResult>(this.CreateFolder_Result), result);
return;
}
if (result.StatusCode == 200)
{
this.Getfiles();
}
else
{
if (result["error"].HasValue)
{
MessageBox.Show(result["error"].ToString());
}
else
{
MessageBox.Show(result.ToString());
}
}
}
private void btlUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fileD = new OpenFileDialog();
Nullable<bool> result = fileD.ShowDialog();
if (result.HasValue && result.Value == false)
{
return;
}
var fs = new FileStream(fileD.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var fileInfo = UniValue.Empty;
fileInfo["path"] = (String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") + System.IO.Path
.Combine(this.CurrentPath, System.IO.Path.GetFileName(fileD.FileName))
.Replace("\\", "/");
fileInfo["mode"] = "add";
fileInfo["autorename"] = true;
fileInfo["mute"] = false;
OAuthUtility.PostAsync
("https://content.dropboxapi.com/2/files/upload",
new HttpParameterCollection
{
{fs}
},
headers: new NameValueCollection {{"Dropbox-API-Arg", fileInfo.ToString()}},
contentType: "application/octet-stream",
authorization: this.Authorization,
callback: this.Upload_Result,
streamWriteCallback: this.Upload_Processing
);
}
private void Upload_Processing(object sender, StreamWriteEventArgs e)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new Action<object, StreamWriteEventArgs>(this.Upload_Processing), sender, e);
return;
}
}
private void Upload_Result(RequestResult result)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new Action<RequestResult>(this.Upload_Result), result);
return;
}
if (result.StatusCode == 200)
{
this.Getfiles();
}
else
{
if (result["error"].HasValue)
{
MessageBox.Show(result["error"].ToString());
}
else
{
MessageBox.Show(result.ToString());
}
}
}
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
if (MyListBox.SelectedItem == null)
{
return;
}
var file = (UniValue)this.MyListBox.SelectedItem;
if (file[".tag"].Equals("folder"))
{
// this.CurrentPath = file["path_display"].ToString();
MessageBox.Show("Cannot download folder, please select a file");
return;
}
SaveFileDialog SaveF = new SaveFileDialog();
SaveF.FileName = System.IO.Path.GetFileName(file["path_display"].ToString());
Nullable<bool> result = SaveF.ShowDialog();
if (result.HasValue && result.Value == false)
{
return;
}
this.DownloadFileStream = new FileStream(SaveF.FileName, FileMode.Create, FileAccess.Write);
this.DownloadWriter = new BinaryWriter(this.DownloadFileStream);
var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");
req.Method = "GET";
req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = file["path_display"].ToString() }).ToString());
req.BeginGetResponse(resultB =>
{
var resp = req.EndGetResponse(resultB);
this.DownloadReader = resp.GetResponseStream();
this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length,
this.DownloadReadCallback, null);
}, null);
this.Getfiles();
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
NewOAuthUtility.DeleteAsync
(
"https://api.dropboxapi.com/2/files/delete_v2",
new HttpParameterCollection
{
new
{
path = ((String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") + System.IO.Path
.Combine(this.CurrentPath, this.MyTextBox.Text).Replace("\\", "/"))
}
},
contentType: "application/json",
authorization: this.Authorization,
callback: this.DeleteFile_Result
);
}
private void DeleteFile_Result(RequestResult result)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new Action<RequestResult>(this.DeleteFile_Result), result);
return;
}
if (result.StatusCode == 200)
{
this.Getfiles();
}
else
{
if (result["error"].HasValue)
{
MessageBox.Show(result["error"].ToString());
}
else
{
MessageBox.Show(result.ToString());
}
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}
public void Getfiles()
{
OAuthUtility.PostAsync
(
"https://api.dropboxapi.com/2/files/list_folder",
new HttpParameterCollection
{
new
{
path = this.CurrentPath,
include_media_info = true
}
//{"path", this.CurrentPath },
//{"access_token", <PASSWORD> }
},
contentType: "application/json",
authorization: this.Authorization,
callback: this.GetFiles_Result
);
}
public void GetFiles_Result(RequestResult result)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new Action<RequestResult>(GetFiles_Result), result);
return;
}
if (result.StatusCode == 200)
{
this.MyListBox.Items.Clear();
this.MyListBox.DisplayMemberPath = "path_display";
foreach (UniValue file in result["entries"])
{
MyListBox.Items.Add(file);
}
if (!String.IsNullOrEmpty(this.CurrentPath))
{
this.MyListBox.Items.Insert(0, UniValue.ParseJson("{path_display: '..'}"));
}
}
else
{
MessageBox.Show(result.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//MyTextBox.Text = MyListBox.SelectedItem.ToString().Split('/')[0];
//this.MyListBox.DisplayMemberPath = "name".ToString();
//MyTextBox.Text = MyListBox.SelectedItem.ToString();
//MyTextBox.Text = MyListBox.DisplayMemberPath = "path_display";
/*var memberpath = MyListBox.DisplayMemberPath = "path_display";
foreach (var file in memberpath)
{
MyTextBox.Text = MyListBox.SelectedItem.ToString();
}*/
//this.MyTextBox.Text = MyListBox.DisplayMemberPath.ToString();
//var selectedThing = MyListBox.SelectedItem.ToString();
//MyTextBox.Text = selectedThing.Substring(0, selectedThing.IndexOf("@") + 1);
}
private void MyListBox_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (MyListBox.SelectedItem == null)
{
return;
}
var file = (UniValue)this.MyListBox.SelectedItem;
if (file["path_display"] == "..")
{
if (!String.IsNullOrEmpty(this.CurrentPath))
{
this.CurrentPath = System.IO.Path.GetDirectoryName(this.CurrentPath).Replace("\\", "/");
if (this.CurrentPath == "/")
{
this.CurrentPath = "";
}
}
}
else
{
if (file[".tag"].Equals("folder"))
{
this.CurrentPath = file["path_display"].ToString();
}
else
{
SaveFileDialog SaveF = new SaveFileDialog();
SaveF.FileName = System.IO.Path.GetFileName(file["path_display"].ToString());
Nullable<bool> result = SaveF.ShowDialog();
if (result.HasValue && result.Value == false)
{
return;
}
this.DownloadFileStream = new FileStream(SaveF.FileName, FileMode.Create, FileAccess.Write);
this.DownloadWriter = new BinaryWriter(this.DownloadFileStream);
var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");
req.Method = "GET";
req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = file["path_display"].ToString() }).ToString());
req.BeginGetResponse(resultB =>
{
var resp = req.EndGetResponse(resultB);
this.DownloadReader = resp.GetResponseStream();
this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length,
this.DownloadReadCallback, null);
}, null);
}
}
this.Getfiles();
}
private void DownloadReadCallback(IAsyncResult resultB)
{
var bytesRead = this.DownloadReader.EndRead(resultB);
if (bytesRead > 0)
{
if (this.DownloadFileStream.CanWrite)
{
this.DownloadWriter.Write(this.DownloadReadBuffer.Take(bytesRead).ToArray());
this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length,
DownloadReadCallback, null);
}
}
else
{
this.DownloadFileStream.Close();
}
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
OAuthUtility.PostAsync
(
"https://api.dropboxapi.com/2/files/search",
new HttpParameterCollection
{
new
{
//string som man skal søge.
query = MyTextBox.Text,
// den path i brugerens dropbox man skal søge i.
path = this.CurrentPath
}
},
contentType: "application/json",
authorization: this.Authorization,
callback: this.GetFilesSearch_Result
);
}
private void GetFilesSearch_Result(RequestResult result)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(new Action<RequestResult>(GetFilesSearch_Result), result);
return;
}
if (result.StatusCode == 200)
{
this.MyListBox.Items.Clear();
this.MyListBox.DisplayMemberPath = "metadata";
foreach (UniValue file in result["matches"])
{
MyListBox.Items.Add(file);
}
if (!String.IsNullOrEmpty(this.CurrentPath))
{
this.MyListBox.Items.Insert(0, UniValue.ParseJson("{path_display: '..'}"));
}
}
else
{
MessageBox.Show(result.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void MyListBox_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (string file in files)
{
var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var fileInfo = UniValue.Empty;
fileInfo["path"] = (String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") + System.IO.Path
.Combine(this.CurrentPath, System.IO.Path.GetFileName(file))
.Replace("\\", "/");
fileInfo["mode"] = "add";
fileInfo["autorename"] = true;
fileInfo["mute"] = false;
OAuthUtility.PostAsync
("https://content.dropboxapi.com/2/files/upload",
new HttpParameterCollection
{
{fs}
},
headers: new NameValueCollection { { "Dropbox-API-Arg", fileInfo.ToString() } },
contentType: "application/octet-stream",
authorization: this.Authorization,
callback: this.Upload_Result,
streamWriteCallback: this.Upload_Processing
);
}
}
private void MyListBox_DragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.All;
}
private void BtnUpdate_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog fileD = new OpenFileDialog();
Nullable<bool> result = fileD.ShowDialog();
if (result.HasValue && result.Value == false)
{
return;
}
var fs = new FileStream(fileD.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var fileInfo = UniValue.Empty;
fileInfo["path"] = (String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") + System.IO.Path
.Combine(this.CurrentPath, System.IO.Path.GetFileName(fileD.FileName))
.Replace("\\", "/");
fileInfo["mode"] = "add";
fileInfo["autorename"] = true;
fileInfo["mute"] = false;
OAuthUtility.PostAsync
("https://content.dropboxapi.com/2/files/upload",
new HttpParameterCollection
{
{fs}
},
headers: new NameValueCollection { { "Dropbox-API-Arg", fileInfo.ToString() } },
contentType: "application/octet-stream",
authorization: this.Authorization,
callback: this.Upload_Result,
streamWriteCallback: this.Upload_Processing
);
NewOAuthUtility.DeleteAsync
(
"https://api.dropboxapi.com/2/files/delete_v2",
new HttpParameterCollection
{
new
{
path = ((String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") + System.IO.Path
.Combine(this.CurrentPath, this.MyTextBox.Text).Replace("\\", "/"))
}
},
contentType: "application/json",
authorization: this.Authorization,
callback: this.DeleteFile_Result
);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms.VisualStyles;
using System.Windows.Threading;
using Dropbox.Api;
using Dropbox.Api.Files;
using Microsoft.Win32;
using Nemiro.OAuth;
using Nemiro.OAuth.LoginForms;
namespace FileMIApp
{
class DropBoxIntegration
{
private DropboxClient DBClient;
private ListFolderArg DBFolders;
private string oauth2State;
private const string RedirectUri = "https://filemi.eu.auth0.com/login/callback";
private string CurrentPath = "";
//Contructor
public DropBoxIntegration(string Apikey, string ApiSecret, string ApplicationName = "FileMI")
{
try
{
AppKey = Apikey;
AppSecret = ApiSecret;
AppName = ApplicationName;
}
catch (Exception )
{
throw;
}
}
public string AppKey
{
get;
private set;
}
public string AppSecret
{
get;
private set;
}
public string AppName
{
get;
private set;
}
public string AuthenticationUrl
{
get;
private set;
}
public string AccessTocken
{
get;
private set;
}
public string Uid
{
get;
private set;
}
public string GeneratedAuthenticationURL()
{
try
{
this.oauth2State = Guid.NewGuid().ToString("N");
Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, AppKey, RedirectUri,
state: oauth2State);
AuthenticationUrl = authorizeUri.AbsoluteUri.ToString();
return authorizeUri.AbsoluteUri.ToString();
}
catch (Exception )
{
throw;
}
}
public string GenerateAccessToken()
{
try
{
string _strAccessToken = string.Empty;
if (CanAuthenticate())
{
if (string.IsNullOrEmpty(AuthenticationUrl))
{
throw new Exception("AuthenticationURL is not generated !");
}
Login login = new Login(AppKey, AuthenticationUrl, this.oauth2State);
login.Owner = Application.Current.MainWindow;
login.ShowDialog();
if (login.Result)
{
_strAccessToken = login.AccessToken;
AccessTocken = login.AccessToken;
Uid = login.Uid;
DropboxClientConfig CC = new DropboxClientConfig(AppName, 1);
HttpClient HTC = new HttpClient();
HTC.Timeout = TimeSpan.FromMinutes(10);
CC.HttpClient = HTC;
DBClient = new DropboxClient(AccessTocken, CC);
}
else
{
DBClient = null;
AccessTocken = string.Empty;
Uid = string.Empty;
}
}
return _strAccessToken;
}
catch (Exception ex)
{
throw ex;
}
}
private bool CanAuthenticate()
{
try
{
if (AppKey == null)
{
throw new ArgumentNullException("AppKey");
}
if (AppSecret == null)
{
throw new ArgumentNullException("AppSecret");
}
return true;
}
catch (Exception e)
{
throw;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Nemiro.OAuth;
namespace FileMIApp
{
class NewOAuthUtility
{
public static void DeleteAsync(string endpoint = null, HttpParameterCollection parameters = null,
HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null,
AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null, bool allowWriteStreamBuffering = false,
bool allowSendChunked = true, long contentLength = -1, HttpWriteRequestStream streamWriteCallback = null,
int writeBufferSize = 4096, int readBufferSize = 4096, bool donotEncodeKeys = false)
{
NewOAuthUtility.ExecuteRequestAsync("DELETE", endpoint, parameters, authorization, headers, contentType, accessToken,
callback, allowWriteStreamBuffering, allowSendChunked, contentLength, streamWriteCallback, writeBufferSize,
readBufferSize, donotEncodeKeys);
}
public static void ExecuteRequestAsync(string method = "POST", string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null, bool allowWriteStreamBuffering = false, bool allowSendChunked = true, long contentLength = -1, HttpWriteRequestStream streamWriteCallback = null, int writeBufferSize = 4096, int readBufferSize = 4096, bool donotEncodeKeys = false)
{
new Thread((ThreadStart)(() =>
{
RequestResult result;
try
{
result = OAuthUtility.ExecuteRequest(method, endpoint, parameters, authorization, headers, contentType, accessToken, allowWriteStreamBuffering, allowSendChunked, contentLength, streamWriteCallback, writeBufferSize, readBufferSize, donotEncodeKeys);
}
catch (RequestException ex)
{
result = ex.RequestResult;
}
if (callback == null)
return;
callback(result);
}))
{
IsBackground = true
}.Start();
}
}
}
| 3e30a3639c19fec0d4abc1dfc6062e3aa552c68d | [
"C#"
] | 3 | C# | Matiasromer/FileMIApp | 814a4a3d4c2f509d3a2918afcc281b6f4e250003 | 45749292349d2997c94ec12eb61b7fa2d20d402e |
refs/heads/master | <repo_name>SaraRandolph/questions-and-answers<file_sep>/app/config/init.js
var app = angular.module('SaraStackUnderflow', [
'firebase',
'ui.router',
'summernote',
"ngSanitize",
]);
<file_sep>/app/components/views/home/home-controller.js
app.controller('HomeController', function($firebaseArray, $scope, QuestionService, CONSTANTS) {
// $scope.activeQuestion = QuestionService.setActiveQuestion().then(function(a, b) {
// debugger;
// $state.go("question", { id: $state.params.id })
// })
$scope.questionList = QuestionService.getQuestions();
$scope.vote = 0;
$scope.changeVote = function(question) {
$scope.dishes.$add($scope.newDish).then(function(dish) {
$rootScope.member.dishList = $rootScope.member.dishList || {}
$rootScope.member.dishList[dish.key()] = $scope.newDish;
$rootScope.member.$save();
$scope.newDish = ''
});
}
});
// $rootScope, $state, AuthService, CONSTANTS, $firebaseObject
// var mc = this;
// var db = new Firebase(FBREF);
// $scope.questionsArr = $firebaseArray(new Firebase(FBREF + 'questions'));
// $scope.member;
// function handleDBResponse (err, authData){
// if(err){
// console.log(err);
// return;
// }
// console.log(authData);
// var userToSave = {
// username: mc.user.email,
// reputation: 0,
// created: Date.now()
// }
// $scope.$apply(function(){
// $scope.member = userToSave;
// })
// db.child('users').child(authData.uid).update(userToSave);
// }
// $scope.register = function(){
// db.createUser(mc.user, handleDBResponse);
// }
// $scope.login = function(){
// console.log(mc.user)
// db.authWithPassword(mc.user, handleDBResponse)
// }
// // set active question
// $scope.setActiveQuestion = function(question){
// $scope.activeQuestion = $firebaseObject(new Firebase(FBREF + 'questions/' +question.$id));
// $scope.activeQuestionResponses = $firebaseArray(new Firebase(FBREF + 'questions/' +question.$id + '/responses'))
// }
<file_sep>/app/components/views/ask-a-question/ask-question-controller.js
app.controller('AskQuestionController', function($scope, $rootScope, QuestionService, $firebaseArray, $state){
$scope.questions = QuestionService.getQuestions();
$scope.createQuestion = function(newQuestion) {
debugger;
newQuestion.date = Date.now();
newQuestion.votes = 0;
$scope.questions.$add($scope.newQuestion).then(function() {
$rootScope.member.questionList = $rootScope.member.questionList || {};
$rootScope.member.questionList = $scope.newQuestion;
$rootScope.member.$save();
$scope.newQuestion = '';
})
}
$scope.goHome = function(){
$state.go("home")
}
})<file_sep>/app/config/routes.js
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home',{
url:'/',
templateUrl:'app/components/views/home/home.html',
controller: 'HomeController',
controllerAs: 'hc'
})
.state('login',{
url:'/login',
templateUrl:'app/components/views/login/login.html',
controller: 'RegistrationController'
})
.state('registration',{
url:'/registration',
templateUrl:'app/components/views/registration/registration.html',
controller: 'RegistrationController'
})
.state('askQuestion',{
url:'/ask-question',
templateUrl:'app/components/views/ask-a-question/askquestion.html',
controller: 'AskQuestionController',
controllerAs: 'sc'
})
.state('profile',{
url:'/profile',
templateUrl:'app/components/views/profile/profile.html',
controller: 'ProfileController'
})
.state('viewQuestion',{
url:'/:id',
templateUrl:'app/components/views/view-question/viewquestion.html',
controller: 'ViewQuestionController'
})
})
// Sets auto Login
app.run(function ($rootScope, $state, AuthService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toStateParams) {
var invalidUser = AuthService.authMember();
if (invalidUser) {
//FORCES AUTHENTICATION
if (toState.name !== 'login' && toState.name !== 'registration') {
event.preventDefault()
$state.go('login')
}
}
});
})<file_sep>/app/components/views/view-question/view-question-controller.js
app.controller('ViewQuestionController', function($scope, QuestionService, $rootScope, $firebaseArray, $stateParams){
$scope.question = QuestionService.getQuestion($stateParams.id)
$scope.addResponse = function(newResponse) {
newResponse.member = $rootScope.member.$id;
newResponse.solution = false;
newResponse.votes = 0
$scope.question.responses = [];
$scope.question.responses.push(newResponse)
$scope.question.$save().then(function(question){
$rootScope.member.responsesList = $rootScope.member.responsesList || {}
$rootScope.member.responsesList[question.key()] = [];
$rootScope.member.responsesList[question.key()].push(newResponse)
$rootScope.member.$save();
$scope.newResponse = "";
})
}
})<file_sep>/app/components/views/profile/profile-controller.js
app.controller('ProfileController', function($scope, $firebaseArray, CONSTANTS, $firebaseObject){
$scope.removeQuestion = function (index) {
$scope.questionsArr.splice(index, 1)
}
$scope.solution = {
value:false
}
}) | 78e4fcc30226754b9ce4517f56b04d74d655a6ee | [
"JavaScript"
] | 6 | JavaScript | SaraRandolph/questions-and-answers | 746ff5c44da0d03ab582489d25fd3a6c17345232 | 9a0f9838364a18fb904078b356ca80f3e273119e |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
public class Platillo
{
private string descripcion;
private double importe;
private int clavePla, tiempo;
static int cont = 1000;
public Platillo(string desc, double imp, int tiemp)
{
descripcion = desc;
importe = imp;
tiempo = tiemp;
clavePla = cont;
cont += 5;
}
public int pClave
{
get
{
return clavePla;
}
}
public string pDesc
{
get
{
return descripcion;
}
set
{
descripcion = value;
}
}
public double pImporte
{
get
{
return importe;
}
set
{
importe = value;
}
}
public int pTiempo
{
get
{
return tiempo;
}
set
{
tiempo = value;
}
}
public static int ObtieneClave()
{
return cont;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmMenu : Form
{
AdministraMesa admMesas;
ListPlatillos LPlatillos;
DictionaryPedidos dPedidos;
ListPlatillosPedidos lPlaPe;
public frmMenu()
{
InitializeComponent();
admMesas = new AdministraMesa();
LPlatillos = new ListPlatillos();
lPlaPe = new ListPlatillosPedidos(LPlatillos);
dPedidos = new DictionaryPedidos(lPlaPe);
}
private void registrarToolStripMenuItem_Click(object sender, EventArgs e)
{
frmAltaMesas AltaMesas = new frmAltaMesas(admMesas);
AltaMesas.ShowDialog();
}
private void salirToolStripMenuItem1_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("¿Deseas Salir?", "Confirmar", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Application.Exit();
}
}
private void todasToolStripMenuItem_Click(object sender, EventArgs e)
{
frmConsultaMesas ConsultaMesas = new frmConsultaMesas(admMesas);
ConsultaMesas.ShowDialog();
}
private void registrarToolStripMenuItem1_Click(object sender, EventArgs e)
{
frmPlatillos RegistraPlatillos = new frmPlatillos(LPlatillos);
RegistraPlatillos.ShowDialog();
}
private void consultarToolStripMenuItem1_Click(object sender, EventArgs e)
{
frmConsultaPlatillos ConsultaPlatillo = new frmConsultaPlatillos(LPlatillos);
ConsultaPlatillo.ShowDialog();
}
private void registrarToolStripMenuItem2_Click(object sender, EventArgs e)
{
frmPedidos registraPedidos = new frmPedidos(LPlatillos, dPedidos, lPlaPe,admMesas);
registraPedidos.ShowDialog();
}
private void AsignartoolStripMenuItem_Click(object sender, EventArgs e)
{
frmAsignaMesa asigna = new frmAsignaMesa(admMesas);
asigna.ShowDialog();
}
private void todosToolStripMenuItem_Click(object sender, EventArgs e)
{
frmReportePedidos reporte = new frmReportePedidos(dPedidos);
reporte.ShowDialog();
}
private void reportePlatillosPedidosToolStripMenuItem_Click(object sender, EventArgs e)
{
frmReportePlatilloPedido reporte = new frmReportePlatilloPedido(lPlaPe);
reporte.ShowDialog();
}
private void pagarCuentaToolStripMenuItem_Click(object sender, EventArgs e)
{
frmPagarCuenta pagar = new frmPagarCuenta();
pagar.ShowDialog();
}
private void cierreDelDiaToolStripMenuItem_Click(object sender, EventArgs e)
{
frmCierreDia cierre = new frmCierreDia();
cierre.ShowDialog();
}
private void frmMenu_Load(object sender, EventArgs e)
{
}
private void individualToolStripMenuItem_Click(object sender, EventArgs e)
{
frmConsultaMesaIndividual consulta = new frmConsultaMesaIndividual(admMesas);
consulta.ShowDialog();
}
private void agregaPlatilloToolStripMenuItem_Click(object sender, EventArgs e)
{
frmAgregaPlatilloV2 agrega = new frmAgregaPlatilloV2(LPlatillos, dPedidos, lPlaPe, admMesas);
agrega.ShowDialog();
}
private void individualToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmReportePedidos : Form
{
DictionaryPedidos dPedidos;
public frmReportePedidos(DictionaryPedidos dP)
{
InitializeComponent();
dPedidos = dP;
}
private void frmReportePedidos_Load(object sender, EventArgs e)
{
string[] numPe = dPedidos.arregloNumPedidos();
string[] numMesa = dPedidos.arregloNumMesa();
string[] numBebidas = dPedidos.arregloNumBebidas();
string[] numPla = dPedidos.arregloNumPlatillos();
for (int i = 0; i < numPe.Length; i++)
{
dgvPedidos.Rows.Add(numPe[i], numMesa[i], numBebidas[i], numPla[i]);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
class Pedido
{
private int numMesa, numBebidas, numPlatillos;
public Pedido(int numM, int numbe)
{
numMesa = numM;
numBebidas = numbe;
}
public int pNumMesa
{
get
{
return numMesa;
}
set
{
numMesa = value;
}
}
public int pnumBebidas
{
get
{
return numBebidas;
}
set
{
numBebidas = value;
}
}
public int pNumPlatillos
{
get
{
return numPlatillos;
}
set
{
numPlatillos = value;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
class ListVentas
{
private List<Ventas> lVentas;
public ListVentas()
{
lVentas = new List<Ventas>();
}
public void AgregaVenta (int numP, double importe)
{
Ventas ven = new Ventas(numP, importe);
lVentas.Add(ven);
}
public double TotalVentas()
{
return Ventas.retornaTotal();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmAltaMesas : Form
{
AdministraMesa admMesas;
public frmAltaMesas(AdministraMesa aMesas)
{
InitializeComponent();
admMesas = aMesas;
txtNumMesa.Text = Mesa.RetornaNumMesa().ToString();
}
private void btnGuardar_Click(object sender, EventArgs e)
{
if (admMesas.RegresaTamaño() >= 10)
{
MessageBox.Show("NUMERO MAXIMO DE MESAS", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (ValidarDescripcion())
{
string desc = cmbDescripcion.SelectedItem.ToString();
int numPersonas = Convert.ToInt32(numUpNumPer.Value.ToString());
admMesas.AgregaMesas(desc, numPersonas);
MessageBox.Show("Mesa Agregada Con Exito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (admMesas.RegresaTamaño()<=9)
{
txtNumMesa.Text = Mesa.RetornaNumMesa().ToString();
}
//limpia
cmbDescripcion.SelectedIndex = -1;
numUpNumPer.Value = 1;
cmbDescripcion.Focus();
}
}
}
public bool ValidarDescripcion()
{
bool retorno = false;
if (cmbDescripcion.SelectedIndex != -1)
{
retorno = true;
}
return retorno;
}
private void cmbDescripcion_Validating(object sender, CancelEventArgs e)
{
if (cmbDescripcion.SelectedIndex == -1)
{
ErrorPMesas.SetError(cmbDescripcion, "Descripcion Vacia");
cmbDescripcion.Focus();
}
else
{
ErrorPMesas.SetError(cmbDescripcion, "");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmConsultaMesas : Form
{
AdministraMesa admMesa;
public frmConsultaMesas(AdministraMesa aMesa)
{
InitializeComponent();
admMesa = aMesa;
}
private void frmConsultaMesas_Load(object sender, EventArgs e)
{
string[] numM = admMesa.NumeroDeMesas();
string[] desc = admMesa.arregloDescripcion();
string[] estatus = admMesa.arregloEstatus();
string[] nombreC = admMesa.arregloNombreCliente();
string[] numP = admMesa.arregloNumPersonas();
for (int i = 0; i < numM.Length; i++)
{
dgvConsultaMesas.Rows.Add(numM[i], nombreC[i], desc[i], numP[i], estatus[i]);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmReportePlatilloPedido : Form
{
ListPlatillosPedidos lPlaPe;
public frmReportePlatilloPedido(ListPlatillosPedidos lpp)
{
InitializeComponent();
lPlaPe = lpp;
}
private void frmReportePlatilloPedido_Load(object sender, EventArgs e)
{
int[] numPe = lPlaPe.RetornaNumPedidos();
int[] ClaveP = lPlaPe.RetornaClavesP();
int[] Cant = lPlaPe.RetornaCant();
for (int i = 0; i < numPe.Length; i++)
{
DataGReportePlaPed.Rows.Add(numPe[i], ClaveP[i],Cant[i]);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmAgregaPlatilloV2 : Form
{
ListPlatillos listPlatillos;
ListPlatillosPedidos lPLaPedidos;
DictionaryPedidos dPedidos;
AdministraMesa admMesa;
int numPe, numMesa, op=1;
public frmAgregaPlatilloV2(ListPlatillos lPlatillos, DictionaryPedidos dP, ListPlatillosPedidos lPlaPe, AdministraMesa aM)
{
InitializeComponent();
listPlatillos = lPlatillos;
lPLaPedidos = lPlaPe;
dPedidos = dP;
admMesa = aM;
}
public frmAgregaPlatilloV2(ListPlatillos lPlatillos, DictionaryPedidos dP, ListPlatillosPedidos lPlaPe, AdministraMesa aM, int numP, int numM, int op2)
{
InitializeComponent();
listPlatillos = lPlatillos;
lPLaPedidos = lPlaPe;
dPedidos = dP;
admMesa = aM;
numPe = numP;
numMesa = numM;
op = op2;
}
private void btnTerminar_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("¿Estas Seguro De Salir?", "Confirmar", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
this.Close();
}
//Limpiar AL Terminar
cmbNumPe.Text = "";
lblNombre.Text = "Nombre";
cmbDescripcion.Text = "";
numUpCantidad.Value = 1;
dtgvPlatillo.Rows.Clear();
}
private void btnQuitar_Click(object sender, EventArgs e)
{
int clavePla = Convert.ToInt32(dtgvPlatillo.CurrentRow.Cells[0].Value);
lPLaPedidos.QuitarPlatillo(numPe, clavePla);
dPedidos.ActualizaPedido(numPe);
dtgvPlatillo.Rows.Clear();
string[] Aclave = lPLaPedidos.RegresaPlatilloClaves(numPe);
string[] Adesc = lPLaPedidos.RegresaPlatilloDescripcion(numPe);
string[] Aimporte = lPLaPedidos.RegresaPlatilloImporte(numPe);
string[] Atiempo = lPLaPedidos.RegresaPlatilloTiempo(numPe);
for (int i = 0; i < Aclave.Length; i++)
{
dtgvPlatillo.Rows.Add(Aclave[i], Adesc[i], Aimporte[i], Atiempo[i]);
}
}
private void cmbNumPe_SelectedIndexChanged(object sender, EventArgs e)
{
dtgvPlatillo.Rows.Clear();
numPe = Convert.ToInt32(cmbNumPe.SelectedItem.ToString());
numMesa = dPedidos.PedidoMesa(numPe);
string nombreC = admMesa.RegresaNombreCliente(numMesa);
lblNombre.Text = nombreC;
string[] Aclave = lPLaPedidos.RegresaPlatilloClaves(numPe);
string[] Adesc = lPLaPedidos.RegresaPlatilloDescripcion(numPe);
string[] Aimporte = lPLaPedidos.RegresaPlatilloImporte(numPe);
string[] Atiempo = lPLaPedidos.RegresaPlatilloTiempo(numPe);
for (int i = 0; i < Aclave.Length; i++)
{
dtgvPlatillo.Rows.Add(Aclave[i], Adesc[i], Aimporte[i], Atiempo[i]);
}
}
private void btnAgregar_Click(object sender, EventArgs e)
{
int cant = Convert.ToInt32(numUpCantidad.Value.ToString());
string desc = cmbDescripcion.SelectedItem.ToString();
int clavePla = listPlatillos.NombreAClave(desc);
double importe = listPlatillos.RegresaImporte(clavePla);
int tiempo = listPlatillos.RegresaTiempo(clavePla);
lPLaPedidos.AgregarPlatillo(numPe, clavePla, cant);
dPedidos.ActualizaPedido(numPe);
//agrega al grid
dtgvPlatillo.Rows.Clear();
string[] Aclave = lPLaPedidos.RegresaPlatilloClaves(numPe);
string[] Adesc = lPLaPedidos.RegresaPlatilloDescripcion(numPe);
string[] Aimporte = lPLaPedidos.RegresaPlatilloImporte(numPe);
string[] Atiempo = lPLaPedidos.RegresaPlatilloTiempo(numPe);
for (int i = 0; i < Aclave.Length; i++)
{
dtgvPlatillo.Rows.Add(Aclave[i], Adesc[i], Aimporte[i], Atiempo[i]);
}
}
private void frmAgregaPlatilloV2_Load(object sender, EventArgs e)
{
string[] numPedidos = dPedidos.arregloNumPedidos();
for (int i = 0; i < numPedidos.Length; i++)
{
cmbNumPe.Items.Add(numPedidos[i]);
}
string[] descripcion = listPlatillos.arregloDescripcion();
for (int i = 0; i < descripcion.Length; i++)
{
cmbDescripcion.Items.Add(descripcion[i]);
}
if (op != 1)
{
cmbNumPe.Enabled = false;
cmbNumPe.Text = numPe.ToString();
string nombreC = admMesa.RegresaNombreCliente(numMesa);
lblNombre.Text = nombreC;
string[] Aclave = lPLaPedidos.RegresaPlatilloClaves(numPe);
string[] Adesc = lPLaPedidos.RegresaPlatilloDescripcion(numPe);
string[] Aimporte = lPLaPedidos.RegresaPlatilloImporte(numPe);
string[] Atiempo = lPLaPedidos.RegresaPlatilloTiempo(numPe);
for (int i = 0; i < Aclave.Length; i++)
{
dtgvPlatillo.Rows.Add(Aclave[i], Adesc[i], Aimporte[i], Atiempo[i]);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmAgregaPlatillo : Form
{
ListPlatillosPedidos lPLaPedidos;
DictionaryPedidos dPedidos;
public frmAgregaPlatillo(DictionaryPedidos dP, ListPlatillosPedidos lPlaPe)
{
InitializeComponent();
lPLaPedidos = lPlaPe;
dPedidos = dP;
}
private void btnTerminar_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
class Ventas
{
private double importe;
private int numP;
private static double total=0;
public Ventas (int numP,double importe)
{
this.numP = numP;
this.importe = importe;
total += importe;
}
public double pImporte
{
get
{
return importe;
}
set
{
importe = value;
}
}
public int pNumP
{
get
{
return numP;
}
set
{
numP = value;
}
}
public static double retornaTotal()
{
return total;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
public class ListPlatillos
{
private List<Platillo> ListPlatillo;
public ListPlatillos()
{
ListPlatillo = new List<Platillo>();
}
public void AgregaPlatillo(string desc, double importe, int tiempo)
{
Platillo platillo = new Platillo(desc, importe, tiempo);
ListPlatillo.Add(platillo);
}
public string[] ReportePlatillos()
{
string[] cadena = new string[ListPlatillo.Count];
for (int i = 0; i < ListPlatillo.Count; i++)
{
cadena[i] = "CLAVE: " + ListPlatillo[i].pClave + ", DESCRIPCION: " + ListPlatillo[i].pDesc + ", IMPORTE: " + ListPlatillo[i].pImporte + ", TIEMPO DE PREPARACION: " + ListPlatillo[i].pTiempo;
}
return cadena;
}
public int Tamaño()
{
return ListPlatillo.Count;
}
//nuevo
public bool ValidarPlatilloDesc(string desc)
{
bool encontrado = false;
foreach (Platillo item in ListPlatillo)
{
if (item.pDesc.Equals(desc))
{
encontrado = true;
break;
}
}
return encontrado;
}
public string[] arregloClave()
{
string[] cadena = new string[ListPlatillo.Count];
int pos = 0;
foreach (Platillo item in ListPlatillo)
{
cadena[pos] = item.pClave.ToString();
pos++;
}
return cadena;
}
public string[] arregloDescripcion()
{
string[] cadena = new string[ListPlatillo.Count];
int pos = 0;
foreach (Platillo item in ListPlatillo)
{
cadena[pos] = item.pDesc;
pos++;
}
return cadena;
}
public string[] arregloImporte()
{
string[] cadena = new string[ListPlatillo.Count];
int pos = 0;
foreach (Platillo item in ListPlatillo)
{
cadena[pos] = item.pImporte.ToString();
pos++;
}
return cadena;
}
public string[] arregloTiempo()
{
string[] cadena = new string[ListPlatillo.Count];
int pos = 0;
foreach (Platillo item in ListPlatillo)
{
cadena[pos] = item.pTiempo.ToString();
pos++;
}
return cadena;
}
public string RegresaDescripcion(int clavePla)
{
string desc = "";
foreach (Platillo item in ListPlatillo)
{
if (item.pClave.Equals(clavePla))
{
desc = item.pDesc;
}
}
return desc;
}
public double RegresaImporte (int clavePla)
{
double importe=0;
foreach (Platillo item in ListPlatillo)
{
if (item.pClave.Equals(clavePla))
{
importe = item.pImporte;
}
}
return importe;
}
public int RegresaTiempo(int clavePla)
{
int tiempo = 0;
foreach (Platillo item in ListPlatillo)
{
if (item.pClave.Equals(clavePla))
{
tiempo = item.pTiempo;
}
}
return tiempo;
}
//
public bool ListVacio()
{
bool vacio = false;
if (ListPlatillo.Count() == 0)
{
vacio = true;
}
return vacio;
}
public int NombreAClave(string cadena)
{
int clave = -1;
for (int i = 0; i < ListPlatillo.Count; i++)
{
if (ListPlatillo[i].pDesc == cadena)
{
clave = ListPlatillo[i].pClave;
}
}
return clave;
}
public bool BuscaPlatillo(int clave)
{
bool existe = false;
foreach (Platillo item in ListPlatillo)
{
if (item.pClave == clave)
{
existe = true;
}
}
return existe;
}
public double Importe(int clave)
{
double importe = 0;
for (int i = 0; i < ListPlatillo.Count; i++)
{
if (ListPlatillo[i].pClave == clave)
{
importe = ListPlatillo[i].pImporte;
break;
}
}
return importe;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
class Mesa
{
private int numMesa, numPersonas;
private string descripcion;
private bool estatus;
private string nombreCliente;
private static int numM=1;
public Mesa(string desc, int numPersonas)
{
numMesa = numM;
numM++;
descripcion = desc;
this.numPersonas = numPersonas;
estatus = true;
}
public int pNumMesa
{
get
{
return numMesa;
}
}
public int pNumPersonas
{
get
{
return numPersonas;
}
set
{
numPersonas = value;
}
}
public string pDescripcion
{
get
{
return descripcion;
}
set
{
descripcion = value;
}
}
public bool pEstatus
{
get
{
return estatus;
}
set
{
estatus = value;
}
}
public string pNombreCliente
{
get
{
return nombreCliente;
}
set
{
nombreCliente = value;
}
}
public static int RetornaNumMesa()
{
return numM;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmPedidos : Form
{
ListPlatillos listPlatillos;
DictionaryPedidos dPedidos;
ListPlatillosPedidos lPLaPedidos;
AdministraMesa admMesa;
public frmPedidos(ListPlatillos lPlatillos, DictionaryPedidos dP, ListPlatillosPedidos lPlaPe,AdministraMesa aM)
{
InitializeComponent();
listPlatillos = lPlatillos;
dPedidos = dP;
lPLaPedidos = lPlaPe;
admMesa = aM;
}
private void btnAgregaPlatillo_Click(object sender, EventArgs e)
{
bool agregar = true;
if (ValidarVacio())
{
if (ValidarMESA())
{
if (ValidarVacioPedido())
{
int numPe = Convert.ToInt32(txtNumPe.Text.ToString());
if (lPLaPedidos.numPExiste(numPe))
{
ErrorPPedido.SetError(txtNumPe, "Numero De Pedido Invalido");
txtNumPe.Focus();
agregar = false;
}
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem);
if (admMesa.RegresaNombreCliente(numM).Equals("NO ASIGNADA"))
{
MessageBox.Show("MESA SIN ASIGNAR!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
//limpiar errorprovider
ErrorPPedido.SetError(cmbNumMesa, "");
ErrorPPedido.SetError(txtNumPe, "");
agregar = false;
}
if (listPlatillos.ListVacio())
{
MessageBox.Show("NO HAY PLATILLOS AGREGADOS!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
agregar = false;
}
if (agregar != false)
{
int numBe = Convert.ToInt32(numUpBebidas.Value);
dPedidos.AgregaPedido(numPe, numM, numBe);
frmAgregaPlatilloV2 agrega = new frmAgregaPlatilloV2(listPlatillos, dPedidos, lPLaPedidos, admMesa, numPe, numM, 2);
agrega.ShowDialog();
txtNumPe.Enabled = false;
cmbNumMesa.Enabled = false;
//limpiar errorprovider
ErrorPPedido.SetError(cmbNumMesa, "");
ErrorPPedido.SetError(txtNumPe, "");
}
}
}
}
}
private void btmGuardar_Click(object sender, EventArgs e)
{
bool guardar = true;
if (ValidarVacio())
{
if (ValidarVacioPedido())
{
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem);
if (admMesa.RegresaNombreCliente(numM).Equals("NO ASIGNADA"))
{
MessageBox.Show("MESA SIN ASIGNAR!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
//limpiar errorprovider
ErrorPPedido.SetError(cmbNumMesa, "");
ErrorPPedido.SetError(txtNumPe, "");
guardar = false;
}
//Falta validar que no deje guardar sin antes haber pedido un platillo, hay un error al quitar el platillo
int numPe = Convert.ToInt32(txtNumPe.Text);
if (lPLaPedidos.numPExiste(numPe) != true)
{
MessageBox.Show("NO HAY PLATILLOS AGREGADOS!,FAVOR DE AGREGAR", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
guardar = false;
}
if (guardar != false)
{
MessageBox.Show("Pedido Agregado Correctamente", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
//limpiar errorprovider
ErrorPPedido.SetError(cmbNumMesa, "");
ErrorPPedido.SetError(txtNumPe, "");
//limpiar al guardar
cmbNumMesa.Text = "";
txtNombrecliente.Text = "";
txtNumPe.Text = "";
dgvMesas.Rows.Clear();
txtNumPe.Enabled = true;
cmbNumMesa.Enabled = true;
cmbNumMesa.Focus();
}
}
}
}
private void cmbNumMesa_SelectedIndexChanged(object sender, EventArgs e)
{
dgvMesas.Rows.Clear();
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem.ToString());
string desc = admMesa.RegresaDescripcion(numM);
string estatus = admMesa.RegresaEstatus(numM);
string nombreC = admMesa.RegresaNombreCliente(numM);
int numP = admMesa.RegresaNumPersonas(numM);
txtNombrecliente.Text = nombreC;
dgvMesas.Rows.Add(numM, nombreC, desc, numP, estatus);
}
private void frmPedidos_Load(object sender, EventArgs e)
{
string[] arreglo = admMesa.NumeroDeMesas();
for (int i = 0; i < arreglo.Length; i++)
{
cmbNumMesa.Items.Add(arreglo[i]);
}
}
private void txtNumPe_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsControl(e.KeyChar)) && (!char.IsDigit(e.KeyChar)))
{
e.Handled = true;
}
}
public bool ValidarVacio()
{
bool retorno = true;
string Clave = cmbNumMesa.Text;
if (Clave.Equals(""))
{
ErrorPPedido.SetError(cmbNumMesa, "No Se Ha Seleccionado Ningun Numero De Mesa");
cmbNumMesa.Focus();
retorno = false;
}
return retorno;
}
public bool ValidarMESA()
{
bool retorno = true;
int NumM = Convert.ToInt32(cmbNumMesa.SelectedItem.ToString());
if (dPedidos.BuscaPedidoDeMESA(NumM))
{
ErrorPPedido.SetError(cmbNumMesa, "YA SE HA DADO DE ALTA EL PEDIDO DE ESA MESA, SELECCIONE OTRA");
cmbNumMesa.Focus();
retorno = false;
}
return retorno;
}
public bool ValidarVacioPedido()
{
bool retorno = true;
string NumPedido = txtNumPe.Text;
if (NumPedido.Equals(""))
{
ErrorPPedido.SetError(txtNumPe, "No Se Ha Proporcionado El Numero De Pedido");
txtNumPe.Focus();
retorno = false;
}
return retorno;
}
private void cmbNumMesa_Validating(object sender, CancelEventArgs e)
{
if (ValidarVacio() == false)
{
e.Cancel = true;
}
}
private void txtNumPe_Validating(object sender, CancelEventArgs e)
{
if (ValidarVacioPedido() == false)
{
e.Cancel = true;
}
}
private void cmbNumMesa_Validated(object sender, EventArgs e)
{
ErrorPPedido.SetError(cmbNumMesa, "");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
//Ejemplo de edicion
public class AdministraMesa
{
private Mesa[] aMesas;
private int contMesas = 0;
public AdministraMesa()
{
aMesas = new Mesa[10];
}
public bool AgregaMesas(string desc, int numPersonas)
{
bool agrega = false;
Mesa mesa = new Mesa(desc, numPersonas);
if (contMesas <= 9)
{
aMesas[contMesas] = mesa;
contMesas++;
agrega = true;
}
return agrega;
}
public int RegresaTamaño()
{
int tamaño = 0;
foreach(Mesa item in aMesas)
{
if(item!=null)
{
tamaño++;
}
}
return tamaño;
}
public void AsignaMesa(int posMesa, string nombreCliente)
{
aMesas[posMesa].pNombreCliente = nombreCliente;
aMesas[posMesa].pEstatus = false;
}
//nuevo
public string RegresaDescripcion(int numM)
{
string desc="";
for (int i = 0; i < contMesas; i++)
{
if (aMesas[i].pNumMesa.Equals(numM))
{
desc=aMesas[i].pDescripcion;
}
}
return desc;
}
public int RegresaNumPersonas(int numM)
{
int num = 0;
for (int i = 0; i < contMesas; i++)
{
if (aMesas[i].pNumMesa.Equals(numM))
{
num = aMesas[i].pNumPersonas;
}
}
return num;
}
public string RegresaEstatus(int numM)
{
string estatus = "DESOCUPADA";
for (int i = 0; i < contMesas; i++)
{
if (aMesas[i].pNumMesa.Equals(numM))
{
bool estado = aMesas[i].pEstatus;
if (estado==false)
{
estatus = "OCUPADA";
}
}
}
return estatus;
}
public string RegresaNombreCliente(int numM)
{
string nombre = "NO ASIGNADA";
for (int i = 0; i < contMesas; i++)
{
if (aMesas[i].pNumMesa.Equals(numM))
{
string nom = aMesas[i].pNombreCliente;
if (nom!=null)
{
nombre = nom;
}
}
}
return nombre;
}
public string[] NumeroDeMesas()
{
string[] arreglo = new string[contMesas];
for (int i = 0; i < contMesas; i++)
{
arreglo[i] = aMesas[i].pNumMesa.ToString();
}
return arreglo;
}
public string[] arregloDescripcion()
{
string[] arreglo = new string[contMesas];
for (int i = 0; i < contMesas; i++)
{
arreglo[i] = aMesas[i].pDescripcion;
}
return arreglo;
}
public string[] arregloNumPersonas()
{
string[] arreglo = new string[contMesas];
for (int i = 0; i < contMesas; i++)
{
arreglo[i] = aMesas[i].pNumPersonas.ToString();
}
return arreglo;
}
public string[] arregloEstatus()
{
string estatus;
bool estado;
string[] arreglo = new string[contMesas];
for (int i = 0; i < contMesas; i++)
{
estatus = "DESOCUPADA";
estado = aMesas[i].pEstatus;
if (estado == false)
{
estatus = "OCUPADA";
}
arreglo[i] = estatus;
}
return arreglo;
}
public string[] arregloNombreCliente()
{
string nombre;
string[] arreglo = new string[contMesas];
for (int i = 0; i < contMesas; i++)
{
nombre = "NO ASIGNADA";
string nom = aMesas[i].pNombreCliente;
if (nom != null)
{
nombre = nom;
}
arreglo[i] = nombre;
}
return arreglo;
}
//
public void LiberarMesa(int posMesa)
{
aMesas[posMesa].pNombreCliente = null;
aMesas[posMesa].pEstatus = true;
}
public string[] ReporteMesas()
{
string[] cadena = new string[aMesas.Length];
int pos = 0;
string estatus = "OCUPADA";
string cliente = "NO HAY CLIENTE ASIGNADO";
foreach (Mesa item in aMesas)
{
if (item != null)
{
if (item.pEstatus == true)
{
estatus = "DESOCUPADA";
}
if (item.pNombreCliente != null)
{
cliente = item.pNombreCliente;
}
cadena[pos] = "NUMERO DE MESA: " + item.pNumMesa + ", DESCRIPCION: " + item.pDescripcion + ", NUMERO DE PERSONAS: " + item.pNumPersonas + ", ESTATUS: " + estatus + ", CLIENTE: " + cliente;
pos++;
}
}
return cadena;
}
public string[] ReporteMesaOcupadas()
{
string[] cadena = new string[aMesas.Length];
int pos = 0;
string estatus = "OCUPADA";
foreach (Mesa item in aMesas)
{
if (item != null)
{
if (item.pEstatus == false)
{
cadena[pos] = "MESA:" + item.pNumMesa + " " + "ESTATUS: " + estatus;
pos++;
}
}
}
return cadena;
}
public string[] ReporteMesaDesocupadas()
{
string[] cadena = new string[aMesas.Length];
int pos = 0;
string estatus = "DESOCUPADA";
foreach (Mesa item in aMesas)
{
if (item != null)
{
if (item.pEstatus == true)
{
cadena[pos] = "MESA:" + item.pNumMesa + " " + "ESTATUS: " + estatus;
pos++;
}
}
}
return cadena;
}
public int BuscaMesa(int numMesa)
{
int pos = -1;
for (int i = 0; i < contMesas; i++)
{
if (aMesas[i].pNumMesa == numMesa)
{
pos = i;
}
}
return pos;
}
public bool ArregloVacio()
{
bool vacio = false;
if (aMesas[0] == null)
{
vacio = true;
}
return vacio;
}
public bool MesaDisponible(int posMesa)
{
bool disponibilidad = true;
if (aMesas[posMesa].pEstatus == false)
{
disponibilidad = false;
}
return disponibilidad;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmConsultaMesaIndividual : Form
{
AdministraMesa admMesa;
public frmConsultaMesaIndividual(AdministraMesa admM)
{
InitializeComponent();
admMesa = admM;
}
private void frmConsultaMesaIndividual_Load(object sender, EventArgs e)
{
string[] arreglo = admMesa.NumeroDeMesas();
for (int i = 0; i < arreglo.Length; i++)
{
cmbNumMesa.Items.Add(arreglo[i]);
}
}
private void cmbNumMesa_SelectedIndexChanged(object sender, EventArgs e)
{
lblNombre.Text = "Nombre del Cliente";
dgvMesas.Rows.Clear();
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem.ToString());
string desc = admMesa.RegresaDescripcion(numM);
string estatus = admMesa.RegresaEstatus(numM);
string nombreC = admMesa.RegresaNombreCliente(numM);
int numP = admMesa.RegresaNumPersonas(numM);
lblNombre.Text = nombreC;
dgvMesas.Rows.Add(numM, nombreC, desc, numP, estatus);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
class PlatilloPedido
{
private int numPedido, cantidad;
private int clavePlatillo;
public PlatilloPedido(int numP, int claveP, int cant)
{
numPedido = numP;
clavePlatillo = claveP;
cantidad = cant;
}
public int pNumP
{
get
{
return numPedido;
}
}
public int pClaveP
{
get
{
return clavePlatillo;
}
}
public int pCantidad
{
get
{
return cantidad;
}
set
{
cantidad = value;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmPagarCuenta : Form
{
ListPlatillos listPlatillos;
ListPlatillosPedidos lPLaPedidos;
DictionaryPedidos dPedidos;
AdministraMesa admMesa;
public frmPagarCuenta(ListPlatillos lPlatillos, DictionaryPedidos dP, ListPlatillosPedidos lPlaPe, AdministraMesa aM)
{
InitializeComponent();
listPlatillos = lPlatillos;
lPLaPedidos = lPlaPe;
admMesa = aM;
dPedidos = dP;
}
private void btnPagar_Click(object sender, EventArgs e)
{
}
private void frmPagarCuenta_Load(object sender, EventArgs e)
{
string[] numPedidos = dPedidos.arregloNumPedidos();
for (int i = 0; i < numPedidos.Length; i++)
{
cmbNumPe.Items.Add(numPedidos[i]);
}
}
private void cmbNumPe_SelectedIndexChanged(object sender, EventArgs e)
{
int NumPe = Convert.ToInt32(cmbNumPe.SelectedItem.ToString());
int numMesa = dPedidos.RegresaNumMesa(NumPe);
int numBebidas = dPedidos.RegresaNumBebibas(NumPe);
double importeBebidas = dPedidos.ImporteBebidas(NumPe);
int platillos = dPedidos.RegresaNumPla(NumPe);
double importePlatillos = dPedidos.ImportePlatillos(NumPe);
dgvPagarCuenta.Rows.Add(numMesa,numBebidas,importeBebidas,platillos,importePlatillos);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmPlatillos : Form
{
ListPlatillos listPlatillos;
public frmPlatillos(ListPlatillos Lpla)
{
InitializeComponent();
listPlatillos = Lpla;
txtClavePlatillo.Text = Platillo.ObtieneClave().ToString();
}
private void btnSalir_Click(object sender, EventArgs e)
{
this.Close();
}
private void txtClavePlatillo_TextChanged(object sender, EventArgs e)
{
}
private void btnRegistrar_Click(object sender, EventArgs e)
{
if (ValidarDescripcion())
{
if (ValidarImporte())
{
if (ValidarDuplicado())
{
string ClavePlatillo = txtClavePlatillo.Text;
string desc = txtDescripcion.Text;
double importe = Convert.ToDouble(txtImportePlatillo.Text);
int tiempo = Convert.ToInt32(numUpTiempo.Value);
listPlatillos.AgregaPlatillo(desc, importe, tiempo);
MessageBox.Show("Platillo Agregado Correctamente", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
//Limpiar ErrorProvider
ErrorPPlatillos.SetError(txtDescripcion, "");
ErrorPPlatillos.SetError(txtImportePlatillo, "");
DataGPlatillos.Rows.Clear();
string[] Aclave = listPlatillos.arregloClave();
string[] Adesc = listPlatillos.arregloDescripcion();
string[] Aimporte = listPlatillos.arregloImporte();
string[] Atiempo = listPlatillos.arregloTiempo();
for (int i = 0; i < Aclave.Length; i++)
{
DataGPlatillos.Rows.Add(Aclave[i], Adesc[i], Aimporte[i], Atiempo[i]);
}
//Limpiar Al Registrar
txtDescripcion.Text = "";
txtImportePlatillo.Text = "0";
numUpTiempo.Value = 10;
txtClavePlatillo.Text = Platillo.ObtieneClave().ToString();
txtDescripcion.Focus();
}
}
}
}
public bool ValidarDescripcion()
{
bool retorno = true;
string descripcion = txtDescripcion.Text;
if (descripcion.Equals(""))
{
ErrorPPlatillos.SetError(txtDescripcion, "Descripcion en blanco");
txtDescripcion.Focus();
retorno = false;
}
return retorno;
}
public bool ValidarDuplicado()
{
bool duplicado = true;
string desc = txtDescripcion.Text;
if (listPlatillos.ValidarPlatilloDesc(desc) != false)
{
ErrorPPlatillos.SetError(txtDescripcion, "Nombre De Platillo Repetido");
txtDescripcion.Focus();
duplicado = false;
}
return duplicado;
}
public bool ValidarImporte()
{
bool retorno = true;
int importe = Convert.ToInt32(txtImportePlatillo.Text.ToString());
if (importe.Equals(0))
{
ErrorPPlatillos.SetError(txtImportePlatillo, "IMPORTE INVALIDO");
txtImportePlatillo.Focus();
retorno = false;
}
return retorno;
}
private void txtDescripcion_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsWhiteSpace(e.KeyChar)) && !(char.IsLetter(e.KeyChar)) && !(char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}
private void txtImportePlatillo_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsControl(e.KeyChar)) && (!char.IsDigit(e.KeyChar)))
{
e.Handled = true;
}
}
private void txtDescripcion_Validating(object sender, CancelEventArgs e)
{
if (ValidarDescripcion() == false)
{
e.Cancel = true;
}
}
private void txtImportePlatillo_Validating(object sender, CancelEventArgs e)
{
if (ValidarImporte() == false)
{
e.Cancel = true;
}
}
private void frmPlatillos_Load(object sender, EventArgs e)
{
string[] Aclave = listPlatillos.arregloClave();
string[] Adesc = listPlatillos.arregloDescripcion();
string[] Aimporte = listPlatillos.arregloImporte();
string[] Atiempo = listPlatillos.arregloTiempo();
for (int i = 0; i < Aclave.Length; i++)
{
DataGPlatillos.Rows.Add(Aclave[i], Adesc[i], Aimporte[i], Atiempo[i]);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmAsignaMesa : Form
{
AdministraMesa admMesa;
public frmAsignaMesa(AdministraMesa admM)
{
InitializeComponent();
admMesa = admM;
}
private void frmAsignaMesa_Load(object sender, EventArgs e)
{
string[] arreglo = admMesa.NumeroDeMesas();
for (int i = 0; i < arreglo.Length; i++)
{
cmbNumMesa.Items.Add(arreglo[i]);
}
}
private void cmbNumMesa_SelectedIndexChanged(object sender, EventArgs e)
{
dgvMesas.Rows.Clear();
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem.ToString());
string desc = admMesa.RegresaDescripcion(numM);
string estatus = admMesa.RegresaEstatus(numM);
string nombreC = admMesa.RegresaNombreCliente(numM);
int numP = admMesa.RegresaNumPersonas(numM);
dgvMesas.Rows.Add(numM, nombreC, desc, numP, estatus);
}
private void btnAsignar_Click(object sender, EventArgs e)
{
if (ValidarVacio())
{
if (ValidarEstatus())
{
if (ValidarNombre())
{
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem.ToString());
string nombreC = txtNombreCliente.Text.ToString();
int pos = admMesa.BuscaMesa(numM);
admMesa.AsignaMesa(pos, nombreC);
MessageBox.Show("Mesa Asignada a " + nombreC, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
errorpAsignaMesa.SetError(cmbNumMesa, "");
cmbNumMesa.Text = "";
txtNombreCliente.Text = "";
cmbNumMesa.Focus();
dgvMesas.Rows.Clear();
}
}
}
}
private void txtNombreCliente_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsWhiteSpace(e.KeyChar)) && !(char.IsLetter(e.KeyChar)) && !(char.IsControl(e.KeyChar)))
{
e.Handled = true;
}
}
public bool ValidarNombre()
{
bool retorno = false;
if (txtNombreCliente.Text != "")
{
retorno = true;
}
return retorno;
}
public bool ValidarVacio()
{
bool retorno = true;
string Clave = cmbNumMesa.Text;
if (Clave.Equals(""))
{
errorpAsignaMesa.SetError(cmbNumMesa, "No Se Ha Seleccionado Ningun Numero De Mesa");
cmbNumMesa.Focus();
retorno = false;
}
return retorno;
}
public bool ValidarEstatus()
{
bool estatus = true;
int numM = Convert.ToInt32(cmbNumMesa.SelectedItem.ToString());
if (admMesa.RegresaEstatus(numM) == "OCUPADA")
{
MessageBox.Show("Estatus: OCUPADA", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
estatus = false;
}
return estatus;
}
private void txtNombreCliente_Validating(object sender, CancelEventArgs e)
{
if (txtNombreCliente.Text == "")
{
errorpAsignaMesa.SetError(txtNombreCliente, "No puede dejar este espacio en blanco");
txtNombreCliente.Focus();
}
else
{
errorpAsignaMesa.SetError(txtNombreCliente, "");
}
}
private void cmbNumMesa_Validating(object sender, CancelEventArgs e)
{
if (ValidarVacio() == false)
{
e.Cancel = true;
}
}
private void cmbNumMesa_Validated(object sender, EventArgs e)
{
errorpAsignaMesa.SetError(cmbNumMesa, "");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
public class DictionaryPedidos
{
private Dictionary<int, Pedido> DicPedidos;
private ListPlatillosPedidos lp;
public DictionaryPedidos(ListPlatillosPedidos lPlaPe)
{
DicPedidos = new Dictionary<int, Pedido>();
lp = lPlaPe;
}
public void AgregaPedido(int numPe, int numM, int numbe)
{
Pedido p = new Pedido(numM, numbe);
DicPedidos.Add(numPe, p);
}
public string[] ReportePedidos()
{
int pos = 0;
string[] cadena = new string[DicPedidos.Count];
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
string arr = String.Format("NUMERO PEDIDO: {0}, NUMERO DE MESA: {1}, BEBIDAS: {2}, PLATILLOS: {3}",
numP, p.pNumMesa, p.pnumBebidas, p.pNumPlatillos);
cadena[pos] = arr;
pos++;
}
return cadena;
}
public string[] arregloNumPedidos()
{
int pos = 0;
string[] cadena = new string[DicPedidos.Count];
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
string arr = numP.ToString();
cadena[pos] = arr;
pos++;
}
return cadena;
}
public string[] arregloNumMesa()
{
int pos = 0;
string[] cadena = new string[DicPedidos.Count];
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
string arr = p.pNumMesa.ToString();
cadena[pos] = arr;
pos++;
}
return cadena;
}
public string[] arregloNumBebidas()
{
int pos = 0;
string[] cadena = new string[DicPedidos.Count];
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
string arr = p.pnumBebidas.ToString();
cadena[pos] = arr;
pos++;
}
return cadena;
}
public string[] arregloNumPlatillos()
{
int pos = 0;
string[] cadena = new string[DicPedidos.Count];
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
string arr = p.pNumPlatillos.ToString();
cadena[pos] = arr;
pos++;
}
return cadena;
}
public int RegresaNumMesa(int numPed)
{
int numPedido = 0;
Pedido p;
int numM = 0;
for (int i = 0; i < DicPedidos.Count; i++)
{
KeyValuePair<int, Pedido> dato = DicPedidos.ElementAt(i);
numPedido = dato.Key;
p = dato.Value;
if (numPedido == numPed)
{
numM = p.pNumMesa;
}
}
return numM;
}
public int RegresaNumBebibas(int numPed)
{
int numPedido = 0;
Pedido p;
int numB = 0;
for (int i = 0; i < DicPedidos.Count; i++)
{
KeyValuePair<int, Pedido> dato = DicPedidos.ElementAt(i);
numPedido = dato.Key;
p = dato.Value;
if (numPedido == numPed)
{
numB = p.pnumBebidas;
}
}
return numB;
}
public int RegresaNumPla(int numPed)
{
int numPedido = 0;
Pedido p;
int numPla = 0;
for (int i = 0; i < DicPedidos.Count; i++)
{
KeyValuePair<int, Pedido> dato = DicPedidos.ElementAt(i);
numPedido = dato.Key;
p = dato.Value;
if (numPedido == numPed)
{
numPla = p.pNumPlatillos;
}
}
return numPla;
}
public bool BuscaPedido(int num)
{
bool existe = false;
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
if (numP == num)
{
existe = true;
}
}
return existe;
}
public bool BuscaPedidoDeMESA(int numM)
{
bool existe = false;
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numMesa = item.Value.pNumMesa;
if (numM.Equals(numMesa))
{
existe = true;
}
}
return existe;
}
public void ActualizaPedido (int numPed)
{
int numP = 0;
Pedido p;
int cantidad = 0;
for (int i = 0; i < DicPedidos.Count; i++)
{
KeyValuePair<int, Pedido> dato = DicPedidos.ElementAt(i);
numP = dato.Key;
p = dato.Value;
if (numP == numPed)
{
cantidad = lp.CalcularNumPlatillos(numP);
p.pNumPlatillos = cantidad;
break;
}
}
}
public double ImporteBebidas(int numPe)
{
double importeBe = 0;
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
if (numP == numPe)
{
importeBe = p.pnumBebidas * 23;
break;
}
}
return importeBe;
}
public double ImportePlatillos(int numPe)
{
double importe = 0;
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
if (numP == numPe)
{
importe = lp.ImportePlatillos(numP);
}
}
return importe;
}
public double ImporteTotal(int numPe, bool descuento)
{
double importeT = 0;
double desc = 0;
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numP = item.Key;
Pedido p = item.Value;
if (numP == numPe)
{
importeT = this.ImporteBebidas(numPe) + this.ImportePlatillos(numPe);
if (descuento)
{
desc = importeT * .10;
importeT -= desc;
}
}
}
return importeT;
}
public bool DicVacio()
{
bool vacio = false;
if (DicPedidos.Count() == 0)
{
vacio = true;
}
return vacio;
}
public void BorrarPedido(int numP)
{
for (int i = 0; i < DicPedidos.Count; i++)
{
if (DicPedidos.ElementAt(i).Key.Equals(numP))
{
KeyValuePair<int, Pedido> dato = DicPedidos.ElementAt(i);
DicPedidos.Remove(dato.Key);
}
}
}
public int PedidoMesa(int numP)
{
int numM = 0;
foreach (KeyValuePair<int, Pedido> item in DicPedidos)
{
int numPe = item.Key;
Pedido p = item.Value;
if (numPe == numP)
{
numM = p.pNumMesa;
break;
}
}
return numM;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsProyectoRestaurante
{
public class ListPlatillosPedidos
{
private List<PlatilloPedido> lPlatillosPedidos;
private ListPlatillos lPlatillos;
public ListPlatillosPedidos(ListPlatillos lpla)
{
lPlatillosPedidos = new List<PlatilloPedido>();
lPlatillos = lpla;
}
public void Agrega(int numP, int claveP, int cant)
{
PlatilloPedido pp = new PlatilloPedido(numP, claveP, cant);
lPlatillosPedidos.Add(pp);
}
public void AgregarPlatillo(int numP, int claveP, int cant)
{
if (lPlatillosPedidos.Count != 0)
{
for (int i = 0; i < lPlatillosPedidos.Count; i++)
{
if (lPlatillosPedidos.ElementAt(i).pNumP.Equals(numP))
{
if (lPlatillosPedidos.ElementAt(i).pClaveP.Equals(claveP))
{
lPlatillosPedidos.ElementAt(i).pCantidad += cant;
break;
}
else
{
Agrega(numP, claveP, cant);
break;
}
}
}
Agrega(numP, claveP, cant);
}
else
{
Agrega(numP, claveP, cant);
}
}
public void QuitarPlatillo(int numP, int claveP)
{
if (lPlatillosPedidos.Count != 0)
{
for (int i = 0; i < lPlatillosPedidos.Count; i++)
{
if (lPlatillosPedidos.ElementAt(i).pNumP.Equals(numP) & lPlatillosPedidos.ElementAt(i).pClaveP.Equals(claveP))
if (lPlatillosPedidos.ElementAt(i).pCantidad == 1)
{
lPlatillosPedidos.RemoveAt(i);
}
else
{
lPlatillosPedidos.ElementAt(i).pCantidad -= 1;
}
}
}
}
public int CalcularNumPlatillos(int numPe)
{
int cont = 0;
for (int i = 0; i < lPlatillosPedidos.Count; i++)
{
if (lPlatillosPedidos.ElementAt(i).pNumP.Equals(numPe))
{
cont+=lPlatillosPedidos.ElementAt(i).pCantidad;
}
}
return cont;
}
public double ImportePlatillos(int numPe)
{
double total = 0;
for (int i = 0; i < lPlatillosPedidos.Count; i++)
{
if (lPlatillosPedidos.ElementAt(i).pNumP == numPe)
{
int clave = lPlatillosPedidos.ElementAt(i).pClaveP;
double importe = lPlatillos.Importe(clave);
total += lPlatillosPedidos.ElementAt(i).pCantidad * importe;
}
}
return total;
}
public string[] ReportePlatillos()
{
string[] cadena = new string[lPlatillosPedidos.Count];
for (int i = 0; i < lPlatillosPedidos.Count; i++)
{
cadena[i] = "NUMERO DE PEDIDO: " + lPlatillosPedidos[i].pNumP + ", CLAVE PLATILLO: " + lPlatillosPedidos[i].pClaveP + ", CANTIDAD: " + lPlatillosPedidos[i].pCantidad;
}
return cadena;
}
public void BorrarPlatillos(int numP)
{
for (int i = 0; i < lPlatillosPedidos.Count; i++)
{
if (lPlatillosPedidos.ElementAt(i).pNumP.Equals(numP))
{
lPlatillosPedidos.RemoveAt(i);
}
}
}
public int[] RetornaNumPedidos()
{
int[] ArreglonumP = new int[lPlatillosPedidos.Count];
int pos= 0;
foreach(PlatilloPedido item in lPlatillosPedidos)
{
if(item!=null)
{
ArreglonumP[pos] = item.pNumP;
pos++;
}
}
return ArreglonumP;
}
public int[] RetornaClavesP()
{
int[] ArregloClavesP = new int[lPlatillosPedidos.Count];
int pos = 0;
foreach (PlatilloPedido item in lPlatillosPedidos)
{
if (item != null)
{
ArregloClavesP[pos] = item.pClaveP;
pos++;
}
}
return ArregloClavesP;
}
public int[] RetornaCant()
{
int[] ArregloCantidad = new int[lPlatillosPedidos.Count];
int pos = 0;
foreach (PlatilloPedido item in lPlatillosPedidos)
{
if (item != null)
{
ArregloCantidad[pos] = item.pCantidad;
pos++;
}
}
return ArregloCantidad;
}
public bool ListVacio()
{
bool vacio = false;
if (lPlatillosPedidos.Count() == 0)
{
vacio = true;
}
return vacio;
}
public bool numPExiste(int numP)
{
bool existe = false;
foreach(PlatilloPedido item in lPlatillosPedidos)
{
if (item != null)
{
if (item.pNumP.Equals(numP))
{
existe = true;
}
}
}
return existe;
}
public string[] RegresaPlatilloDescripcion(int numP)
{
int numPlatillos = this.CalcularNumPlatillos(numP);
int[] claves = this.RetornaClavesP();
string[] cadena = new string[numPlatillos];
int pos = 0;
string desc = "";
int clavePla = 0, cant = 0;
for (int j = 0; j < lPlatillosPedidos.Count; j++)
{
if (lPlatillosPedidos.ElementAt(j).pNumP == numP)
{
clavePla = lPlatillosPedidos.ElementAt(j).pClaveP;
cant = lPlatillosPedidos.ElementAt(j).pCantidad;
for (int k = 0; k < claves.Length; k++)
{
if (clavePla == claves[k])
{
desc = lPlatillos.RegresaDescripcion(claves[k]);
for (int l = 0; l < cant; l++)
{
cadena[pos] = desc;
pos++;
}
break;
}
}
}
}
return cadena;
}
public string[] RegresaPlatilloImporte(int numP)
{
int numPlatillos = this.CalcularNumPlatillos(numP);
int[] claves = this.RetornaClavesP();
string[] cadena = new string[numPlatillos];
int pos = 0;
double importe = 0;
int clavePla = 0, cant = 0;
for (int j = 0; j < lPlatillosPedidos.Count; j++)
{
if (lPlatillosPedidos.ElementAt(j).pNumP == numP)
{
clavePla = lPlatillosPedidos.ElementAt(j).pClaveP;
cant = lPlatillosPedidos.ElementAt(j).pCantidad;
for (int k = 0; k < claves.Length; k++)
{
if (clavePla == claves[k])
{
importe = lPlatillos.RegresaImporte(claves[k]);
for (int l = 0; l < cant; l++)
{
cadena[pos] = importe.ToString();
pos++;
}
break;
}
}
}
}
return cadena;
}
public string[] RegresaPlatilloTiempo(int numP)
{
int numPlatillos = this.CalcularNumPlatillos(numP);
int[] claves = this.RetornaClavesP();
string[] cadena = new string[numPlatillos];
int pos = 0;
int clavePla = 0, cant = 0, tiempo = 0;
for (int j = 0; j < lPlatillosPedidos.Count; j++)
{
if (lPlatillosPedidos.ElementAt(j).pNumP == numP)
{
clavePla = lPlatillosPedidos.ElementAt(j).pClaveP;
cant = lPlatillosPedidos.ElementAt(j).pCantidad;
for (int k = 0; k < claves.Length; k++)
{
if (clavePla == claves[k])
{
tiempo = lPlatillos.RegresaTiempo(claves[k]);
for (int l = 0; l < cant; l++)
{
cadena[pos] = tiempo.ToString();
pos++;
}
break;
}
}
}
}
return cadena;
}
public string[] RegresaPlatilloClaves(int numP)
{
int numPlatillos = this.CalcularNumPlatillos(numP);
int[] claves = this.RetornaClavesP();
string[] cadena = new string[numPlatillos];
int pos = 0;
int clavePla = 0, cant = 0;
for (int j = 0; j < lPlatillosPedidos.Count; j++)
{
if (lPlatillosPedidos.ElementAt(j).pNumP==numP)
{
clavePla = lPlatillosPedidos.ElementAt(j).pClaveP;
cant = lPlatillosPedidos.ElementAt(j).pCantidad;
for (int k = 0; k < claves.Length; k++)
{
if (clavePla == claves[k])
{
for (int l = 0; l < cant; l++)
{
cadena[pos] = clavePla.ToString();
pos++;
}
break;
}
}
}
}
return cadena;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsProyectoRestaurante
{
public partial class frmConsultaPlatillos : Form
{
ListPlatillos listPlatillos;
public frmConsultaPlatillos(ListPlatillos lPlatillos)
{
InitializeComponent();
listPlatillos = lPlatillos;
}
private void frmConsultaPlatillos_Load(object sender, EventArgs e)
{
string[] clave = listPlatillos.arregloClave();
string[] desc = listPlatillos.arregloDescripcion();
string[] importe = listPlatillos.arregloImporte();
string[] tiempo = listPlatillos.arregloTiempo();
for (int i = 0; i < clave.Length; i++)
{
dgvConsultaPlatillos.Rows.Add(clave[i], desc[i], importe[i], tiempo[i]);
}
}
}
}
| d5da3edbeb2222817586d6b7ceeff57ee6e8332d | [
"C#"
] | 23 | C# | lalberto08/WindowsFormsProyectoRestaurante | 75060e940a3e2ff7a637d0c6d200d8c633a966fe | 789979ed15ea9591d98e2d010d58b13252194724 |
refs/heads/master | <file_sep>
public class Queue {
ObjectBox head;
ObjectBox tail;
int count;
public void push(Object obj) {
ObjectBox ob = new ObjectBox();
ob.obj = obj;
if (head == null) {
head = ob;
} else {
tail.next = ob;
}
tail = ob;
count++;
}
public Object pull() {
Object obj;
//ObjectBox ob1;
obj = head.obj;
//System.out.println("Что лежит дальше "+head.next.obj);
head = head.next;
//head = ob1;
count--;
return obj;
}
public int get_size() {
return count;
}
}
| e50753760d215fcfa9fb1fcd9ad869613986d154 | [
"Java"
] | 1 | Java | imrche/all_stud_projects | 149c3784cd4e4c7d4e9ebfa5084dedf97f87a41c | 7f10fa14759a741332f800ebdffb62dbeaa6e1dc |
refs/heads/master | <repo_name>hipposareevil/postgrescli<file_sep>/README.md
# postgrescli
Tiny postgresql cli. Run 'psql' against some remote DB
# Docker build
```
docker build -t hipposareevil/postgrescli .
```
# Usage
```
docker run -it\
-e POSTGRESQL_PASSWORD=<PASSWORD> \
-e POSTGRESQL_USERNAME=USER \
-e POSTGRESQL_DATABASE=awesomedb \
-e POSTGRESQL_HOST=some_url \
hipposareevil/postgrescli
```
<file_sep>/Dockerfile
FROM docker.io/bitnami/postgresql:10.9.0
COPY entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]
<file_sep>/entrypoint.sh
#!/bin/bash
export PGPASSWORD="$<PASSWORD>"
# run
/opt/bitnami/postgresql/bin/psql \
-U $POSTGRESQL_USERNAME \
-d $POSTGRESQL_DATABASE \
--host $POSTGRESQL_HOST
| 930246c39a5eec964783b32906d50361cbd20ce2 | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Markdown | hipposareevil/postgrescli | 9ea3a77823837732e9837beeb69d3652a264ee69 | a8f4f65faa8184fb725d11c5dfb42617424bd58e |
refs/heads/master | <repo_name>lopomaster/job_board<file_sep>/config/routes.rb
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
devise_for :users, controllers: { sessions: 'api/v1/sessions', registrations: 'api/v1/registrations' }
resources :users, except: [:edit, :new, :show] do
get :subscribe_to_advert
end
get 'user/:username', to: 'users#show', as: :username
resources :job_adverts, except: :index do
get :my_adverts_as_candidate, on: :collection
get :my_adverts_as_company, on: :collection
get :list_adverts, on: :collection
end
resources :job_subscriptions, except: :index do
get :my_subscriptions_as_candidate, on: :collection
get :my_subscriptions_as_company, on: :collection
end
end
end
# todo Web app
root to: 'home#index'
devise_for :users, controllers: {sessions: 'users/sessions', registrations: 'users/registrations'}
match "*path", to: "api/v1/application#routing_error", via: :all
end<file_sep>/spec/support/shoulda_matchers.rb
Shoulda::Matchers.configure do |sm|
sm.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
<file_sep>/app/serializers/candidate_serializer.rb
class CandidateSerializer < ApplicationSerializer
attributes :type, :profession, :notes
has_one :user
end<file_sep>/app/models/candidate.rb
class Candidate < ApplicationRecord
has_one :user, as: :profile, dependent: :destroy, inverse_of: :profile
has_many :job_subscriptions
has_and_belongs_to_many :subscription_job_adverts, class_name: 'JobAdvert', join_table: :job_subscriptions
validates_presence_of :profession
end<file_sep>/app/models/job_subscription.rb
class JobSubscription < ApplicationRecord
belongs_to :job_advert
belongs_to :candidate
has_one :company, through: :job_advert
validates_presence_of :job_advert, :candidate, :subscription_status_cd
validates_uniqueness_of :candidate, scope: :job_advert_id
as_enum :subscription_status, { reject: 0, highlight: 1, hire: 2, pending: 3 }
end
<file_sep>/spec/api/v1/registrations_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V1::RegistrationsController, type: :request do
# initialize test data
let(:user_candidate_params) {
{ user: { email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", username: "lopomaster", first_name: "fn", last_name: "ln", profile_type: "Candidate", profile_attributes: { profession: "RoR Programmer", notes: "notes"} }
}.to_json
}
let(:user_company_params) {
{ user: { email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", username: "lopomaster_company", first_name: "fn", last_name: "ln", profile_type: "Company", profile_attributes: { name: "RoR Programmer", description: "notes"} }
}.to_json
}
let(:invalid_user_params) { {"user": {"username": 'username', "password": '<PASSWORD>' }}.to_json }
describe 'GET /api/v1/users/sign_up/' do
context 'Create an user as Candidate -> returns status code 200' do
it 'returns 200' do
expect{ post "/api/v1/users", params: user_candidate_params, headers: { 'Content-Type' => 'application/json' } }.to change(User, :count).by(1)
expect(response).to have_http_status(200)
expect(User.count).to eq(1)
expect(User.first.profile_type).to eq('Candidate')
end
end
context 'Create an user as Company -> returns status code 200' do
it 'returns 200' do
expect{ post "/api/v1/users", params: user_company_params, headers: { 'Content-Type' => 'application/json' } }.to change(User, :count).by(1)
expect(response).to have_http_status(200)
expect(User.count).to eq(1)
expect(User.first.profile_type).to eq('Company')
end
end
context 'when params is invalid' do
it 'returns status code 200 and token nil' do
expect{ post "/api/v1/users", params: invalid_user_params, headers: { 'Content-Type' => 'application/json' } }.to change(User, :count).by(0)
expect(response).to have_http_status(400)
end
end
end
end<file_sep>/spec/models/job_subscription_spec.rb
require 'rails_helper'
RSpec.describe JobSubscription, type: :model do
it { should belong_to :job_advert }
it { should belong_to :candidate }
it { should have_one :company }
it { should validate_presence_of :job_advert }
it { should validate_presence_of :candidate }
it { should validate_presence_of :subscription_status_cd }
it "validates uniqueness of candidate scoped to job_advert" do
company = create(:user, :as_company)
candidate = create(:user, :as_candidate)
job_advert = create :job_advert, company: company.profile
expect( create( :job_subscription, candidate: candidate.profile, job_advert: job_advert ) ).to be_valid
expect( build( :job_subscription, candidate: candidate.profile, job_advert: job_advert ) ).to_not be_valid
end
it { should respond_to(:candidate) }
it { should respond_to(:job_advert) }
it { should respond_to(:subscription_status) }
end
<file_sep>/app/controllers/api/v1/job_subscriptions_controller.rb
class Api::V1::JobSubscriptionsController < Api::V1::ApplicationController
before_action :set_job_subscription, only: [:show, :update]
load_and_authorize_resource :job_subscription
respond_to :json
def show
render json: @job_subscription, status: :ok
end
# Listing subscriptions as candidate
def my_subscriptions_as_candidate
authorize! :index, JobSubscription.new
@q = current_user.profile.job_subscriptions.ransack(params[:q])
@job_subscriptions = @q.result.page( params[:page] ).per(@per_page)
render json: @job_subscriptions, each_serializer: JobSubscriptionSerializer,
serializer: ActiveModel::Serializer::CollectionSerializer
end
# Create a subscription to job_advert as candidate
def create
@job_subscription = new_instance(job_subscription_params)
@job_subscription.save
render_resource @job_subscription
end
# Update status of a subscription
def update
@job_subscription.update(job_subscription_update_params)
render_resource @job_subscription
end
private
def set_job_subscription
@job_subscription = JobSubscription.find(params[:id])
render json: ApiMessage.not_found, status: :not_found if @job_subscription.blank?
end
def job_subscription_params
params.require(:job_subscription).permit(:candidate_id, :company_id)
end
def job_subscription_update_params
params.require(:job_subscription).permit(:subscription_status)
end
def new_instance build_params = {}
@job_subscription = current_user.profile.job_subscriptions.build build_params
end
end<file_sep>/db/migrate/20190614203215_create_tables.rb
class CreateTables < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.references :profile, polymorphic: true, null: false
## Database authenticatable
t.string :email, null: false, default: ""
t.string :username, null: false
t.string :first_name
t.string :last_name
t.string :encrypted_password, null: false, default: ""
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :username, unique: true
create_table :job_adverts do |t|
t.belongs_to :company, null: false, foreign_key: true
t.text :description
t.timestamps
end
create_table :job_subscriptions do |t|
t.belongs_to :candidate, null: false, foreign_key: true
t.belongs_to :job_advert, null: false, foreign_key: true
t.integer :subscription_status_cd, default: 0
t.timestamps
end
add_index :job_subscriptions, [:company_id, :candidate_id ], :unique => true
create_table :companies do |t|
t.string :name
t.text :description
t.timestamps
end
add_index :companies, :name, unique: true
create_table :candidates do |t|
t.string :profession
t.string :notes
t.timestamps
end
end
def self.down
raise ActiveRecord::IrreversibleMigration
end
end
<file_sep>/app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
if user.present?
can :update, User do |user_element|
user_element.id == user.id
end
can :read, User do
true
end
# Adverts
can :update, JobAdvert do |job_advert|
job_advert.company_id == user.id and user.profile_type == 'Company'
end
can :create, JobAdvert do
user.profile_type == 'Company'
end
can :my_adverts_as_company, JobAdvert do
user.profile_type == 'Company'
end
can :my_adverts_as_candidate, JobAdvert do
user.profile_type == 'Candidate'
end
can [:list_adverts, :read], JobAdvert do
true
end
#Subscriptions
can :manage, JobSubscription do |job_subscription|
user.profile_type == 'Company' and job_subscription.job_advert.company_id == user.id
end
can :create, JobSubscription do |job_subscription|
user.profile_type == 'Candidate' and job_subscription.candidate_id = user.id
end
can :index, JobSubscription do |job_subscription|
user.profile_type == 'Candidate'
end
end
end
end
<file_sep>/app/controllers/api/v1/application_controller.rb
class Api::V1::ApplicationController < ActionController::API
include ApplicationHelper
include ExceptionHandler
include AuthorizeRequest
include Response
before_action :authorize_request
before_action :set_default_per_page, only: :index
before_action :configure_permitted_parameters, if: :devise_controller?
def routing_error
not_found ApiMessage.invalid_route
end
private
def set_default_per_page
@per_page = params[:per_page] || 10
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
end
end
<file_sep>/app/controllers/api/v1/companies_controller.rb
class Api::V1::CompaniesController < Api::V1::ApplicationController
def new_company
@user = User.new(profile: Company.new)
end
end
<file_sep>/spec/support/controller_spec_helper.rb
module ControllerSpecHelper
require 'devise/jwt/test_helpers'
# return valid headers
def valid_headers(user)
header = { 'Accept' => 'application/json', 'Content-Type' => 'application/json' }
Devise::JWT::TestHelpers.auth_headers(header, user)
end
# return valid token
def valid_token(user)
header = { 'Accept' => 'application/json', 'Content-Type' => 'application/json' }
header = Devise::JWT::TestHelpers.auth_headers(header, user)
header['Authorization']
end
# return invalid headers
def invalid_headers
{
"Authorization" => nil,
"Content-Type" => "application/json"
}
end
# return invalid headers
def invalid_headers_token
{
"Authorization" => invalid_token,
"Content-Type" => "application/json"
}
end
def invalid_token
'fake_token.fake_token.fake_token'
end
end<file_sep>/app/controllers/api/v1/sessions_controller.rb
class Api::V1::SessionsController < Devise::SessionsController
include Devise::Controllers::Helpers
skip_before_action :verify_authenticity_token
prepend_before_action :require_no_authentication, only: :create
before_action :rewrite_param_names, only: :create
respond_to :json
def new
render json: Message.missing_token, status: 401
end
def create
user = User.find_by_username(params.dig(:session, :user, :username))
resource = warden.authenticate(:scope => :user)
yield resource if block_given?
if user and current_token
sign_in(resource_name, resource)
render json: {success: true, jwt: current_token, message: "Authentication successful" }, status: :ok
else
render json: {success: false, jwt: nil, message: "Authentication failed", code: 'AF' }, status: :unauthorized
end
end
private
def rewrite_param_names
request.params[:user] = {username: request.params[:username], password: request.params[:password]}
end
def current_token
request.env['warden-jwt_auth.token']
end
end<file_sep>/app/serializers/user_serializer.rb
class UserSerializer < ApplicationSerializer
attributes :username, :first_name, :last_name, :email
belongs_to :profile
end<file_sep>/app/serializers/job_advert_serializer.rb
class JobAdvertSerializer < ApplicationSerializer
attributes :description, :id
has_one :company
end<file_sep>/app/serializers/company_serializer.rb
class CompanySerializer < ApplicationSerializer
attributes :type, :name, :description
has_one :user
end<file_sep>/spec/factories/candidates.rb
FactoryBot.define do
factory :candidate do
profession { Faker::Movies::StarWars.planet }
notes { Faker::Lorem.paragraph }
end
end
<file_sep>/app/controllers/concerns/exception_handler.rb
module ExceptionHandler
extend ActiveSupport::Concern
# Define custom error subclasses - rescue catches `StandardErrors`
class AuthenticationError < StandardError; end
class MissingToken < StandardError; end
class InvalidToken < StandardError; end
included do
# Define custom handlers
rescue_from StandardError do |e|
error message: e.message, code: 'OT'
end
rescue_from ActiveRecord::RecordInvalid do |e|
error ApiMessage.unprocessable_entity
end
rescue_from ExceptionHandler::AuthenticationError do |e|
unauthorized ApiMessage.unprocessable_entity
end
rescue_from ExceptionHandler::MissingToken do |e|
unauthorized ApiMessage.missing_token
end
rescue_from ExceptionHandler::InvalidToken do |e|
unauthorized ApiMessage.invalid_token
end
rescue_from JWT::VerificationError do |e|
unauthorized ApiMessage.verification_error
end
rescue_from JWT::ExpiredSignature do |e|
unauthorized ApiMessage.unauthorized
end
rescue_from JWT::DecodeError do |e|
unauthorized ApiMessage.unauthorized
end
rescue_from ActiveRecord::RecordNotFound do |e|
not_found ApiMessage.not_found
end
rescue_from CanCan::AccessDenied do |e|
not_found ApiMessage.access_denied
end
end
private
def unauthorized message
json_response({ message: message }, :unauthorized)
end
def error message
json_response({ message: message }, :error)
end
def not_found message
json_response({ message: message }, :not_found)
end
end<file_sep>/app/models/job_advert.rb
class JobAdvert < ApplicationRecord
belongs_to :company
has_many :job_subscriptions
has_and_belongs_to_many :subscription_job_adverts, class_name: 'Candidate', join_table: :job_subscriptions
validates_presence_of :description
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
PROFILE_TYPES = [Candidate, Company]
include Devise::Models::DatabaseAuthenticatable
devise :database_authenticatable, :trackable, :validatable, :registerable,
:jwt_authenticatable, jwt_revocation_strategy: Devise::JWT::RevocationStrategies::Null
belongs_to :profile, polymorphic: true, dependent: :destroy, required: true
validates_uniqueness_of :username, :email
validates_format_of :email, :with => Devise::email_regexp
validates_presence_of :username, :first_name, :last_name, :email
accepts_nested_attributes_for :profile, reject_if: :all_blank, allow_destroy: false
def build_profile(params, profile_type)
raise "Unknown profile_type: #{profile_type}" unless PROFILE_TYPES.include?(profile_type)
self.profile = profile_type.new(params)
end
end
<file_sep>/app/serializers/job_subscription_serializer.rb
class JobSubscriptionSerializer < ApplicationSerializer
attributes :subscription_status, :created_at
has_one :job_advert
has_one :candidate
def subscription_status
translate_enum self.object, :subscription_status
end
end<file_sep>/spec/models/company_spec.rb
require 'rails_helper'
RSpec.describe Company, type: :model do
it { should have_one :user }
it { should have_many :job_adverts }
it { should validate_presence_of :description }
it { should validate_presence_of :name }
it { should respond_to(:name) }
it { should respond_to(:description) }
end
<file_sep>/spec/factories/users.rb
require 'securerandom'
require '<PASSWORD>'
FactoryBot.define do
factory :user do
username { Faker::Name.unique.name }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
email { Faker::Internet.unique.email }
password { <PASSWORD> }
password_confirmation { <PASSWORD> }
encrypted_password { <PASSWORD>(password) }
trait :as_candidate do
association :profile, factory: :candidate
end
trait :as_company do
association :profile, factory: :company
end
end
end
<file_sep>/spec/api/v1/sessions_controller_spec.rb
require 'rails_helper'
RSpec.describe Api::V1::SessionsController, type: :request do
# initialize test data
let(:user) { create(:user, :as_candidate, password: '<PASSWORD>', password_confirmation: '<PASSWORD>') }
let(:user_params) { {"user": {"username": user.username, "password": '<PASSWORD>' }}.to_json }
let(:invalid_user_params) { {"user": {"username": user.username, "password": '<PASSWORD>' }}.to_json }
describe 'GET /api/v1/users/sign_in/' do
context 'returns status code 200' do
before { post "/api/v1/users/sign_in/", params: user_params, headers: { 'Content-Type' => 'application/json' } }
it 'returns the token' do
expect(json['message']).to eq('Authentication successful')
expect(response).to have_http_status(200)
expect(json['message']).to be_a(String)
end
end
context 'when the password is invalid' do
before { post "/api/v1/users/sign_in/", params: invalid_user_params, headers: headers }
it 'returns status code 200 and token nil' do
expect(json['message']).to eq('Authentication failed')
expect(json['jwt']).to eq(nil)
expect(response).to have_http_status(401)
end
end
end
end<file_sep>/app/controllers/api/v1/candidates_controller.rb
class Api::V1::CandidatesController < Api::V1::ApplicationController
def new_candidate
@user = User.new(profile: Candidate.new)
end
end
<file_sep>/app/controllers/api/v1/registrations_controller.rb
class Api::V1::RegistrationsController < Devise::RegistrationsController
include ApplicationHelper
skip_before_action :verify_authenticity_token
prepend_before_action :require_no_authentication, only: :create
before_action :configure_permitted_parameters
respond_to :json
def create
begin
profile_klass = User::PROFILE_TYPES.detect { |m| user_params[:profile_type].classify.constantize == m }
ensure
unless profile_klass
build_resource(user_params.except(:profile_attributes))
resource.save
render_resource(resource)
return
end
end
profile_params = user_params[:profile_attributes]
build_resource(user_params.except(:profile_attributes))
resource.build_profile(profile_params, profile_klass)
# resource.profile = profile_klass.new profile_params
resource.save
render_resource(resource)
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :first_name, :last_name, :password_confirmation, :profile_type, profile_attributes: [:name, :description, :profession, :notes] )
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :first_name, :last_name, :email, :password, :password_confirmation, profile_attributes: [:name, :description, :profession, :notes] ] )
end
end
<file_sep>/spec/factories/job_adverts.rb
FactoryBot.define do
factory :job_advert, class: JobAdvert do
description { Faker::Lorem.sentence }
company
end
end
<file_sep>/spec/models/candidate_spec.rb
require 'rails_helper'
RSpec.describe Candidate, type: :model do
it { should have_one :user }
it { should have_many :job_subscriptions }
it { should have_and_belong_to_many :subscription_job_adverts }
it { should validate_presence_of :profession }
it { should respond_to(:profession) }
it { should respond_to(:notes) }
end
<file_sep>/app/controllers/api/v1/job_adverts_controller.rb
class Api::V1::JobAdvertsController < Api::V1::ApplicationController
before_action :set_job_advert, only: [:show, :update]
load_and_authorize_resource :job_advert, except: [ :my_adverts_as_company, :my_adverts_as_candidate]
respond_to :json
def show
render json: @job_advert, status: :ok
end
# My adverts as company
def my_adverts_as_company
authorize! :my_adverts_as_company, JobAdvert.new
@q = current_user.profile.job_adverts.ransack(params[:q])
@job_adverts = @q.result.page( params[:page] ).per(@per_page)
render json: @job_adverts, each_serializer: JobAdvertSerializer,
serializer: ActiveModel::Serializer::CollectionSerializer
end
# My adverts as candidate
def my_adverts_as_candidate
authorize! :my_adverts_as_candidate, JobAdvert.new
@q = current_user.profile.subscription_job_adverts.ransack(params[:q])
@job_adverts = @q.result.page( params[:page] ).per(@per_page)
render json: @job_adverts, each_serializer: JobAdvertSerializer,
serializer: ActiveModel::Serializer::CollectionSerializer
end
# List all adverts
def list_adverts
@q = JobAdvert.all.ransack(params[:q])
@job_adverts = @q.result.page( params[:page] ).per(@per_page)
render json: @job_adverts, each_serializer: JobAdvertSerializer,
serializer: ActiveModel::Serializer::CollectionSerializer
end
def create
@job_advert = new_instance(job_advert_params)
@job_advert.save
render_resource @job_advert
end
def update
@job_advert.update(job_advert_params)
render_resource @job_advert
end
private
def set_job_advert
@job_advert = JobAdvert.find(params[:id])
render json: ApiMessage.not_found, status: :not_found if @job_advert.blank?
end
def job_advert_params
params.require(:job_advert).permit(:description)
end
def new_instance build_params = {}
@job_advert = current_user.profile.job_adverts.build build_params
end
end<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
it { should belong_to :profile }
it { should validate_presence_of :email }
it { should validate_presence_of :password }
it { should validate_presence_of :username }
it { should validate_presence_of :first_name }
it { should validate_presence_of :last_name }
it { should validate_confirmation_of :password }
it { should respond_to(:email) }
it { should respond_to(:username) }
end
<file_sep>/spec/factories/companies.rb
FactoryBot.define do
factory :company do
name { Faker::Name.unique.name }
description { Faker::Lorem.paragraph }
end
end<file_sep>/app/controllers/concerns/api_message.rb
# app/lib/api_message.rb
class ApiMessage
def self.not_found(record = 'record')
{ message: "Sorry, #{record} not found.", code: 'NF'}
end
def self.invalid_credentials
{ message: 'Invalid credentials', code: 'IC'}
end
def self.invalid_token
{ message: 'Invalid token', code: 'IT'}
end
def self.missing_token
{ message: 'Missing token', code: 'MT'}
end
def self.unauthorized
{ message: 'Unauthorized request', code: 'UR'}
end
def self.account_created
{ message: 'Account created successfully', code: 'AC'}
end
def self.account_not_created
{ message: 'Account could not be created', code: 'ANC'}
end
def self.expired_token
{ message: 'Sorry, your token has expired. Please login to continue.', code: 'TE'}
end
def self.unprocessable_entity
{ message: 'Unprocessable entity', code: 'UE'}
end
def self.verification_error
{ message: 'Token verification error', code: 'VE'}
end
def self.invalid_route
{ message: 'Route not found', code: 'RNF'}
end
def self.access_denied
{ message: 'You are not authorized', code: 'NA'}
end
end<file_sep>/spec/models/ability/ability_spec.rb
require 'rails_helper'
require 'cancan/matchers'
RSpec.describe Ability, type: :model do
describe "Job Adverts abilities" do
subject(:ability) { Ability.new(user) }
context "User as company can update a job advert" do
let(:user) { create(:user, :as_company) }
it do
job_advert = create :job_advert, company: user.profile
should be_able_to(:update, job_advert)
end
it do
other_user_company = create(:user, :as_company)
job_advert = create :job_advert, company: other_user_company.profile
should_not be_able_to(:update, job_advert)
end
end
context "Only User as company can create a job advert" do
let(:user) { create(:user, :as_company) }
let(:job_advert) { create(:job_advert, company: user.profile) }
it do
should be_able_to(:create, job_advert)
end
end
context "A Candidate User can not create a job advert" do
let(:user) { create(:user, :as_candidate) }
it do
should_not be_able_to(:create, JobAdvert.new)
end
end
context "User can read and list job adverts" do
let(:user) { create(:user, :as_candidate) }
let(:job_advert) { create(:job_advert) }
it do
should be_able_to(:list_adverts, JobAdvert)
end
it do
should be_able_to(:read, job_advert)
end
end
context "Company User can list adverts created" do
let(:user) { create(:user, :as_company) }
let(:job_advert) { create(:job_advert, company: user.profile) }
it do
should be_able_to(:my_adverts_as_company, JobAdvert)
end
end
context "Candidate User can not list adverts created" do
let(:user) { create(:user, :as_candidate) }
it do
should_not be_able_to(:my_adverts_as_company, JobAdvert)
end
end
# context "Candidate User can list adverts as candidate" do
# let(:user) { create(:user, :as_candidate) }
# let(:job_advert) { create(:job_advert) }
#
# it do
# should be_able_to(:my_adverts_as_candidate, JobAdvert)
# end
# end
#
# context "Company User can not list adverts as candidate" do
# let(:user) { create(:user, :as_company) }
# let(:job_advert) { create(:job_advert, company: user.profile) }
#
# it do
# should_not be_able_to(:my_adverts_as_candidate, JobAdvert)
# end
# end
# Users
context "User as company can update a job advert" do
let(:user) { create(:user, :as_company) }
it do
should be_able_to(:read, user)
end
it do
should be_able_to(:update, user)
end
it do
other_user_company = create(:user, :as_company)
should_not be_able_to(:update, other_user_company)
end
end
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :token_authentication, unless: :user_signed_in?, except: [:parse_results, :exempt_data, :departments_info, :check_status]
def token_authentication
request.headers['Authorization'] = params['Authorization']
begin
user = AuthorizeApiRequest.new(request.headers).call
rescue ExceptionHandler::MissingToken
end
sign_in(user) if user.present?
end
end
<file_sep>/spec/factories/job_subscriptions.rb
FactoryBot.define do
factory :job_subscription, class: JobSubscription do
candidate
job_advert
subscription_status { :pending }
end
end
<file_sep>/app/controllers/concerns/authorize_request.rb
module AuthorizeRequest
extend ActiveSupport::Concern
attr_reader :current_user
private
def authorize_request
@current_user ||= AuthorizeApiRequest.new(request.headers).call
end
def current_user
@current_user
end
def authorization?
return true if request.headers['Authorization'].present?
end
end<file_sep>/app/serializers/application_serializer.rb
class ApplicationSerializer < ActiveModel::Serializer
include SimpleEnum::ViewHelpers
def type
self.object.class.to_s
end
end
<file_sep>/spec/models/job_advert_spec.rb
require 'rails_helper'
RSpec.describe JobAdvert, type: :model do
it { should belong_to :company }
it { should have_many :job_subscriptions }
it { should have_and_belong_to_many :subscription_job_adverts }
it { should validate_presence_of :description }
it { should respond_to(:company) }
it { should respond_to(:description) }
end<file_sep>/app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < Api::V1::ApplicationController
before_action :set_user, only: [:show, :update]
load_and_authorize_resource :user
respond_to :json
def show
render json: @user, status: :ok
end
def index
@q = User.all.ransack(params[:q])
@users = @q.result.page( params[:page] ).per(@per_page)
render json: @users, each_serializer: UserSerializer,
serializer: ActiveModel::Serializer::CollectionSerializer
end
def update
@user.update(user_params)
render_resource @user
end
private
def set_user
@user = params[:id].present? ? User.find(params[:id]) : User.find_by_username(params[:username])
render json: ApiMessage.not_found, status: :not_found if @user.blank?
end
def user_params
params.require(:user).permit(:first_mame, :last_name, :email, :password, :password_confirmation)
end
end<file_sep>/app/models/company.rb
class Company < ApplicationRecord
has_one :user, as: :profile, dependent: :destroy, inverse_of: :profile
has_many :job_adverts
validates_presence_of :name, :description
validates_uniqueness_of :name
end | 14dc8602eb102664208b5f532bd970baa8c442bb | [
"Ruby"
] | 41 | Ruby | lopomaster/job_board | dd948f23137d263dda0019cd82dd07545677198e | 599998acae927e3d224882b60ebd89970459c26c |
refs/heads/master | <file_sep>
# BowlingAPerfectTDD
<file_sep>/* jshint esversion: 6 */
const chai = require("chai");
const score = require("../bowlScore.js");
const expect = chai.expect;
let game1 = [
{
a: 4,
b: 3
},
{
a: 10,
},
{
a: 7,
b: 3
},
{
a: 8,
b: 0
},
{
a: 2,
b: 8
},
{
a: 10,
},
{
a: 10,
},
{
a: 8,
b: 0
},
{
a: 3,
b: 7
},
{
a: 10,
b: 5,
c: 4
}
];
let game2 = [
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0
},
{
a: 0,
b: 0,
}
];
let game3 = [
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10
},
{
a: 10,
b: 10,
c: 10
}
];
let game4 = [
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5,
c: 5
}
];
let game5 = [
{
a: 5,
b: 5
},
{
a: 10
},
{
a: 5,
b: 5
},
{
a: 10
},
{
a: 5,
b: 5
},
{
a: 10
},
{
a: 5,
b: 5
},
{
a: 10
},
{
a: 5,
b: 5
},
{
a: 5,
b: 5,
c: 5
}
];
describe("score function", () => {
it("should be a function", () => {
expect(score).to.be.a("function");
});
it("should only take in an array of data", () => {
expect(score.bind(null, 19)).to.throw(Error);
expect(score.bind(null, {a: 12})).to.throw(Error);
expect(score.bind(null, NaN)).to.throw(Error);
expect(score.bind(null, "Bowling")).to.throw(Error);
});
it("should only take an array of 10 objects", () => {
expect(score.bind(null, [4, 5, 9])).to.throw(Error);
expect(score.bind(null, [{4: 5}, {a: 7}, {b: 2}])).to.throw(Error);
});
it("should be able to calculate a perfect game", () => {
expect(score(game3)).to.equal(300);
expect(score(game2)).to.equal(0);
});
it("should calculate spares", () => {
expect(score(game4)).to.equal(150);
});
it("should calculate mixed scores", () => {
expect(score(game5)).to.equal(190);
expect(score(game1)).to.equal(166);
});
}); | 80625a9e92a82992541be88f7950f1efbdf4e6a9 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | GaganTut/BowlingAPerfectTDD | 9723f43d74391d7d71cd924cb27216cb3c4740d7 | 00f17a3478d090303d535e60774b4647ab17ebb4 |
refs/heads/master | <repo_name>avantika001/railways<file_sep>/railwaylogfile.sql
mysql> create table passenger( p_id int(11) unsigned zerofill not null auto_increment,
-> u_id int(11),
-> t_id int(11),
-> status varchar(30),
-> source varchar(30),
-> destination varchar(30),
-> t_no int,
-> primary key(p_id,u_id)
-> );
mysql> alter table passenger add foreign key(u_id) references user(u_id);
mysql> alter table passenger add foreign key(t_no) references train(t_no);<file_sep>/search_for_train.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>seach for train</title>
</head>
<script type="text/javascript">
function validate() {
var EmailId=document.getElementById("email");
var atpos = EmailId.value.indexOf("@");
var dotpos = EmailId.value.lastIndexOf(".");
var pw=document.getElementById("pw");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=EmailId.value.length)
{
alert("Enter valid email-ID");
EmailId.focus();
return false;
}
if(pw.value.length< 8)
{
alert("Password consists of atleast 8 characters");
pw.focus();
return false;
}
return true;
}
</script>
<style type="text/css">
#loginarea{
background-color: white;
width: 30%;
margin: auto;
border-radius: 25px;
border: 2px solid blue;
margin-top: 100px;
background-color: rgba(0,0,0,0.2);
box-shadow: inset -2px -2px rgba(0,0,0,0.5);
padding: 40px;
font-family:sans-serif;
font-size: 20px;
color: white;
}
html {
background: url(img/bg4.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#submit {
border-radius: 5px;
background-color: rgba(0,0,0,0);
padding: 7px 7px 7px 7px;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
#logintext {
text-align: center;
}
.data {
color: white;
}
button,a{
text-decoration:none;
padding:7px;
margin:5px;
background-color:DodgerBlue;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
a:hover{
background-color:green;
}
button:hover{
background-color:red;
cursor:pointer;
}
</style>
<body>
<div id="loginarea">
<center>plan your journey<center><br>
<!-- changed -->
<?php
error_reporting(E_ALL);
ob_start();
include('user_homepage.php');
include('login.php');
include('signup.php');
ob_end_clean();
error_reporting(E_ALL);
$db=mysqli_connect("localhost","avantika","avantika","db1")or die("connection not established"); #port number
if(isset($_POST['search'])){
$from=$_POST['from'];
$to=$_POST['to'];
$type=$_POST['type'];
//$sql="select * from user";
if($from==$to)
echo "source and destination cannot be same!";
else{
if(($to=="Gorakhpur")||($to=="Indore")){
$sql="select T.t_no,T.t_name,T.start_t,S.arrival_time from train T,station S where T.t_no=S.t_no and T.start_station='$from'";
}
else if(($from=="Gorakhpur")||($from=="Indore")){
$sql="select T.t_no,T.t_name,S.arrival_time as start_t,T.arrival_time from train T,station S where T.t_no=S.t_no and T.start_station='$to'";
}
else{
$sql="select * from train where start_station='$from' and end_station='$to'";
}
if($result1=mysqli_query($db,$sql)){
//echo "working";
}else{
printf("ERROR: Could not execute $sql. " . mysqli_error($db));
}
if(!$result1 || mysqli_num_rows($result1)==0){
//output data of each row
echo "0 results";
}else{
while($row=mysqli_fetch_assoc($result1)){
//$i=$i+1;
$train=$row['t_no'];
$sql2=""; $fare="";$seats="";
if($type=='AC_fare'){
$sql2=mysqli_query($db,"SELECT AC_fare,A_seat from train_status where t_no='$train'");
$row1=mysqli_fetch_assoc($sql2);
$fare=$row1['AC_fare'];
$seats=$row1['A_seat'];
}else {
$sql2=mysqli_query($db,"SELECT g_fare,B_seat from train_status where t_no='$train'");
$row1=mysqli_fetch_assoc($sql2);
$fare=$row1['g_fare'];
$seats=$row1['B_seat'];
}
echo "<br><table><tr><td>Train no</td><td>:</td><td>".$row['t_no']."</td></tr><tr><td>Train Name</td><td>:</td><td>".$row['t_name']."</td></tr><tr><td>Start Time</td><td>:</td><td>".$row['start_t']."</td></tr>";
echo "<tr><td>Fare</td><td>:</td><td>".$fare."</td></tr><tr><td>seats</td><td>:</td><td>".$seats."</td></tr></table><br>";
//echo "<input type='button' onclick='book('"."$i".".');' value='book ticket'/>";
}
}}
}
?>
<!-- change end --><br>
<a href="book.php">want to book?</a><br>
<a href="user_homepage.php">go back</a><br>
<a href="logout.php">logout</a><br>
</div>
</body>
</html>
<file_sep>/railwayrest.sql
>create table user (u_id int not null auto_increment primary key,first_name varchar(30),last_name varchar(30),email varchar(30),gender varchar(30),age varchar(30),password varchar(30));
>create table train(t_no int primary key,t_name varchar(30),no_of_seats int,start_t varchar(30),start_station varchar(30),end_station varchar(30));
>create table train_status(t_no int primary key,A_seat int,B_seat int,AC_fare varchar(30),g_fare varchar(30),foreign key(t_no) references train(t_no) on update cascade on delete cascade);
>create table station(s_no int primary key,s_name varchar(30),halt varchar(30),arrival_time varchar(30),t_no varchar(30),hours varchar(30));
<file_sep>/signup.php
<?php
session_start();
error_reporting(E_ERROR | E_PARSE);
$db=mysqli_connect("localhost","avantika","avantika","db1"); #port number
if(!$db){
printf("not connected to server");
}
if(isset($_POST['register'])){
$first_name=mysqli_real_escape_string($db,$_POST['first_name']);
$last_name=mysqli_real_escape_string($db,$_POST['last_name']);
$email=mysqli_real_escape_string($db,$_POST['email']);
$age=mysqli_real_escape_string($db,$_POST['age']);
$gender=mysqli_real_escape_string($db,$_POST['gender']);
$password=mysqli_real_escape_string($db,$_POST['password']);
$retype_password=mysqli_real_escape_string($db,$_POST['retype_password']);
//save to database
if($password == $retype_password){
#$password=md5($password);//encrypting the password
$sql="INSERT INTO user (first_name,last_name,email,gender,age,password) VALUES('$first_name','$last_name','$email','$gender','$age','$password')";
if(mysqli_query($db, $sql)){
$row=mysqli_query($db,"SELECT * from user where first_name='$first_name' and last_name='$last_name'
and gender='$gender' and age='$age' and email='$email'");
if($row1=mysqli_fetch_assoc($row)){
$_SESSION['first_name']=$first_name;
$_SESSION['u_id']=$row1['u_id'];
$_SESSION['success']="your account has been created!";
header('location:user_homepage.php');
}
//redirecting to user home page
//echo "<script> window.location.assign('user_homepage.php'); </script>";
} else{
printf("ERROR: Could not able to execute $sql. " . mysqli_error($db));
}
}
else{
$_SESSION['message']="the passwords do not match";
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>SignUp</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<script type="text/javascript">
function validate() {
var EmailId=document.getElementById("email");
var atpos = EmailId.value.indexOf("@");
var dotpos = EmailId.value.lastIndexOf(".");
var pw=document.getElementById("pw");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=EmailId.value.length)
{
alert("Enter valid email-ID");
EmailId.focus();
return false;
}
if(pw.value.length< 8)
{
alert("Password consists of atleast 8 characters");
pw.focus();
return false;
}
return true;
}
</script>
<style type="text/css">
#loginarea{
background-color: white;
width: 30%;
margin: auto;
border-radius: 25px;
border: 2px solid blue;
margin-top: 100px;
background-color: rgba(0,0,0,0.2);
box-shadow: inset -2px -2px rgba(0,0,0,0.5);
padding: 40px;
font-family:sans-serif;
font-size: 20px;
color: white;
}
html {
background: url(img/bg4.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#register,#gobackbtn {
text-decoration:none;
border-radius: 5px;
background-color: DodgerBlue;
padding: 7px 7px 7px 7px;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
#register:hover,#gobackbtn:hover{
background-color:red;
cursor:pointer;
}
#gobackbtn{
background-color:green;
}
#logintext {
text-align: center;
}
.data {
color: white;
}
input{
border-radius:5px;
padding:7px;
}
</style>
<body style=""><div id="loginarea">
<center>Register Here!</center>
<form class="" action="signup.php" method="POST">
<table>
<tr>
<td>first name:</td>
<td><input type="text" name="first_name" value="" required/></td>
</tr>
<tr>
<td>last name:</td>
<td><input type="text" name="last_name" value="" required></td>
</tr>
<tr>
<td>email:</td>
<td><input type="text" name="email" value="" required/></td>
</tr>
<tr>
<td>age:</td>
<td><input type="text" name="age" value="" required/></td>
</tr>
<tr>
<td>gender:</td>
<td><input type="text" name="gender" value="" placeholder="male/female/other" required/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" value="" required/></td>
</tr>
<tr>
<td>Retype Password:</td>
<td><input type="password" name="retype_password" value="" required/></td>
</tr>
</table>
<center>
<button type="submit" name="register" id="register">Register!</button><center>
</form>
<center>
<a href="homepage.php" id="gobackbtn">Go Back</a></center></div>
</body>
</html>
<file_sep>/user_homepage.php
<?php
ob_start();
include('login.php');
include('signup.php');
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>user homepage</title>
<script type="text/javascript">
function validate() {
var EmailId=document.getElementById("email");
var atpos = EmailId.value.indexOf("@");
var dotpos = EmailId.value.lastIndexOf(".");
var pw=document.getElementById("pw");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=EmailId.value.length)
{
alert("Enter valid email-ID");
EmailId.focus();
return false;
}
if(pw.value.length< 8)
{
alert("Password consists of atleast 8 characters");
pw.focus();
return false;
}
return true;
}
</script>
<style type="text/css">
#loginarea{
background-color: white;
width: 30%;
margin: auto;
border-radius: 25px;
border: 2px solid blue;
margin-top: 100px;
background-color: rgba(0,0,0,0.2);
box-shadow: inset -2px -2px rgba(0,0,0,0.5);
padding: 40px;
font-family:sans-serif;
font-size: 20px;
color: white;
}
html {
background: url(img/bg4.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#submit {
border-radius: 5px;
background-color: rgba(0,0,0,0);
padding: 7px 7px 7px 7px;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
#logintext {
text-align: center;
}
.data {
color: white;
}
button,a{
text-decoration:none;
padding:7px;
margin:5px;
background-color:DodgerBlue;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
.title{
background-color:black;
padding:7px;
border-radius:5px;
}
a:hover{
background-color:green;
}
button:hover{
background-color:red;
cursor:pointer;
}
</style>
</head>
<body>
<?php if(isset($_SESSION['success'])): ?>
<div class="error success">
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<?php if(isset($_SESSION['first_name'])): ?>
<div id="loginarea">
<div id="logintext">Welcome, <strong><?php echo $_SESSION['first_name'] ;?></strong></div>
<!-- search for train code --><br><br>
<center class="title">Search</center>
<div class="search">
<form class="" action="search_for_train.php" method="post" id="search_for_train">
<table>
<tr>
<tr>
<td>from:</td>
<td><select class="selectpicker" name="from" id="from" required>
<option value="Kanpur(KNP)">Kanpur(KNP)</option>
<option value="Patna(PTA)">Patna(PTA)</option>
<option value="Bengaluru(BNG)">Bengaluru(BNG)</option>
<option value="Bhopal(BHO)">Bhopal(BHO)</option>
<option value="Gorakhpur">Gorakhpur</option>
<option value="Indore">Indore</option>
</select></td>
</tr>
<tr>
<td>to:</td>
<td><select class="selectpicker" name="to" id="to" required>
<option value="Kanpur(KNP)">Kanpur(KNP)</option>
<option value="Patna(PTA)">Patna(PTA)</option>
<option value="Bengaluru(BNG)">Bengaluru(BNG)</option>
<option value="Bhopal(BHO)">Bhopal(BHO)</option>
<option value="Gorakhpur">Gorakhpur</option>
<option value="Indore">Indore</option>
</select></td>
</tr>
<tr>
<td>category:</td>
<td><select class="selectpicker" name="type" id="type" required>
<option value="AC_fare">AC_fare</option>
<option value="g_fare">g_fare</option>
</select></td>
</tr>
</table>
<button type="submit" name="search">search!</button>
</form>
</div>
<!-- enquiry -->
<br><div class="search"><center class="title">Make enquiry</center>
<form class="" action="enquiry_for_PNR.php" method="post">
<label for="PNR">PNR</label>
<input type="text" name="PNR" value="" required><br>
<label for="TNO">Ticket No</label>
<input type="text" name="TNO" value="" required><br>
<button type="submit" name="check">check</button>
</form>
</div><br>
<center>
<br><a href="book.php">Book Tickets</a>
<?php endif ?></center>
<center><a href="cancel_tickets.php">Cancel Tickets</a></center>
<center><a href="logout.php">Logout</a><br></center>
</body>
</html>
<file_sep>/cancel_tickets.php
<?php
ob_start();
include('login.php');
include('signup.php');
ob_end_clean();
$db=mysqli_connect("localhost","avantika","avantika","db1") or doe("cannot connect to the server");
$PNR=$_POST['PNR'];
if(isset($_POST['cancel_tickets'])){
// mysqli_query($db,"CALL updateValue('$PNR')");
$PNR=$_POST['PNR'];
if($sql=mysqli_query($db,"SELECT * from passenger where p_id='$PNR'")){
while($row=mysqli_fetch_assoc($sql)){
$PNR=$row['p_id'];
$USER=$row['u_id'];
$TICKET=$row['t_id'];
$SOURCE=$row['source'];
$DESTINATION=$row['destination'];
$TRAIN=$row['t_no'];
$TYPE=$row['type'];
mysqli_query($db,"update passenger set status='canceled' where p_id='$PNR' ");
if($TYPE=='AC_fare'){
mysqli_query($db,"update train_status set A_seat=A_seat+1 where t_no='$TRAIN' ");
}else{
mysqli_query($db,"update train_status set B_seat=B_seat+1 where t_no='$TRAIN' ");
}
echo '<script type="text/javascript">alert("canceled");</script>';
}
}else {
printf("PNR NOT FOUND");
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>cancel tickets</title>
<script type="text/javascript">
function validate() {
var EmailId=document.getElementById("email");
var atpos = EmailId.value.indexOf("@");
var dotpos = EmailId.value.lastIndexOf(".");
var pw=document.getElementById("pw");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=EmailId.value.length)
{
alert("Enter valid email-ID");
EmailId.focus();
return false;
}
if(pw.value.length< 8)
{
alert("Password consists of atleast 8 characters");
pw.focus();
return false;
}
return true;
}
</script>
<style type="text/css">
#loginarea{
background-color: white;
width: 30%;
margin: auto;
border-radius: 25px;
border: 2px solid blue;
margin-top: 100px;
background-color: rgba(0,0,0,0.2);
box-shadow: inset -2px -2px rgba(0,0,0,0.5);
padding: 40px;
font-family:sans-serif;
font-size: 20px;
color: white;
}
html {
background: url(img/bg4.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#submit {
border-radius: 5px;
background-color: rgba(0,0,0,0);
padding: 7px 7px 7px 7px;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
#logintext {
text-align: center;
}
.data {
color: white;
}
button,a{
text-decoration:none;
padding:7px;
margin:5px;
background-color:DodgerBlue;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
width:400px;
text-align:center;
}
a:hover{
background-color:green;
}
button:hover{
background-color:red;
cursor:pointer;
}
</style>
</head>
<body>
<div id="loginarea">
<form class="" action="cancel_tickets.php" method="post">
<div id="logintext">Cancel Tickets</div><br/><br/>
<table>
<tr><td><label for="PNR">PNR</label>
<input type="text" name="PNR" value="" required><br></td></tr>
<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
<tr><td><label for="ticket_id">Ticket ID</label>
<input type="text" name="ticket_id" value="" required><br></td></tr>
<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
</table>
<button type="submit" name="cancel_tickets">SUBMIT</button>
</form>
<a href="user_homepage.php">go back</a><br>
<a href="logout.php">logout</a><br>
</body>
</html>
<file_sep>/logout.php
<?php
ob_start();
include('user_homepage.php');
include('enquiry_for_PNR.php');
include('search_for_train.php');
include('book.php');
ob_end_clean();
session_start();
session_destroy();
unset($_SESSION['u_id']);
$_SESSION['message']='You have been logged out';
header('location:homepage.php');
?>
<file_sep>/login.php
<?php
session_start();
error_reporting(E_ERROR | E_PARSE);
$db=mysqli_connect("localhost","avantika","avantika","db1");
$email=mysqli_real_escape_string($db,$_POST['email']);
$password=mysqli_real_escape_string($db,$_POST['password']);
//query the db for user email and passwords
if(isset($_POST['login'])){
$result=mysqli_query($db,"select * from user where email='$email' and password='$password'")
or die("failed to query database");
$row=mysqli_fetch_array($result);
if(($row['email']==$email)&& ($row['password']==$password)){
//echo "login successful! welcome,",$row['first_name'];
$_SESSION['first_name']=$row['first_name'];
$_SESSION['u_id']=$row['u_id'];
$_SESSION['success']="you've been logged in!";
header('location:user_homepage.php'); //redirecting to user home page NOT WORKING
//echo "<script> window.location.assign('user_homepage.php'); </script>"; //REDIRECTION WORKING
exit();
}else{
echo "failed to login";
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<script type="text/javascript">
function validate() {
var EmailId=document.getElementById("email");
var atpos = EmailId.value.indexOf("@");
var dotpos = EmailId.value.lastIndexOf(".");
var pw=document.getElementById("pw");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=EmailId.value.length)
{
alert("Enter valid email-ID");
EmailId.focus();
return false;
}
if(pw.value.length< 8)
{
alert("Password consists of atleast 8 characters");
pw.focus();
return false;
}
return true;
}
</script>
<style type="text/css">
#loginarea{
background-color: white;
width: 30%;
margin: auto;
border-radius: 25px;
border: 2px solid blue;
margin-top: 100px;
background-color: rgba(0,0,0,0.2);
box-shadow: inset -2px -2px rgba(0,0,0,0.5);
padding: 40px;
font-family:sans-serif;
font-size: 20px;
color: white;
}
html {
background: url(img/bg4.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#submit {
border-radius: 5px;
background-color: rgba(0,0,0,0);
padding: 7px 7px 7px 7px;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
#logintext {
text-align: center;
}
.data {
color: white;
}
input{
border:none;
padding:10px;
border-radius:10px;
}
input[type=text]:focus {
background-color: lightblue;
}
.login,.goback{
border:2px solid white;
padding:15px;
background: Dodgerblue;
border-radius:5px;
margin:15px;
cursor:pointer;
font-size:20px;
color:white;
}
.login:hover,.goback:hover{
background:green;
}
</style>
</head>
<body>
<div id="loginarea">
<form class="" action="login.php" method="post">
<div id="logintext">Login to Indian Railways!</div><br/><br/>
<table>
<tr><td><div class="data">Enter E-Mail ID:</div></td><td><input type="text" name="email"/></td></tr>
<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
<tr><td><div class="data">Enter Password:</div></td><td><input type="password" name="password"/></td></tr>
<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
</table>
<button type="submit" name="login" class="login">Login</button>
<a href="homepage.php" class="goback">Go back</a>
</form></div>
</body>
</html>
<file_sep>/book.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>booking</title>
<LINK REL="STYLESHEET" HREF="STYLE.CSS">
<style type="text/css">
#booktkt {
margin:auto;
margin-top: 50px;
width: 40%;
height: 60%;
padding: auto;
padding-top: 50px;
padding-left: 50px;
background-color: rgba(0,0,0,0.3);
border-radius: 25px;
}
html {
background: url(img/bg7.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#journeytext,#loginarea {
color: white;
font-size: 28px;
font-family:"Comic Sans MS", cursive, sans-serif;
}
#trains {
margin-left: 90px;
font-size: 15px;
}
#submit {
margin-left: 150px;
margin-bottom: 40px;
margin-top: 30px
}
button,a{
text-decoration:none;
padding:7px;
margin:5px;
background-color:DodgerBlue;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
width:400px;
}
a:hover{
background-color:green;
}
button:hover{
background-color:red;
cursor:pointer;
}
</style>
<script type="text/javascript">
function validate() {
var trains=document.getElementById("trains");
if(trains.selectedIndex==0)
{
alert("Please select your train");
trains.focus();
return false;
}
}
</script>
</head>
<body>
<div id="book">
<h1 align="center" id="journeytext">Plan your journey</h1><br/><br/>
<div id="loginarea">
<form class="" action="book.php" method="post" id="book">
<table border="0">
<tr>
<td>from:</td>
<td><select class="" name="from" id="from" required>
<option value="Kanpur(KNP)">Kanpur(KNP)</option>
<option value="Patna(PTA)">Patna(PTA)</option>
<option value="Bengaluru(BNG)">Bengaluru(BNG)</option>
<option value="Bhopal(BHO)">Bhopal(BHO)</option>
<option value="Gorakhpur">Gorakhpur</option>
<option value="Indore">Indore</option>
</select></td>
</tr>
<tr>
<td>to:</td>
<td><select class="" name="to" id="to" required>
<option value="Kanpur(KNP)">Kanpur(KNP)</option>
<option value="Patna(PTA)">Patna(PTA)</option>
<option value="Bengaluru(BNG)">Bengaluru(BNG)</option>
<option value="Bhopal(BHO)">Bhopal(BHO)</option>
<option value="Gorakhpur">Gorakhpur</option>
<option value="Indore">Indore</option>
</select></td>
</tr>
<tr>
<td>category:</td>
<td><select class="" name="type" id="type" required>
<option value="AC_fare">AC_fare</option>
<option value="g_fare">g_fare</option>
</select></td>
</tr>
<tr>
<td>TRAIN</TD>
<td>
<select class="" name="train_no">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select><td></tr>
</table>
<center><button type="submit" name="book_ticket">BOOK!</button></center>
</form><center><br>
<a href="search_for_train.php">go back</a><br>
<a href="user_homepage.php">homepage</a><br>
<a href="logout.php">logout</a><br></center>
<?php
error_reporting(E_ALL);
ob_start();
include('login.php');
include('signup.php');
ob_end_clean();
$db=mysqli_connect("localhost","avantika","avantika","db1") or die("connection not established");
$from=$_POST['from'];
$to=$_POST['to'];
if(isset($_POST['book_ticket'])&&($from!=$to)){
$type=$_POST['type'];
$u_id=$_SESSION['u_id'];
$t_id=rand(0,300);
//echo "original t_id:".$t_id."<br>";
//store the t_id in database
if($sql=mysqli_query($db,"SELECT t_id from passenger")){
while($row=mysqli_fetch_assoc($sql)){
//echo 'row[t_id]:'.$row['t_id']; //content of the row
//echo 't_id:'.$t_id."<br>";
if($t_id==(int)$row['t_id']){
//echo "not yet generated";
$t_id=rand(0,300);
//echo 'generated t_id:'.$t_id."<br>";
}
}
}else{
printf("ERROR: Could not execute $sql. " . mysqli_error($db));
}
//echo "ticket:".$t_id;
//defining status by chechking the availability of seats of that type
$status="waiting";
$t_no = $_POST['train_no']; //from search_for_train.php
//echo "train:".$t_no;
if($type=='AC_fare'){
//check number of B_seat
$sql=mysqli_query($db,"select A_seat from train_status where t_no='$t_no'");
$row=mysqli_fetch_assoc($sql);
$result=(int)$row['A_seat'];
if($result>0){
$status="booked";
//decrease the number of seats in B_seat
mysqli_query($db,"UPDATE train_status SET A_seat=A_seat-1 where t_no='$t_no'");
}
}else{
$sql=mysqli_query($db,"select B_seat from train_status where t_no='$t_no'");
$row=mysqli_fetch_assoc($sql);
$result=$row['B_seat'];
if($result>0){
$status="booked";
//decrease the number of seats in A_seat
mysqli_query($db,"UPDATE train_status SET B_seat=B_seat-1 where t_no='$t_no'");
}
}
$final="INSERT INTO passenger(u_id,t_id,status,source,destination,t_no,type) VALUES($u_id,$t_id,'$status','$from','$to',$t_no,'$type')";
if(mysqli_query($db,$final)){
echo '<script type="text/javascript">alert("'.$status.'");</script>';
}else{
printf("ERROR: Could not able to execute $sql. " . mysqli_error($db));
}
}else{
echo "<center>same source and destination cannot be booked!</center>";
}
$u_id=$_SESSION['u_id'];
$db=mysqli_connect("localhost","avantika","avantika","db1") or die("connection not established");
$sql=mysqli_query($db,"SELECT * from passenger where u_id=$u_id and t_id=$t_id");
$row=mysqli_fetch_assoc($sql);
if($row['status']=='booked'){
echo "<center>Your seat has been booked.<br>Your PNR number is:".$row['p_id']."<br>and<br> ticket id is:".$row['t_id']."</center>";
}
?>
</div>
</body>
</html>
<file_sep>/enquiry_for_PNR.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>enquiry for PNR</title>
</head>
<script type="text/javascript">
function validate() {
var EmailId=document.getElementById("email");
var atpos = EmailId.value.indexOf("@");
var dotpos = EmailId.value.lastIndexOf(".");
var pw=document.getElementById("pw");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=EmailId.value.length)
{
alert("Enter valid email-ID");
EmailId.focus();
return false;
}
if(pw.value.length< 8)
{
alert("Password consists of atleast 8 characters");
pw.focus();
return false;
}
return true;
}
</script>
<style type="text/css">
#loginarea{
background-color: white;
width: 30%;
margin: auto;
border-radius: 25px;
border: 2px solid blue;
margin-top: 100px;
background-color: rgba(0,0,0,0.2);
box-shadow: inset -2px -2px rgba(0,0,0,0.5);
padding: 40px;
font-family:sans-serif;
font-size: 20px;
color: white;
}
html {
background: url(img/bg4.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#submit {
border-radius: 5px;
background-color: rgba(0,0,0,0);
padding: 7px 7px 7px 7px;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
}
#logintext {
text-align: center;
}
.data {
color: white;
}
button,a{
text-decoration:none;
padding:7px;
margin:5px;
background-color:DodgerBlue;
box-shadow: inset -1px -1px rgba(0,0,0,0.5);
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 17px;
margin:auto;
margin-top: 20px;
display:block;
color: white;
width:400px;
}
a:hover{
background-color:green;
}
button:hover{
background-color:red;
cursor:pointer;
}
</style>
<body><center>
<div id="loginarea">
Status<br>
<?php
$PNR=""; $USER=""; $TICKET=""; $SOURCE=""; $DESTINATION=""; $TRAIN="";
error_reporting(E_ALL);
$db=mysqli_connect("localhost","avantika","avantika","db1") or die("connection not established");
if(isset($_POST['check'])){
$PNR=$_POST['PNR'];
if($sql=mysqli_query($db,"SELECT * from passenger where p_id='$PNR'")){
while($row=mysqli_fetch_assoc($sql)){
$PNR=$row['p_id'];
$USER=$row['u_id'];
$TICKET=$row['t_id'];
$SOURCE=$row['source'];
$DESTINATION=$row['destination'];
$TRAIN=$row['t_no'];
echo "<table><tr><td>PID</td><td>:</td><td>".$row['p_id']."</td></tr><tr><td>USER ID</td><td>:</td><td>".$row['u_id']."</td></tr><tr><td>TICKET ID</td><td>:</td><td>".$row['t_id']."</td></tr><tr><td>SOURCE</td><td>:</td><td>".$row['source']."</td></tr><tr><td>DESTINATION</td><td>:</td><td>".$row['destination']."</td></tr><tr><td>TRAIN NO</td><td>:</td><td>".$row['t_no']."</td></tr><tr><td>STATUS</td><td>:</td><td>".$row['status']."</td></tr></table>";
}
}else {
printf("PNR NOT FOUND");
}
}
?>
<a href="user_homepage.php">go back</a><br>
<a href="logout.php">logout</a><br>
</div></center>
</body>
</html>
<file_sep>/README.md
# railways
6th sem dbms, 7th sem web
| efe93e12c665482fb7017184f163ac534e7635ab | [
"Markdown",
"SQL",
"PHP"
] | 11 | SQL | avantika001/railways | f592e8d8814b74fe2777949a32300477423c3bc3 | 3f0e0eed1b6ea4eeecc197a9577690f10283592b |
refs/heads/master | <repo_name>Zefir12/Baza-Danych<file_sep>/Moduł_wczytywania_kopizapasowej.py
from Funkcje_i_zmienne import *
import os
print('----------------------Wczytywanie kopi zapasowej danych---------------------')
file = open('KopiaDanych/nazwakopia.txt', 'r').read()
file1 = open('KopiaDanych/dzienkopia.txt', 'r').read()
file5 = open('KopiaDanych/miesiackopia.txt', 'r').read()
file6 = open('KopiaDanych/rokkopia.txt', 'r').read()
file2 = open('KopiaDanych/weglekopia.txt', 'r').read()
file3 = open('KopiaDanych/tluszczekopia.txt', 'r').read()
file4 = open('KopiaDanych/bialkakopia.txt', 'r').read()
indeksfile = open('KopiaDanych/indeksykopia.txt', 'r')
strefeddf = int(indeksfile.readline())
indekskopia = open('Dane/indeksy.txt', 'w')
indekskopia.write(str(strefeddf))
indekskopia.close()
file = file.split('\n')
file1 = file1.split('\n')
file2 = file2.split('\n')
file3 = file3.split('\n')
file4 = file4.split('\n')
file5 = file5.split('\n')
file6 = file6.split('\n')
if len(file) > 1:
filekopia = open('Dane/nazwa.txt', 'w')
file1kopia = open('Dane/dzien.txt', 'w')
file5kopia = open('Dane/miesiac.txt', 'w')
file6kopia = open('Dane/rok.txt', 'w')
file2kopia = open('Dane/wegle.txt', 'w')
file3kopia = open('Dane/tluszcze.txt', 'w')
file4kopia = open('Dane/bialka.txt', 'w')
for line in file:
filekopia.write(line)
filekopia.write('\n')
for line in file1:
file1kopia.write(line)
file1kopia.write('\n')
for line in file2:
file2kopia.write(line)
file2kopia.write('\n')
for line in file3:
file3kopia.write(line)
file3kopia.write('\n')
for line in file5:
file5kopia.write(line)
file5kopia.write('\n')
for line in file6:
file6kopia.write(line)
file6kopia.write('\n')
x = len(file4) - 1
for line in file4:
xd = (1 - (x / (len(file4) - 1))) * 100
xd = round(xd, 2)
os.system("cls")
pasekladowania(xd)
x -= 1
file4kopia.write(line)
file4kopia.write('\n')
filekopia.close()
file1kopia.close()
file2kopia.close()
file3kopia.close()
file4kopia.close()
file5kopia.close()
file6kopia.close()
else:
print('Baza danych jest pusta, nie ma co kopiować\n')<file_sep>/Funkcje_i_zmienne.py
import os.path
from os import path
import sys
slownik_wegle = {}
slownik_bialka = {}
slownik_tluszcze = {}
slownik_dzien = {}
slownik_miesiac = {}
slownik_rok = {}
slownik_nazwa = {}
generator_produktow = ['Jabłko', 'Banan', 'Kiełbasa', 'Masło', 'Kurczak', 'Wołowina', 'Jogurt', 'Majonez',
'Ser', 'Płatki', 'Dżem', 'Śliwka', 'Ananas', 'Parówki', 'Kalafior', 'Pizza', 'Chrzan', 'Olej']
lista = []
class Jedzenie():
def __init__(self,nazwa,dzien,miesiac,rok,wegle,tluszcze,bialka,indeks):
self.węglowodany=wegle
self.bialka=bialka
self.tluszcze=tluszcze
self.nazwa=nazwa
self.indeks=indeks
self.dzien=dzien
self.miesiac=miesiac
self.rok = rok
self.sortowanie=0
def wpisywanie_do_listy(zmiennaindeks):
for b in lista:
if zmiennaindeks == b.indeks:
slownik_wegle[zmiennaindeks] = b.węglowodany
if zmiennaindeks == b.indeks:
slownik_tluszcze[zmiennaindeks] = b.tluszcze
if zmiennaindeks == b.indeks:
slownik_bialka[zmiennaindeks] = b.bialka
if zmiennaindeks == b.indeks:
slownik_nazwa[zmiennaindeks] = b.nazwa
if zmiennaindeks == b.indeks:
slownik_dzien[zmiennaindeks] = b.dzien
if zmiennaindeks == b.indeks:
slownik_miesiac[zmiennaindeks] = b.miesiac
if zmiennaindeks == b.indeks:
slownik_rok[zmiennaindeks] = b.rok
def pasekladowania(procenty):
if procenty < 5:
print(' [# ] '+str(procenty)+'%')
elif procenty < 10:
print(' [## ] '+str(procenty)+'%')
elif procenty < 15:
print(' [### ] '+str(procenty)+'%')
elif procenty < 20:
print(' [#### ] '+str(procenty)+'%')
elif procenty < 25:
print(' [##### ] '+str(procenty)+'%')
elif procenty < 30:
print(' [###### ] '+str(procenty)+'%')
elif procenty < 35:
print(' [####### ] '+str(procenty)+'%')
elif procenty < 40:
print(' [######## ] '+str(procenty)+'%')
elif procenty < 45:
print(' [######### ] '+str(procenty)+'%')
elif procenty < 50:
print(' [########## ] '+str(procenty)+'%')
elif procenty < 55:
print(' [########### ] '+str(procenty)+'%')
elif procenty < 60:
print(' [############ ] '+str(procenty)+'%')
elif procenty < 65:
print(' [############# ] '+str(procenty)+'%')
elif procenty < 70:
print(' [############## ] '+str(procenty)+'%')
elif procenty < 75:
print(' [############### ] '+str(procenty)+'%')
elif procenty < 80:
print(' [################ ] '+str(procenty)+'%')
elif procenty < 85:
print(' [################# ] '+str(procenty)+'%')
elif procenty < 90:
print(' [################## ] '+str(procenty)+'%')
elif procenty < 95:
print(' [################### ] '+str(procenty)+'%')
else:
print(' [####################] '+str(procenty)+'%')
def zapisywanie_do_pliku():
file = open('Dane/nazwa.txt', 'w')
for b in slownik_nazwa:
file.writelines(slownik_nazwa[b])
file.write('\n')
file.close()
file = open('Dane/wegle.txt', 'w')
for b in slownik_wegle:
file.writelines(slownik_wegle[b])
file.write('\n')
file.close()
file = open('Dane/dzien.txt', 'w')
for b in slownik_dzien:
file.writelines(slownik_dzien[b])
file.write('\n')
file.close()
file = open('Dane/miesiac.txt', 'w')
for b in slownik_miesiac:
file.writelines(slownik_miesiac[b])
file.write('\n')
file.close()
file = open('Dane/rok.txt', 'w')
for b in slownik_rok:
file.writelines(slownik_rok[b])
file.write('\n')
file.close()
file = open('Dane/tluszcze.txt', 'w')
for b in slownik_tluszcze:
file.writelines(slownik_tluszcze[b])
file.write('\n')
file.close()
file = open('Dane/bialka.txt', 'w')
for b in slownik_bialka:
file.writelines(slownik_bialka[b])
file.write('\n')
file.close()
indeksfile = open('Dane/indeksy.txt', 'w')
indekszmiennaxdnachwile = str(len(lista))
indeksfile.write(indekszmiennaxdnachwile)
indeksfile.close()
def czyszczeniepliku(nazwapliku):
file = open(nazwapliku, 'w')
file.close()
def wyszukiwanie(poczym):
iloscobiektow = 0
if poczym == 1:
a = str(input('Podaj nazwe: \n'))
for b in lista:
if a == b.nazwa:
print('\nIndeks: ' + str(b.indeks))
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,
'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
iloscobiektow += 1
if poczym ==2:
a = str(input('Podaj dzien: \n'))
d = str(input('Podaj miesiac: \n'))
c = str(input('Podaj rok: \n'))
for b in lista:
if a == b.dzien:
if d == b.miesiac:
if c == b.rok:
print('\nIndeks: ' + str(b.indeks))
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,
'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
iloscobiektow += 1
if poczym ==3:
a = str(input('Podaj Węglowodany: \n'))
for b in lista:
if a == b.węglowodany:
print('\nIndeks: ' + str(b.indeks))
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,
'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
iloscobiektow += 1
if poczym ==4:
a = str(input('Podaj tłuszcze: \n'))
for b in lista:
if a == b.tluszcze:
print('\nIndeks: ' + str(b.indeks))
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,
'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
iloscobiektow += 1
if poczym ==5:
a = str(input('Podaj białka: \n'))
for b in lista:
if a == b.bialka:
print('\nIndeks: ' + str(b.indeks))
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,
'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
iloscobiektow += 1
if poczym ==6:
a = int(input('Podaj indeks: \n'))
for b in lista:
if a == b.indeks:
print('\nIndeks: ' + str(b.indeks))
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,
'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
iloscobiektow += 1
return iloscobiektow
def sortowanie(poczym):
listazmienna=[]
zmienna = 0
i=0
ii=0
if poczym =='wegle':
for b in lista:
if zmienna < int(b.węglowodany) and b.sortowanie==0:
zmienna = int(b.węglowodany)
listazmienna=[b]
elif zmienna == int(b.węglowodany)and b.sortowanie==0:
listazmienna.append(b)
if i == len(lista)-1:
for bb in listazmienna:
for bbb in lista:
if bbb.indeks == bb.indeks:
bbb.sortowanie=1
print('\nIndeks: ' + str(bbb.indeks),'\nNazwa: ' + bbb.nazwa, '\nBiałka: ' + bbb.bialka, '\nTłuszcze: ' + bbb.tluszcze,
'\nWęglowodany: --> ' + bbb.węglowodany,'<--',
'\nData: ' + bbb.dzien + '-' + bbb.miesiac + '-' + bbb.rok, '\n')
i+=1
for b in lista:
if b.sortowanie == 0:
ii=1
if ii>0:
sortowanie('wegle')
if poczym =='tluszcze':
for b in lista:
if zmienna < int(b.tluszcze) and b.sortowanie==0:
zmienna = int(b.tluszcze)
listazmienna=[b]
elif zmienna == int(b.tluszcze)and b.sortowanie==0:
listazmienna.append(b)
if i == len(lista)-1:
for bb in listazmienna:
for bbb in lista:
if bbb.indeks == bb.indeks:
bbb.sortowanie=1
print('\nIndeks: ' + str(bbb.indeks),'\nNazwa: ' + bbb.nazwa, '\nBiałka: ' + bbb.bialka, '\nTłuszcze: --> ' + bbb.tluszcze,'<--',
'\nWęglowodany: ' + bbb.węglowodany,
'\nData: ' + bbb.dzien + '-' + bbb.miesiac + '-' + bbb.rok, '\n')
i+=1
for b in lista:
if b.sortowanie == 0:
ii=1
if ii>0:
sortowanie('tluszcze')
if poczym =='bialka':
for b in lista:
if zmienna < int(b.bialka) and b.sortowanie==0:
zmienna = int(b.bialka)
listazmienna=[b]
elif zmienna == int(b.bialka)and b.sortowanie==0:
listazmienna.append(b)
if i == len(lista)-1:
for bb in listazmienna:
for bbb in lista:
if bbb.indeks == bb.indeks:
bbb.sortowanie=1
print('\nIndeks: ' + str(bbb.indeks),'\nNazwa: ' + bbb.nazwa, '\nBiałka: --> ' + bbb.bialka,'<--', '\nTłuszcze: ' + bbb.tluszcze,
'\nWęglowodany: ' + bbb.węglowodany,
'\nData: ' + bbb.dzien + '-' + bbb.miesiac + '-' + bbb.rok, '\n')
i+=1
for b in lista:
if b.sortowanie == 0:
ii=1
if ii>0:
sortowanie('bialka')
if poczym =='weglerosnaco':
zmienna=10000
for b in lista:
if zmienna > int(b.węglowodany) and b.sortowanie==0:
zmienna = int(b.węglowodany)
listazmienna=[b]
elif zmienna == int(b.węglowodany)and b.sortowanie==0:
listazmienna.append(b)
if i == len(lista)-1:
for bb in listazmienna:
for bbb in lista:
if bbb.indeks == bb.indeks:
bbb.sortowanie=1
print('\nIndeks: ' + str(bbb.indeks),'\nNazwa: ' + bbb.nazwa, '\nBiałka: ' + bbb.bialka, '\nTłuszcze: ' + bbb.tluszcze,
'\nWęglowodany: --> ' + bbb.węglowodany,'<--',
'\nData: ' + bbb.dzien + '-' + bbb.miesiac + '-' + bbb.rok, '\n')
i+=1
for b in lista:
if b.sortowanie == 0:
ii=1
if ii>0:
sortowanie('weglerosnaco')
if poczym =='tluszczerosnaco':
zmienna = 10000
for b in lista:
if zmienna > int(b.tluszcze) and b.sortowanie==0:
zmienna = int(b.tluszcze)
listazmienna=[b]
elif zmienna == int(b.tluszcze)and b.sortowanie==0:
listazmienna.append(b)
if i == len(lista)-1:
for bb in listazmienna:
for bbb in lista:
if bbb.indeks == bb.indeks:
bbb.sortowanie=1
print('\nIndeks: ' + str(bbb.indeks),'\nNazwa: ' + bbb.nazwa, '\nBiałka: ' + bbb.bialka, '\nTłuszcze: --> ' + bbb.tluszcze,'<--',
'\nWęglowodany: ' + bbb.węglowodany,
'\nData: ' + bbb.dzien + '-' + bbb.miesiac + '-' + bbb.rok, '\n')
i+=1
for b in lista:
if b.sortowanie == 0:
ii=1
if ii>0:
sortowanie('tluszczerosnaco')
if poczym =='bialkarosnaco':
zmienna = 10000
for b in lista:
if zmienna > int(b.bialka) and b.sortowanie==0:
zmienna = int(b.bialka)
listazmienna=[b]
elif zmienna == int(b.bialka)and b.sortowanie==0:
listazmienna.append(b)
if i == len(lista)-1:
for bb in listazmienna:
for bbb in lista:
if bbb.indeks == bb.indeks:
bbb.sortowanie=1
print('\nIndeks: ' + str(bbb.indeks),'\nNazwa: ' + bbb.nazwa, '\nBiałka: --> ' + bbb.bialka,'<--', '\nTłuszcze: ' + bbb.tluszcze,
'\nWęglowodany: ' + bbb.węglowodany,
'\nData: ' + bbb.dzien + '-' + bbb.miesiac + '-' + bbb.rok, '\n')
i+=1
for b in lista:
if b.sortowanie == 0:
ii=1
if ii>0:
sortowanie('bialkarosnaco')
<file_sep>/Bazadanych.py
import random
import os
import os.path
from Funkcje_i_zmienne import *
import sys
def main():
if not path.exists('Dane'):
os.system("md Dane")
if not path.exists('KopiaDanych'):
os.system("md KopiaDanych")
if path.exists('Dane/nazwa.txt') and path.exists('Dane/dzien.txt') and path.exists('Dane/miesiac.txt') and path.exists('Dane/rok.txt') and path.exists('Dane/wegle.txt') and path.exists('Dane/tluszcze.txt') and path.exists('Dane/bialka.txt'):
indeksfile = open('Dane/indeksy.txt', 'r')
bgryh=int(indeksfile.readline())
file = open('Dane/nazwa.txt', 'r').read()
file1 = open('Dane/dzien.txt', 'r').read()
file5 = open('Dane/miesiac.txt', 'r').read()
file6 = open('Dane/rok.txt', 'r').read()
file2 = open('Dane/wegle.txt', 'r').read()
file3 = open('Dane/tluszcze.txt', 'r').read()
file4 = open('Dane/bialka.txt', 'r').read()
file = file.split('\n')
file1 = file1.split('\n')
file2 = file2.split('\n')
file3 = file3.split('\n')
file4 = file4.split('\n')
file5 = file5.split('\n')
file6 = file6.split('\n')
listaa=[]
listab=[]
listac=[]
listad=[]
listae=[]
listaf=[]
listag=[]
for line in file:
listaa.append(line)
for line in file1:
listab.append(line)
for line in file2:
listac.append(line)
for line in file3:
listad.append(line)
for line in file4:
listae.append(line)
for line in file5:
listaf.append(line)
for line in file6:
listag.append(line)
i = 0
while i < bgryh:
lista.append(Jedzenie(listaa[i],listab[i],listaf[i],listag[i],listac[i],listad[i],listae[i],i))
i += 1
i = 0
for b in lista:
if i == b.indeks:
slownik_wegle[i] = b.węglowodany
slownik_tluszcze[i] = b.tluszcze
slownik_bialka[i] = b.bialka
slownik_nazwa[i] = b.nazwa
slownik_dzien[i] = b.dzien
slownik_miesiac[i] = b.miesiac
slownik_rok[i] = b.rok
i += 1
else:
czyszczeniepliku('Dane/nazwa.txt')
czyszczeniepliku('Dane/dzien.txt')
czyszczeniepliku('Dane/miesiac.txt')
czyszczeniepliku('Dane/rok.txt')
czyszczeniepliku('Dane/wegle.txt')
czyszczeniepliku('Dane/tluszcze.txt')
czyszczeniepliku('Dane/bialka.txt')
f = open('Dane/indeksy.txt','w')
f.write('0')
f.close()
czyszczeniepliku('KopiaDanych/nazwakopia.txt')
czyszczeniepliku('KopiaDanych/dzienkopia.txt')
czyszczeniepliku('KopiaDanych/miesiackopia.txt')
czyszczeniepliku('KopiaDanych/rokkopia.txt')
czyszczeniepliku('KopiaDanych/weglekopia.txt')
czyszczeniepliku('KopiaDanych/tluszczekopia.txt')
czyszczeniepliku('KopiaDanych/bialkakopia.txt')
f = open('KopiaDanych/indeksykopia.txt','w')
f.write('0')
f.close()
print('Witaj w bazie danych')
while True:
print('Wybierz opcje: \n1.Zapisz dane w bazie \n2.Szukaj danych w bazie \n3.Generownie sztucznych wpisów w bazie danych \n4.Wyświetlanie całej bazy dnych \n5.Czyszczenie bazy danych i reset programu \n6.Tworzenie kopii zapasowej \n7.Przywracanie kopii zapasowej i reset programu \n8.Moduł sortowania \n9.Wyjście ')
menuopcje = input()
os.system("cls")
if menuopcje=='1':
print('--------------------Moduł Zapisywania-------------------')
zmiennaindeks=len(lista)
lista.append(Jedzenie(input('Podaj nazwe: '),input('Podaj dzien: '),input('Podaj miesiac: '),input('Podaj rok: '),input('Podaj wegle: '),input('Podaj tluszcze: '),input('Podaj bialka: '),zmiennaindeks))
wpisywanie_do_listy(zmiennaindeks)
zapisywanie_do_pliku()
os.system("cls")
elif menuopcje=='2':
print('----------------------Moduł Szukania---------------------')
a=int(input('Podaj po czym chcesz wyszukiwać: \n1.Nazwa\n2.Data\n3.Węglowodany\n4.Tłuszcze\n5.Białka\n6.Indeks\n'))
if a !=6:
print('\nIlość obiektów z tą nazwą wynosi: '+str(wyszukiwanie(a))+'\n')
else:
a = int(input('Podaj indeks: \n'))
for b in lista:
if a == b.indeks:
print('Nazwa: ' + b.nazwa, '\nBiałka: ' + b.bialka, '\nTłuszcze: ' + b.tluszcze,'\nWęglowodany: ' + b.węglowodany, '\nData: ' + b.dzien + '-' + b.miesiac + '-' + b.rok, '\n')
zapisywanie_do_pliku()
print(input('\nPress Enter to go back '))
os.system("cls")
elif menuopcje=='8':
for b in lista:
b.sortowanie=0
print('----------------------Moduł Sortowania---------------------')
a = str(input('Wybierz rodzaj sortowania: \n1.Największa wartość\n2.Najmniejsza wartość\n3.Wartości z dnia/miesiąca/roku'))
os.system('cls')
if a == '1':
aa=str(input('Wybierz po jakiej wartosci chcesz sortować: \n1.Białka\n2.Tłuszcze\n3.Węglowodany\n'))
if aa == '1':
sortowanie('bialkarosnaco')
print(input('\nPress Enter to go back '))
os.system("cls")
if aa == '2':
sortowanie('tluszczerosnaco')
print(input('\nPress Enter to go back '))
os.system("cls")
if aa == '3':
sortowanie('weglerosnaco')
print(input('\nPress Enter to go back '))
os.system("cls")
if a == '2':
aa=str(input('Wybierz po jakiej wartosci chcesz sortować: \n1.Białka\n2.Tłuszcze\n3.Węglowodany\n'))
if aa == '1':
sortowanie('bialka')
print(input('\nPress Enter to go back '))
os.system("cls")
if aa == '2':
sortowanie('tluszcze')
print(input('\nPress Enter to go back '))
os.system("cls")
if aa == '3':
sortowanie('wegle')
print(input('\nPress Enter to go back '))
os.system("cls")
if a == '3':
a=str(input('Wybierz opcje: \n1.Wypisz wszystkie produkty z podanej daty\n2.Podaj sumy i średnie poszczególnych wartości z podanej daty \n'))
b = str(input('Podaj rok: '))
c = str(input('\nPodaj miesiac: '))
d = str(input('\nPodaj dzień: \n'))
if a =='1':
os.system('cls')
zmiennailosc=0
for bb in lista:
if b == bb.rok or b=='0':
if c==bb.miesiac or c=='0':
if d==bb.dzien or d=='0':
print('Indeks: ' + str(bb.indeks))
print('Nazwa: ' + bb.nazwa, '\nBiałka: ' + bb.bialka, '\nTłuszcze: ' + bb.tluszcze,
'\nWęglowodany: ' + bb.węglowodany,
'\nData: ' + bb.dzien + '-' + bb.miesiac + '-' + bb.rok, '\n')
zmiennailosc+=1
print('\nIlosc produktów z podanej daty wynosi: '+str(zmiennailosc)+'\n')
print(input('\nPress Enter to go back '))
os.system("cls")
if a == '2':
zmiennailosc = 0
sumawegli = 0
sumatluszczy = 0
sumabialek = 0
os.system('cls')
for bb in lista:
if b == bb.rok or b == '0':
if c == bb.miesiac or c == '0':
if d == bb.dzien or d == '0':
zmiennailosc += 1
sumawegli += int(bb.węglowodany)
sumatluszczy += int(bb.tluszcze)
sumabialek += int(bb.bialka)
print('Ilość produktów: '+str(zmiennailosc)+'\nSuma białek: '+str(sumabialek)+'\nSuma tłuszczy: '+str(sumatluszczy)+'\nSuma węglowodanów: '+str(sumawegli)+'\n')
sredniewegle=sumawegli/zmiennailosc
srednietluszcze=sumatluszczy/zmiennailosc
sredniebialka=sumabialek/zmiennailosc
print('\nŚrednia ilość białek: '+str(sredniebialka)+'\nŚrednia ilość tłuszczy: '+str(srednietluszcze)+'\nŚrednia ilość węglowodanów: '+str(sredniewegle)+'\n')
print(input('\nPress Enter to go back '))
os.system("cls")
elif menuopcje=='3':
a=int(input('Podaj ile chcesz wygenerować sztuczych wpisów w bazie danych: '))
i=0
while i < a:
procentygeneracji=(i/a)*100
procentygeneracji=round(procentygeneracji,2)
os.system("cls")
pasekladowania(procentygeneracji)
zmiennaindeks = len(lista)
lista.append(Jedzenie(generator_produktow[random.randint(0,len(generator_produktow)-1)],str(random.randint(1,31)),str(random.randint(1,12)),str(random.randint(2000,2019)),str(random.randint(1,200)),str(random.randint(1,200)),str(random.randint(1,200)), zmiennaindeks))
wpisywanie_do_listy(zmiennaindeks)
zapisywanie_do_pliku()
i+=1
zapisywanie_do_pliku()
print(input('\nGenerowanie zakonczone sukcesem\nWciśnij enter aby powrocic '))
os.system("cls")
elif menuopcje=='4':
print('---------------------Moduł Szukania po indeksach----------------------')
for b in lista:
print('Indeks: '+str(b.indeks))
print('Nazwa: '+b.nazwa,'\nBiałka: '+b.bialka,'\nTłuszcze: '+b.tluszcze,'\nWęglowodany: '+b.węglowodany,'\nData: '+b.dzien+'-' +b.miesiac+'-' +b.rok,'\n')
print(input('\nPress Enter to go back '))
os.system("cls")
elif menuopcje == '5':
print('----------------------Czyszczenie bazy danych-------------------------')
czyszczeniepliku('Dane/nazwa.txt')
czyszczeniepliku('Dane/dzien.txt')
czyszczeniepliku('Dane/miesiac.txt')
czyszczeniepliku('Dane/rok.txt')
czyszczeniepliku('Dane/wegle.txt')
czyszczeniepliku('Dane/tluszcze.txt')
czyszczeniepliku('Dane/bialka.txt')
file = open('Dane/indeksy.txt', 'w')
file.write('0')
file.close()
break
elif menuopcje == '6':
os.system("Moduł_tworzenia_kopizapasowej.py")
elif menuopcje == '9':
break
elif menuopcje == '7':
os.system('Moduł_wczytywania_kopizapasowej.py')
break
else:
print('Błędna Opcja\n')
<file_sep>/inicjator.py
from Bazadanych import *
main() | 55adbe3cf499257cf65cd44ded0581a237938a3d | [
"Python"
] | 4 | Python | Zefir12/Baza-Danych | 5725842e291d9cc977ff8a9fd7a4152d3a3251eb | 6a100acdf7e2c2893984f6144bd0aac3cf4420d7 |
refs/heads/master | <repo_name>raynesmike/Memory-Vision<file_sep>/src/application/controller/MainController.java
/**
* Application Programming Project
* @author *
* -<NAME>
* -<NAME>
* -<NAME>
* UTSA CS 3443 Application Programming
* Fall 2018
**/
package application.controller;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
/**
*
* @author Algorado
*
*
*/
public class MainController implements Initializable {
@FXML
private VBox vbox;
private Parent fxml;
/**
* initialize method
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TranslateTransition t = new TranslateTransition(Duration.seconds(1), vbox);
// t.setToX(vbox.getLayoutX() * 32);
try {
fxml = FXMLLoader.load(getClass().getResource("../view/SignIn.fxml"));
vbox.getChildren().removeAll();
vbox.getChildren().setAll(fxml);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* Opens sign up
* @param event ActionEvent
*/
@FXML
private void open_signup(ActionEvent event) {
TranslateTransition t = new TranslateTransition(Duration.seconds(1), vbox);
t.setToX(-472);
t.play();
t.setOnFinished((e) -> {
try {
fxml = FXMLLoader.load(getClass().getResource("../view/Tutorial.fxml"));
vbox.getChildren().removeAll();
vbox.getChildren().setAll(fxml);
} catch (IOException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
/**
* open sign in
* @param event ActionEvent
*/
@FXML
private void open_signin(ActionEvent event) {
TranslateTransition t = new TranslateTransition(Duration.seconds(1), vbox);
t.setToX(0);
t.play();
t.setOnFinished((e) -> {
try {
fxml = FXMLLoader.load(getClass().getResource("../view/SignIn.fxml"));
vbox.getChildren().removeAll();
vbox.getChildren().setAll(fxml);
} catch (IOException ex) {
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
}
<file_sep>/src/application/model/Code.java
/**
* Application Programming Project
* @author *
* -<NAME>
* -<NAME>
* -<NAME>
* UTSA CS 3443 Application Programming
* Fall 2018
**/
package application.model;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Creates Code object
* @author Algorado
*
*/
public class Code {
private String codes;
private int startAddress;
private int curAddress;
private Table table;
//public static ArrayList<codes>functions;
/**
* Constructor
*/
public Code() {
this.startAddress=1000;
this.curAddress=1000;
this.codes = null;
this.table = new Table();
}
/**
* reads strings, parse them, and store them in an arraylist, line per line
* @param codeString String
* @return wholeCode ArrayList<String>
*/
public ArrayList<String> readCode( String codeString ) {
this.codes = codeString;
ArrayList<String> wholeCode = new ArrayList<String>();
@SuppressWarnings("resource")
Scanner scan = new Scanner(codeString);
while( scan.hasNextLine() ) {
String line = scan.nextLine();
wholeCode.add( line );
this.readPerLine( line );
//System.out.println( line );
}
return wholeCode;
}
/**
* Reading the code and defines types
* @param line String
*/
public void readPerLine( String line ) {
String[] word =line.split(" ");
int addSize = 0;
int curAdd;
int prevAdd = curAddress;
// add the variables being classified.
switch(word[0]){
case "int":
//System.out.print(word[0]);
addSize=4;
curAddress = table.classifyLine(line, curAddress, addSize, 1);
curAdd = curAddress;
while ((curAdd - prevAdd) % 4 != 0 ) {
curAdd ++;
}
curAddress=curAdd;
break;
case "char":
//System.out.println(word[0]);
addSize=1;
curAddress = table.classifyLine(line, curAddress, addSize, 2);
curAdd = curAddress;
while ((curAdd - prevAdd) % 4 != 0 ) {
curAdd ++;
}
curAddress=curAdd;break;
case "float":
//System.out.println(word[0]);
addSize=8;
curAddress= table.classifyLine(line, curAddress, addSize, 3);
curAdd = curAddress;
while ((curAdd - prevAdd) % 4 != 0 ) {
curAdd ++;
}
curAddress=curAdd;
break;
case "double":
//System.out.println(word[0]);
addSize=8;
curAddress = table.classifyLine(line, curAddress, addSize, 4);
curAdd = curAddress;
while ((curAdd - prevAdd) % 4 != 0 ) {
curAdd ++;
}
curAddress=curAdd;
break;
default: // actions
table.modify(line);
break;
}
}
/**
* Save button
* @param fileName String
* @param userString String
* @return true
* @throws FileNotFoundException FileNotFoundException
*/
public Boolean save(String fileName, String userString) throws FileNotFoundException {
FileOutputStream file = new FileOutputStream(fileName, false);
PrintWriter outFile = new PrintWriter( file );
outFile.println(userString);
outFile.close();
return true;
}
/**
* Will load code
* @param filename String
* @return data ArrayList<String>
* @throws IOException IOException
*/
public static ArrayList<String> loadCode(String filename) throws IOException {
//File file = new File(fileName);
File file = new File(filename);
Scanner scan = new Scanner(file);
ArrayList<String> data = new ArrayList<String>();
while(scan.hasNext()) {
String line = scan.nextLine();
data.add(line);
}
//System.out.println(data);
scan.close();
return data;
}
/**
* getter method
* @return codes String
*/
public String getCodes() {
return codes;
}
/**
* setter method
* @param codes String
*/
public void setCodes(String codes) {
this.codes = codes;
}
/**
* getter method
* @return startAddress
*/
public int getStartAddress() {
return startAddress;
}
/**
* setter method
* @param startAddress String
*/
public void setStartAddress(int startAddress) {
this.startAddress = startAddress;
}
/**
* getter method
* @return curAddress int
*/
public int getCurAddress() {
return curAddress;
}
/**
* setter method
* @param curAddress String
*/
public void setCurAddress(int curAddress) {
this.curAddress = curAddress;
}
/**
* getter method
* @return table Table
*/
public Table getTable() {
return table;
}
/**
* setter method
* @param table Tavle
*/
public void setTable(Table table) {
this.table = table;
}
}
<file_sep>/src/application/controller/components/VNode.java
package application.controller.components;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.jfoenix.controls.JFXButton;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Point2D;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.CubicCurve;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
/**
* visualizes how memory is connected
* @author Algorado
*
*
*/
public class VNode extends StackPane {
@FXML private StackPane root_pane;
@FXML private Circle port;
@FXML private JFXButton btnVariable;
@FXML private JFXButton btnValue;
@FXML private JFXButton btnAddress;
@FXML private JFXButton btnType;
private Point2D mDragOffset = new Point2D (0.0, 0.0);
private final VNode self;
private AnchorPane right_pane = null;
private final List <String> mLinkIds = new ArrayList <String> ();
/**
* Constructor
*/
public VNode() {
FXMLLoader fxmlLoader = new FXMLLoader(
getClass().getResource("../view/VNode.fxml")
);
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
self = this;
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
//provide a universally unique identifier for this object
setId(UUID.randomUUID().toString());
}
/**
* set-up
* @return port.localToScene(Point2D.ZERO)
*/
public Point2D portCoordinates() {
//port.localToScene(port.layoutBounds.minX, port.layoutBounds.minY);
return port.localToScene(Point2D.ZERO);
//Point2D localCoords = getParent().sceneToLocal(p);
}
// GETTERS & SETTERS
/**
* set-up for cubic curve
* @param source VNode
* @param target target
* @return curve
*/
private CubicCurve createPointerLink(VNode source, VNode target) {
CubicCurve curve = new CubicCurve();
curve.setStartX(source.getLayoutX());
curve.setStartY(source.getLayoutY()+10);
curve.setControlX1(source.getLayoutX() - 40);
curve.setControlY1(source.getLayoutY()+10);
curve.setControlX2(target.getLayoutX() - 40);
curve.setControlY2(target.getLayoutY()+10);
curve.setEndX(target.getLayoutX());
curve.setEndY(target.getLayoutY()+10);
curve.setSmooth(true);
curve.setStroke(Color.BLACK);
curve.setStrokeWidth(3);
curve.setFill(null);
curve.setStrokeLineCap(StrokeLineCap.ROUND);
return curve;
}
/**
* Creates an arrow pointing to the pointer link's target
* @param pointerLink
* @return arrowEnd
*/
private Path createArrowHead(CubicCurve pointerLink) {
double size=Math.max(pointerLink.getBoundsInLocal().getWidth(),
pointerLink.getBoundsInLocal().getHeight());
double scale=size/4d;
Point2D ori=eval(pointerLink, 1);
Point2D tan=evalDt(pointerLink, 1).normalize().multiply(scale);
Path arrowEnd=new Path();
arrowEnd.getElements().add(new MoveTo(ori.getX()-0.2*tan.getX()-0.2*tan.getY(),
ori.getY()-0.2*tan.getY()+0.2*tan.getX()));
arrowEnd.getElements().add(new LineTo(ori.getX(), ori.getY()));
arrowEnd.getElements().add(new LineTo(ori.getX()-0.2*tan.getX()+0.2*tan.getY(),
ori.getY()-0.2*tan.getY()-0.2*tan.getX()));
arrowEnd.setStrokeLineCap(StrokeLineCap.ROUND);
arrowEnd.setStrokeWidth(3);
arrowEnd.setStrokeLineJoin(StrokeLineJoin.ROUND);
return arrowEnd;
}
/**
* This is a utility method for arrow generation
* Evaluate the cubic curve at a parameter 0<=t<=1, returns a Point2D
* @param c the CubicCurve
* @param t param between 0 and 1
* @return a Point2D
*/
private Point2D eval(CubicCurve c, float t){
Point2D p=new Point2D(Math.pow(1-t,3)*c.getStartX()+
3*t*Math.pow(1-t,2)*c.getControlX1()+
3*(1-t)*t*t*c.getControlX2()+
Math.pow(t, 3)*c.getEndX(),
Math.pow(1-t,3)*c.getStartY()+
3*t*Math.pow(1-t, 2)*c.getControlY1()+
3*(1-t)*t*t*c.getControlY2()+
Math.pow(t, 3)*c.getEndY());
return p;
}
/**
* This is a utility method for arrow generation
* Evaluate the tangent of the cubic curve at a parameter 0<=t<=1, returns a Point2D
* @param c the CubicCurve
* @param t param between 0 and 1
* @return a Point2D
*/
private Point2D evalDt(CubicCurve c, float t){
Point2D p=new Point2D(-3*Math.pow(1-t,2)*c.getStartX()+
3*(Math.pow(1-t, 2)-2*t*(1-t))*c.getControlX1()+
3*((1-t)*2*t-t*t)*c.getControlX2()+
3*Math.pow(t, 2)*c.getEndX(),
-3*Math.pow(1-t,2)*c.getStartY()+
3*(Math.pow(1-t, 2)-2*t*(1-t))*c.getControlY1()+
3*((1-t)*2*t-t*t)*c.getControlY2()+
3*Math.pow(t, 2)*c.getEndY());
return p;
}
/**
* getter method
* @return btnVariable String
*/
public JFXButton getVariable() {
return btnVariable;
}
/**
* setter method
* @param variableName String
*/
public void setVariable(String variableName) {
this.btnVariable.setText(variableName);
}
/**
* getter method
* @return btnValue String
*/
public JFXButton getValue() {
return btnValue;
}
/**
* setter method
* @param btnValue String
*/
public void setValue(String value) {
btnValue.setText(value);
}
/**
* getter method
* @return btnAddress String
*/
public JFXButton getAddress() {
return btnAddress;
}
/**
* setter method
* @param address String
*/
public void setAddress(String address) {
btnAddress.setText(address);
}
/**
* getter method
* @return btnType String
*/
public JFXButton getType() {
return btnType;
}
/**
* setter method
* @param type String
*/
public void setType(String type) {
btnType.setText(type);;
}
}<file_sep>/src/application/model/PopulateTable.java
package application.model;
import javafx.beans.property.SimpleStringProperty;
/**
* populates the table
* @author Algorado
*
*/
public class PopulateTable {
private final SimpleStringProperty name;
/**
* Constructor
* @param name String
*/
public PopulateTable(String name) {
super();
this.name = new SimpleStringProperty(name);
}
/**
* getter method
* @return name.get()
*/
public String getName() {
return name.get();
}
}<file_sep>/src/application/controller/SignInController.java
/**
* Application Programming Project
* @author *
* -<NAME>
* -<NAME>
* -<NAME>
* UTSA CS 3443 Application Programming
* Fall 2018
**/
package application.controller;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import application.model.PopulateTable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
/**
*
* @author Algorado
* Responsible for Sign In
*
*/
public class SignInController implements Initializable {
@FXML
private TableColumn<PopulateTable, String> colName;
@FXML // fx:id="Table1"
private TableView<PopulateTable> fileTable; // Value injected by FXMLLoader
@FXML
private JFXButton btnOK, btnCancel, btnNewProject, btnLaunch;
@FXML
private JFXTextField txtName;
String fileName;
String newProjectName;
public static String filePath = "data/";
public ObservableList<PopulateTable> fileList = FXCollections.observableArrayList();
/**
* Helps with signIn
* @param event ActionEvent
*/
public void SignIn(ActionEvent event) {
PopulateTable selectedFile;
selectedFile = fileTable.getSelectionModel().getSelectedItem();
filePath += selectedFile.getName() + ".txt";
try {
Parent memoryMapParent = FXMLLoader.load(getClass().getResource("../view/MemoryMap.fxml"));
Scene memoryMapScene = new Scene(memoryMapParent);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(memoryMapScene);
window.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Initialize method
*/
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
btnLaunch.setVisible(false);
fileTable.getStylesheets().add(MemoryMapController.class.getResource("../view/filetable.css").toExternalForm());
txtName.setVisible(false);
btnCancel.setVisible(false);
btnOK.setVisible(false);
loadFiles();
colName.setCellValueFactory(new PropertyValueFactory<PopulateTable, String>("name"));
fileTable.setItems(fileList);
// reveal option to launch if a project is selected
fileTable.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
btnLaunch.setVisible(true);
} else {
btnLaunch.setVisible(false);
}
});
}
/**
* loads files
*/
public void loadFiles() {
File folder = new File("data");
File[] fList = folder.listFiles();
// loads each .txt file in 'data' folder to the table
for (File file : fList) {
if (file.isFile()) {
if (file.getName().endsWith(".txt")) {
fileList.add(new PopulateTable(file.getName().replaceFirst("[.][^.]+$", "")));
}
}
}
}
/**
* aids with choosing different files
* @param event ActionEvent
*/
public void chooseFile(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File("data"));
fileChooser.setTitle("Choose a file");
fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Text Files", "*.txt"));
File selectedFile = fileChooser.showOpenDialog(new Stage());
if (selectedFile != null) {
String fileName = selectedFile.getName();
fileTable.getItems().add(new PopulateTable(fileName));
}
}
/**
* button settings
* @param event ActionEvent
*/
public void NewProject(ActionEvent event) {
btnOK.setVisible(true);
btnCancel.setVisible(true);
txtName.setVisible(true);
fileTable.getSelectionModel().clearSelection();
btnLaunch.setVisible(false);
btnNewProject.setVisible(false);
}
/**
* confirm
* @param event ActionEvent
*/
public void Confirm(ActionEvent event) {
newProjectName = txtName.getText();
List<String> lines = Arrays.asList("int newProject = 1;", "int *p = &newProject;");
Path file = Paths.get("data/"+txtName.getText()+".txt");
try {
Files.write(file, lines, Charset.forName("UTF-8"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
fileList.add(new PopulateTable(newProjectName));
fileTable.setItems(fileList);
Cancel(event);
//SignIn(event);
}
/**
* Cancel
* @param event ActionEvent
*/
public void Cancel(ActionEvent event) {
btnOK.setVisible(false);
btnCancel.setVisible(false);
txtName.setVisible(false);
btnNewProject.setVisible(true);
}
/**
* Helps with save
* @param filePath String
* @param text String
*/
public void save(String filePath, String text) {
try {
write(new File(filePath), text);
} catch (IOException ex) {
}
}
/**
* helps with writing code
* @param file File
* @param text String
* @throws IOException IOException
*/
private void write(File file, String text) throws IOException {
file.getParentFile().mkdirs();
try (FileWriter fw = new FileWriter(file); PrintWriter pw = new PrintWriter(fw)) {
pw.print(text.trim());
pw.close();
fw.close();
}
}
}
<file_sep>/README.md
# MemoryVision
> Algorado - Fall 2018
> Members:
> <NAME>
> <NAME>
> <NAME>
Memory Vision helps students and educators easily visualize how computer memory works in the C language by generating a custom memory map.
##Login
-On starting our program. you'll see a table with example1 and example2 in it. You could select one of these with pre-prepared code and launch it, or create your own file and launch it
## Bugs
- No X button on Mac and linux, can't close and can't resize window.
- Some words on some buttons are shortened Ex.) Varia... instead of Variable
- If you zoom in too much (it flips it), it causes UI problems, No limit to zooming
- The User Rules lists limitations of the program to help the user avoid errors.
- The Choose file button is under construction.
## Dependencies
-This project requires Java 8, it won't work with Java 10. Editing the .fxml files requires SceneBuilder 8.5.0.
# Memory-Vision
This is a group project for Application Programming with Tyler and Jamal that will read a C program line per line and track the variable's value including pointers
<file_sep>/src/application/controller/MemoryMapController.java
/**
* Application Programming Project
* @author *
* -<NAME>
* -<NAME>
* -<NAME>
* UTSA CS 3443 Application Programming
* Fall 2018
**/
package application.controller;
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.net.URL;
import java.time.Duration;
import java.util.ResourceBundle;
import java.util.function.IntFunction;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
import org.reactfx.Subscription;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialog;
import com.jfoenix.controls.JFXDialogLayout;
import com.jfoenix.controls.JFXToggleNode;
import application.controller.components.CodeArrowFactory;
import application.controller.components.PanPane;
import application.model.C;
import application.model.Code;
import application.model.Variable;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.BoxBlur;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import com.jfoenix.controls.events.JFXDialogEvent;
/**
* Responsible for MemoryMap.fxml
* @author Algorado
*
*/
public class MemoryMapController implements Initializable {
@FXML
private TableView<Variable> table;
@FXML
private TableColumn<Variable, String> variableCol;
@FXML
private TableColumn<Variable, Integer> addressCol;
@FXML
private TableColumn<Variable, String> valueCol;
@FXML
private JFXButton generateB;
@FXML
private TextArea codeTextArea;
@FXML
private Label lineLabel;
@FXML
private VBox nbox;
@FXML
private AnchorPane anchor_root;
@FXML
private StackPane stackPane;
@FXML
private PanPane panPane;
@FXML
private Pane editor;
@FXML
private Stage stage;
@FXML
private HBox hbSettings;
@FXML
private Label statusL;
@FXML
JFXToggleNode btnHelp;
@FXML
JFXButton nextB;
@FXML
JFXButton anotherB;
@FXML
CodeArea codeArea;
@FXML
Pane pane;
@FXML
Circle circleStart;
@FXML
Circle circleEnd;
@FXML
FontAwesomeIcon helpIcon;
private C syntaxH;
private Code code;
private ObservableList<Variable> variableList, emptyTable;
private int index = 0;
private String[] line;
int lineNumber;
String defaultCode;
/**
* Generate button
*/
public void generate() {
nextB.setDisable(false);
generateB.setDisable(true);
clear();
variableList = FXCollections.observableArrayList();
Variable empty = new Variable("Starting ...", 0, "Empty", 0, 0);
emptyTable = FXCollections.observableArrayList();
emptyTable.add(empty);
String codeString = codeArea.getText();
line = codeString.split("\\n");
table.setItems(emptyTable);
}
/**
* button with "Choose another program" is clicked, switch to signin scene
* @param e ActionEvent
*/
public void anotherClicked(ActionEvent e) {
SignInController.filePath = "data/";
Parent pot;
try {
pot = FXMLLoader.load(getClass().getResource("../view/Signin.fxml"));
Scene sceneW = new Scene(pot);
Stage window = (Stage) (((Node) e.getSource()).getScene().getWindow());
window.setScene(sceneW);
window.show();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
/**
* save button
* @param event ActionEvent
*/
public void handle_save(ActionEvent event) {
save(SignInController.filePath, codeArea.getText());
}
/**
* Handles loading
*/
public void handle_load() {
generateB.setDisable(false);
nextB.setDisable(true);
String codeText = "";
codeArea.clear();
try (BufferedReader br = new BufferedReader(new FileReader(SignInController.filePath))) {
while (br.ready()) {
codeText += br.readLine() + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
codeArea.replaceText(codeText.trim());
clear();
}
/**
* Dialog Button
* @param event ActionEvent
*/
public void loadDialog(ActionEvent event) {
if (btnHelp.isDisable() == false) {
BoxBlur blur = new BoxBlur(3, 3, 3);
JFXDialogLayout content = new JFXDialogLayout();
content.setHeading(new Text("User Rules"));
content.setBody(new Text("- Only initialization and modification statements\n"
+ "- Pointers can only be initialized, no Modifying\n"
+ "- No functions, printf statements, File IO, etc\n" + "- NO COMMENTS!\n"
+ "- Single Space between words\n"
+ "- \"x++\" and \"x--\" must be one string (NO SPACES between them)\n" + "- NO +=, -=, *=, /=\n"
+ "- Please enter correct C code, while we do check for some errors, we aren't garbage collectors\n"
+ "- Only Addition and Subtraction!\n"));
StackPane dialogStackPane = new StackPane();
JFXDialog dialog = new JFXDialog(dialogStackPane, content, JFXDialog.DialogTransition.CENTER, true);
JFXButton btnDone = new JFXButton("Done");
btnDone.addEventHandler(ActionEvent.ACTION, (e) -> {
dialog.close();
});
anchor_root.getChildren().add(dialogStackPane);
content.setActions(btnDone);
AnchorPane.setTopAnchor(dialogStackPane, (editor.getHeight() - content.getPrefHeight()) / 3);
AnchorPane.setLeftAnchor(dialogStackPane, (editor.getWidth() - content.getPrefWidth()) / 3);
dialog.show();
dialog.setOnDialogClosed((JFXDialogEvent event1) -> {
editor.setEffect(null);
pane.setEffect(null);
btnHelp.setDisable(false);
btnHelp.setSelected(false);
});
// blurs background
editor.setEffect(blur);
pane.setEffect(blur);
btnHelp.setDisable(true);
}
}
/**
* next button
*/
public void next() {
// disable user input
generateB.setDisable(true);
codeArea.setDisable(true);
// creates arrow indicator to left of code line
IntFunction<Node> numberFactory = LineNumberFactory.get(codeArea);
IntFunction<Node> arrowFactory = new CodeArrowFactory(codeArea.currentParagraphProperty());
IntFunction<Node> graphicFactory = codeLine -> {
HBox hbox = new HBox(numberFactory.apply(codeLine), arrowFactory.apply(codeLine));
hbox.setAlignment(Pos.CENTER_LEFT);
return hbox;
};
codeArea.setParagraphGraphicFactory(graphicFactory);
// step through lines of code until end;
if (index < codeArea.getParagraphs().size()) {
code.readCode(line[index]);
index++;
variableList.removeAll(code.getTable().getVariableList());
variableList.addAll(code.getTable().getVariableList());
codeArea.moveTo(index, 0);
lineNumber++;
table.setItems(variableList);
}
if (index == codeArea.getParagraphs().size()) {
generateB.setDisable(false);
nextB.setDisable(true);
codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
}
}
/**
* clear button
*/
public void clear() {
// codeArea.clear();
index = 0;
codeArea.setDisable(false);
generateB.setDisable(false);
codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
code = new Code();
table.getItems().clear();
}
/**
* Initialize method
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
nextB.setDisable(true);
// Creates and positions help button
btnHelp = new JFXToggleNode();
btnHelp.setGraphic(helpIcon);
btnHelp.setLayoutX(helpIcon.getLayoutX() + 35);
btnHelp.setLayoutY(helpIcon.getLayoutY() - 15);
hbSettings.getChildren().add(btnHelp);
//anchor_root.getChildren().add(btnHelp);
btnHelp.setOnAction(this::loadDialog);
// removes the table's default message
table.setPlaceholder(new Label(""));
// removes horizonal table scroll bar
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// links table.css to the table
table.getStylesheets().add(MemoryMapController.class.getResource("../view/table.css").toExternalForm());
// default/demonstration code
defaultCode = "int v[] = {20, 30, 40};\n" + "int x = 20;\n" + "int y = 30;\n" + "char a[] = {'a', 'b', 'c'};\n"
+ "x = 20 + 30;\n" + "y = x + 50;\n" + "v[1] = 20 + 30;\n" + "v[2] = v[1] + 50;\n"
+ "char name = 'r';\n" + "char last = 'z';\n" + "name = last;\n" + "v[0]++;\n" + "int *p = &x;";
PanPane panPane = new PanPane(pane);
anchor_root.getChildren().add(panPane);
// send panPane to back
anchor_root.getChildren().get(anchor_root.getChildren().size() - 1).toBack();
panPane.setStyle("-fx-background-color: #ffffff");
codeArea = new CodeArea();
codeArea.setId("codeArea");
syntaxH = new C();
codeArea.setLayoutX(0);
codeArea.setLayoutY(0);
codeArea.setPrefSize(325, 425);
// adds line numbers to left of area
codeArea.setParagraphGraphicFactory(LineNumberFactory.get(codeArea));
codeArea.setStyle("-fx-font-size:16px");
codeArea.setEffect(new DropShadow(3, 0, 1, Color.BLACK));
// recomputes syntax highlighting 500ms after user enters text
@SuppressWarnings("unused")
Subscription cleanupWhenNoLongerNeedIt = codeArea.multiPlainChanges().successionEnds(Duration.ofMillis(500))
.subscribe(ignore -> codeArea.setStyleSpans(0, syntaxH.computeHighlighting(codeArea.getText())));
codeArea.replaceText(0, 0, defaultCode);
code = new Code();
variableCol.setCellValueFactory(new PropertyValueFactory<>("variable"));
addressCol.setCellValueFactory(new PropertyValueFactory<>("address"));
valueCol.setCellValueFactory(new PropertyValueFactory<>("value"));
codeArea.getStylesheets().add(MemoryMapController.class.getResource("../view/c.css").toExternalForm());
editor.getChildren().add(codeArea);
System.out.println(codeArea.getText().trim());
handle_load();
}
/**
* saves the code
* @param filePath String
* @param text String
*/
public void save(String filePath, String text) {
try {
write(new File(filePath), text);
} catch (IOException ex) {
}
}
/**
* writes the code
* @param file File
* @param text String
* @throws IOException IOException
*/
private void write(File file, String text) throws IOException {
file.getParentFile().mkdirs();
try (FileWriter fw = new FileWriter(file); PrintWriter pw = new PrintWriter(fw)) {
pw.print(text.trim());
pw.close();
fw.close();
}
}
}
| 460a611784ef5e8f78fb44cc5a67763a6be6e30d | [
"Markdown",
"Java"
] | 7 | Java | raynesmike/Memory-Vision | ec6d14c5be49580a5c01363c889cc3d52ed5a4be | 46b1bfd556154b6cb3fdcc6d840d4922ba8cc6ef |
refs/heads/master | <repo_name>Ruben-Castillo/aumento_precios<file_sep>/aumento_precios.rb
def aumentar_precio(array,multiplicador)
result=[]
n=array.count
n.times do |i|
result.push(array[i]*multiplicador)
end
result
end
print aumentar_precio([2000,1000,5000,350,299],1.2) | 2ebeb862b765e99474f86425274758d14e3a97ea | [
"Ruby"
] | 1 | Ruby | Ruben-Castillo/aumento_precios | 490eef144062dbb17df0e98843b65a68fa94af94 | 35e3b50a1afe446019587bcc4ff57d194e980a09 |
refs/heads/master | <repo_name>AlexanderKapitanovski/QuickInfo<file_sep>/src/QuickInfo/Processors/Converters/Base64String.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using static QuickInfo.NodeFactory;
namespace QuickInfo.Processors.Converters
{
class Base64String : IProcessor
{
public object GetResult(Query query)
{
string base64String = query.OriginalInput;
byte[] data = null;
if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
|| base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
{
return null;
}
if (!Regex.IsMatch(base64String, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None))
{
return null;
}
try
{
data = System.Convert.FromBase64String(base64String);
}
catch (Exception)
{
return null;
}
if (data != null)
{
var pairs = new List<(string, string)>
{
("UTF8:", Encoding.UTF8.GetString(data)),
("ASCI:", Encoding.ASCII.GetString(data)),
("Byte[]:", BitConverter.ToString(data))
};
return NameValueTable(null, right => right.Style = "Fixed", pairs.ToArray());
}
return null;
}
}
}
| 1b8afef14d2b24e64e682b38d518e9bd08c04ed7 | [
"C#"
] | 1 | C# | AlexanderKapitanovski/QuickInfo | a66d5e3091bafaf5c55a8700fa62a4874bc55b34 | 7d80be66961685ae795bd7ba8d343ff046b87cd0 |
refs/heads/master | <repo_name>oceanscott/hound<file_sep>/hound.php
<?php
class hound{
public function getCurrentQuote()
{
require('phpQuery-onefile.php');
$currentDay = date("Y-m-d");
var_dump($currentDay);
$this->getGoldQuote($Quote, $currentDay);
$this->getRate($Quote, $currentDay);
/*
require('phpQuery-onefile.php');
$url = "http://www.xe.com/currencytables/?from=XAU&date=2016-09-29";
$content = file_get_contents($url);
//$usdollar = substr($content , , $length )
//var_dump($content);
//var_dump($doc);
$doc = phpQuery::newDocumentHTML($content);
//var_dump(strpos($doc,'historicalRateTable'));
$temp_US = substr($doc, strpos($doc, 'US Dollar', strpos($doc, 'historicalRateTable-wrap'))+0, 100);
$Quote['US_Gold'] = substr($temp_US, strpos($temp_US, "\">")+2 , strpos($temp_US, "<", strpos($temp_US, "\">")) - strpos($temp_US, "\">") - 2);
$temp_JP = substr($doc, strpos($doc, 'Japanese Yen', strpos($doc, 'historicalRateTable-wrap'))+0, 100);
$Quote['JP_Gold'] = substr($temp_JP, strpos($temp_JP, "\">")+2 , strpos($temp_JP, "<", strpos($temp_JP, "\">")) - strpos($temp_JP, "\">") - 2);
var_dump($Quote['US_Gold']);
var_dump($Quote['JP_Gold']);
//$usd = pq($doc)->find('US Dollar');
//<div class="historicalRateTable-wrap">
//var_dump($usd);
phpQuery::$documents = array();
*/
//$article_title = pq('h2',$article)->text();
return $Quote;
//var_dump($article);
}
public function getGoldQuote(&$Quote, $date)
{
//$currentDay = date("Y-m-d");
//var_dump($currentDay);
$url = "http://www.xe.com/currencytables/?from=XAU&date=".$date;
$content = file_get_contents($url);
//$usdollar = substr($content , , $length )
//var_dump($content);
//var_dump($doc);
$doc = phpQuery::newDocumentHTML($content);
//var_dump(strpos($doc,'historicalRateTable'));
$temp_US = substr($doc, strpos($doc, 'US Dollar', strpos($doc, 'historicalRateTable-wrap'))+0, 100);
$Quote['US_Gold'] = substr($temp_US, strpos($temp_US, "\">")+2 , strpos($temp_US, "<", strpos($temp_US, "\">")) - strpos($temp_US, "\">") - 2);
$temp_JP = substr($doc, strpos($doc, 'Japanese Yen', strpos($doc, 'historicalRateTable-wrap'))+0, 100);
$Quote['JP_Gold'] = substr($temp_JP, strpos($temp_JP, "\">")+2 , strpos($temp_JP, "<", strpos($temp_JP, "\">")) - strpos($temp_JP, "\">") - 2);
var_dump($Quote['US_Gold']);
var_dump($Quote['JP_Gold']);
//$usd = pq($doc)->find('US Dollar');
//<div class="historicalRateTable-wrap">
//var_dump($usd);
phpQuery::$documents = array();
}
public function getRate(&$Quote, $date)
{
$url = "http://www.xe.com/currencytables/?from=JPY&date=".$date;
$content = file_get_contents($url);
//$usdollar = substr($content , , $length )
//var_dump($content);
//var_dump($doc);
$doc = phpQuery::newDocumentHTML($content);
//var_dump(strpos($doc,'historicalRateTable'));
//$temp_US = substr($doc, strpos($doc, 'US Dollar', strpos($doc, 'historicalRateTable-wrap'))+0, 100);
//$Quote['US_Gold'] = substr($temp_US, strpos($temp_US, "\">")+2 , strpos($temp_US, "<", strpos($temp_US, "\">")) - strpos($temp_US, "\">") - 2);
$temp_USDJPY = substr($doc, strpos($doc, 'US Dollar', strpos($doc, 'historicalRateTable-wrap'))+0, 138);
//var_dump($temp_USDJPY);
$Quote['JPYUSD'] = substr($temp_USDJPY, strpos($temp_USDJPY, "\">")+2, strpos($temp_USDJPY, "<", strpos($temp_USDJPY, "\">")) - strpos($temp_USDJPY, "\">") - 2);
//var_dump(strrpos($temp_USDJPY, "\">"));
$Quote['USDJPY'] = substr($temp_USDJPY, strrpos($temp_USDJPY, "\">")+2, strrpos($temp_USDJPY, "<", strrpos($temp_USDJPY, "\">")) - strrpos($temp_USDJPY, "\">") - 2);
var_dump($Quote['JPYUSD']);
var_dump($Quote['USDJPY']);
$temp_TWDJPY = substr($doc, strpos($doc, 'Taiwan New Dollar', strpos($doc, 'historicalRateTable-wrap'))+0, 145);
var_dump($temp_TWDJPY);
$Quote['JPYTWD'] = substr($temp_TWDJPY, strpos($temp_TWDJPY, "\">")+2, strpos($temp_TWDJPY, "<", strpos($temp_TWDJPY, "\">")) - strpos($temp_TWDJPY, "\">") - 2);
//var_dump(strrpos($temp_USDJPY, "\">"));
$Quote['TWDJPY'] = substr($temp_TWDJPY, strrpos($temp_TWDJPY, "\">")+2, strrpos($temp_TWDJPY, "<", strrpos($temp_TWDJPY, "\">")) - strrpos($temp_TWDJPY, "\">") - 2);
var_dump($Quote['JPYUSD']);
var_dump($Quote['USDJPY']);
//var_dump($Quote['JP_Gold']);
//$usd = pq($doc)->find('US Dollar');
//<div class="historicalRateTable-wrap">
//var_dump($usd);
phpQuery::$documents = array();
}
public function getQuoteAt($date)
{
var_dump($date); //$date = "2016-10-10";
$this->getGoldQuote($Quote, $date);
$this->getRate($Quote, $date);
return $Quote;
}
}
?> | 9777bb524344cf49f8b8de038d8d2d959ca0503a | [
"PHP"
] | 1 | PHP | oceanscott/hound | 858e7049293d75bf8e5f0ab27daf4612be8533f1 | 16b934e3aa97187e7229ff743657e9db3f80cda8 |
refs/heads/plinioleitecosta | <file_sep>package controller;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import repository.UsuarioRepository;
import model.Usuario;
@Named
@ViewScoped
public class SelectVendedor implements Serializable
{
@Inject
private UsuarioRepository vendedorRep;
private static final long serialVersionUID = 1L;
private String nome;
private List<Usuario> vendedoresFiltrados;
public void inicializar()
{
vendedoresFiltrados = vendedorRep.todos();
}
public void pesquisar()
{
System.out.println("Texto Vendedor Método SlectVendedor.pesquisar "+this.nome);
vendedoresFiltrados = vendedorRep.porNomeVendedor(this.nome);
}
public void abrirDlgVendedor()
{
Map<String, Object> opcoes = new HashMap<>();
opcoes.put("modal", true);
opcoes.put("resizable", false);
opcoes.put("contentHeight", 470);
RequestContext.getCurrentInstance().openDialog("/usuario/dlgConsultaVendedor.jsf", opcoes, null);
}
public void selecionar(Usuario vendedor)
{
RequestContext.getCurrentInstance().closeDialog(vendedor);
}
public String getNome()
{
return nome;
}
public void setNome(String nome)
{
this.nome = nome;
}
public List<Usuario> getVendedoresFiltrados()
{
return vendedoresFiltrados;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
}
<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>br.com.plcsistemas.exodo</groupId>
<artifactId>Exodo</artifactId>
<version>1.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<hibernate.version>3.5.4-Final</hibernate.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security JSP Taglib -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<!-- Hibernate Entity Manager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-proxool</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-infinispan</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<!-- x (implementação do CDI) -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
<version>2.0.4.Final</version>
<scope>compile</scope>
</dependency>
<!-- Implementacao do Bean Validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
<scope>compile</scope>
</dependency>
<!-- Núcleo do Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.3.Final</version>
<scope>compile</scope>
</dependency>
<!-- Implementação de EntityManager da JPA -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.3.Final</version>
<scope>compile</scope>
</dependency>
<!-- Mojarra (implementação do JSF 2) -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.1.22</version>
<scope>compile</scope>
</dependency>
<!-- OmineFaces ( Utilitários para JSF ) -->
<dependency>
<groupId>org.omnifaces</groupId>
<artifactId>omnifaces</artifactId>
<version>1.5</version>
<scope>compile</scope>
</dependency>
<!-- PrimeFaces (biblioteca de componentes) -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.1</version>
<scope>compile</scope>
</dependency>
<!-- Temas do PrimeFaces -->
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>all-themes</artifactId>
<version>1.0.10</version>
</dependency>
<!-- Driver MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<!-- Abstração para envio de e-mails. Foi utilizado o projeto sample-email do codylerum, no github. Ele foi importado
e depois RunAs -> Maven Install. Depois eu apaguei o projeto, pois os JARs já estão instalados
https://github.com/codylerum/simple-email
-->
<dependency>
<groupId>com.outjected</groupId>
<artifactId>simple-email</artifactId>
<version>0.2.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
<scope>compile</scope>
</dependency>
<!-- Templates para e-mails -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
<compile>compile</compile>
</dependency>
<!-- Formata números em templates -->
<dependency>
<groupId>velocity-tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>1.1</version>
<compile>compile</compile>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
</project><file_sep>package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import service.NegocioException;
import controller.UnidadeMedida;
@Entity
@Table(name="PRODUTO")
public class Produto implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long idProduto;
@NotNull
@NotBlank
@Column(name="nmproduto", length=200)
private String nmproduto;
@NotNull
@Column(name="dsproduto", length=50)
private String dsproduto;
@NotNull
@NotBlank
@NotEmpty
@Column(name="cdbarras", length=20)
private String cdbarras;
@NotNull
@Column(name="dsorigem", length=50)
private Origem dsorigem;
@Column(name="cdcst", length=5)
private String cdcst;
@Column(name="alicms", precision=4, scale=2)
private BigDecimal alicms;
@Column(name="dsncm", length=20)
private String dsncm;
@NotNull
@Column(name="tppreco", length=20)
private TipoControlePreco tppreco;
@Column(name="vlcomissao", precision=4, scale=2)
private BigDecimal vlcomissao;
@Column(name="vlcompra", precision=12, scale=2)
private BigDecimal vlcompra;
@Column(name="vlvenda", precision=12, scale=2)
private BigDecimal vlvenda;
@Column(name="vlpromocao", precision=12, scale=2)
private BigDecimal vlpromocao;
@Column(name="vlmargemlucro", precision=12, scale=2)
private BigDecimal vlmargemlucro;
@Column(name="prdescontomaximo", precision=2, scale=2)
private BigDecimal prdescontomaximo;
@Column(name="vlcustomedio", precision=12, scale=2)
private BigDecimal vlcustomedio;
@NotNull
@Column(name="nmunidade", length=20)
private UnidadeMedida nmunidade;
@NotNull
@Column(name="tplista", length=20)
private TipoListaProduto tplista;
@NotNull(message="Informe o Status do Produto")
@Column(name="stproduto", length=50)
private StatusProduto stproduto;
@Column(name="qtestoque")
private BigDecimal qtestoque;
@Column(name="qtestoqueminimo")
private BigDecimal qtestoqueminimo;
@Column(name="qtestoquemaximo")
private BigDecimal qtestoquemaximo;
@Column(name="qtestoquefracao")
private BigDecimal qtestoquefracao;
@Column(name="qtestoquefpopular")
private BigDecimal qtestoquefpopular;
@Column(name="dslocalizacao", length=100)
private String dslocalizacao;
@Temporal(TemporalType.DATE)
private Date dtcadastro;
@NotNull
@ManyToOne(optional=false)
@JoinColumn(name="idcategoria")
private Categoria categoria;
@NotNull
@ManyToOne(optional=false)
@JoinColumn(name="idfabricante")
private Fabricante fabricante;
public void baixarEstoque(BigDecimal qtitem)
{
BigDecimal novaQuantidade = this.getQtestoque().subtract(qtitem);
if(novaQuantidade.compareTo(novaQuantidade) <= 0)
{
throw new NegocioException("Não Há disponibilidade No Estoque Para Quantidade Solicitada. Estoque Atual: "+this.getQtestoque());
}
this.setQtestoque(novaQuantidade);
}
public Long getIdProduto()
{
return idProduto;
}
public void setIdProduto(Long idProduto)
{
this.idProduto = idProduto;
}
public String getNmproduto()
{
return nmproduto;
}
public void setNmproduto(String nmproduto)
{
this.nmproduto = nmproduto.toUpperCase();
}
public String getDsproduto()
{
return dsproduto;
}
public void setDsproduto(String dsproduto)
{
this.dsproduto = dsproduto.toUpperCase();
}
public String getCdbarras()
{
return cdbarras;
}
public void setCdbarras(String cdbarras)
{
this.cdbarras = cdbarras.toUpperCase();
}
public Origem getDsorigem()
{
return dsorigem;
}
public void setDsorigem(Origem dsorigem)
{
this.dsorigem = dsorigem;
}
public String getCdcst()
{
return cdcst;
}
public void setCdcst(String cdcst)
{
this.cdcst = cdcst.toUpperCase();
}
public String getDsncm()
{
return dsncm;
}
public void setDsncm(String dsncm)
{
this.dsncm = dsncm.toUpperCase();
}
public TipoControlePreco getTppreco()
{
return tppreco;
}
public void setTppreco(TipoControlePreco tppreco)
{
this.tppreco = tppreco;
}
public BigDecimal getVlcomissao()
{
return vlcomissao;
}
public void setVlcomissao(BigDecimal vlcomissao)
{
this.vlcomissao = vlcomissao;
}
public BigDecimal getVlcompra()
{
return vlcompra;
}
public void setVlcompra(BigDecimal vlcompra)
{
this.vlcompra = vlcompra;
}
public BigDecimal getVlvenda()
{
return vlvenda;
}
public void setVlvenda(BigDecimal vlvenda)
{
this.vlvenda = vlvenda;
}
public BigDecimal getVlpromocao()
{
return vlpromocao;
}
public void setVlpromocao(BigDecimal vlpromocao)
{
this.vlpromocao = vlpromocao;
}
public BigDecimal getVlmargemlucro()
{
return vlmargemlucro;
}
public void setVlmargemlucro(BigDecimal vlmargemlucro)
{
this.vlmargemlucro = vlmargemlucro;
}
public BigDecimal getPrdescontomaximo()
{
return prdescontomaximo;
}
public void setPrdescontomaximo(BigDecimal prdescontomaximo)
{
this.prdescontomaximo = prdescontomaximo;
}
public BigDecimal getVlcustomedio()
{
return vlcustomedio;
}
public void setVlcustomedio(BigDecimal vlcustomedio)
{
this.vlcustomedio = vlcustomedio;
}
public UnidadeMedida getNmunidade()
{
return nmunidade;
}
public void setNmunidade(UnidadeMedida nmunidade)
{
this.nmunidade = nmunidade;
}
public TipoListaProduto getTplista()
{
return tplista;
}
public void setTplista(TipoListaProduto tplista)
{
this.tplista = tplista;
}
public StatusProduto getStproduto()
{
return stproduto;
}
public void setStproduto(StatusProduto stproduto)
{
this.stproduto = stproduto;
}
public BigDecimal getQtestoque()
{
return qtestoque;
}
public void setQtestoque(BigDecimal qtestoque)
{
this.qtestoque = qtestoque;
}
public BigDecimal getQtestoqueminimo()
{
return qtestoqueminimo;
}
public void setQtestoqueminimo(BigDecimal qtestoqueminimo)
{
this.qtestoqueminimo = qtestoqueminimo;
}
public BigDecimal getQtestoquemaximo()
{
return qtestoquemaximo;
}
public void setQtestoquemaximo(BigDecimal qtestoquemaximo)
{
this.qtestoquemaximo = qtestoquemaximo;
}
public BigDecimal getQtestoquefracao()
{
return qtestoquefracao;
}
public void setQtestoquefracao(BigDecimal qtestoquefracao)
{
this.qtestoquefracao = qtestoquefracao;
}
public BigDecimal getQtestoquefpopular()
{
return qtestoquefpopular;
}
public void setQtestoquefpopular(BigDecimal qtestoquefpopular)
{
this.qtestoquefpopular = qtestoquefpopular;
}
public String getDslocalizacao()
{
return dslocalizacao;
}
public void setDslocalizacao(String dslocalizacao)
{
this.dslocalizacao = dslocalizacao.toUpperCase();
}
public Date getDtcadastro()
{
return dtcadastro;
}
public void setDtcadastro(Date dtcadastro)
{
this.dtcadastro = (new Date());
}
public Categoria getCategoria()
{
return categoria;
}
public void setCategoria(Categoria categoria)
{
this.categoria = categoria;
}
public Fabricante getFabricante()
{
return fabricante;
}
public void setFabricante(Fabricante fabricante)
{
this.fabricante = fabricante;
}
public BigDecimal getAlicms()
{
return alicms;
}
public void setAlicms(BigDecimal alicms)
{
this.alicms = alicms;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((idProduto == null) ? 0 : idProduto.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Produto other = (Produto) obj;
if (idProduto == null) {
if (other.idProduto != null)
return false;
} else if (!idProduto.equals(other.idProduto))
return false;
return true;
}
}
<file_sep>package security;
/*
* Classe UsuarioSistema responsável por identificar qual o objeto usuário efetuou o login.
* O método contrutor foi alterado exatamente para termos todas as informações do usuário,
* através de seu objeto.
*/
import java.util.Collection;
import model.Usuario;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
public class UsuarioSistema extends User
{
private static final long serialVersionUID = 1L;
private Usuario usuario;
public UsuarioSistema(Usuario usuario, Collection<? extends GrantedAuthority> authorities)
{
super(usuario.getNmlogin(), usuario.getDssenha(), authorities);
this.usuario = usuario;
System.out.println("Usuariosistema: "+usuario.getNmlogin());
}
public Usuario getUsuario()
{
return usuario;
}
}
<file_sep>package controller;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import model.Produto;
import repository.ProdutoRepository;
import util.jsf.FacesUtil;
@Named
@ViewScoped
public class SelectProduto implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private ProdutoRepository produtoRep;
private String nomeProduto;
private List<Produto> produtosFiltrados;
public void inicializar()
{
if(FacesUtil.isNotPostBack())
{
produtosFiltrados = produtoRep.todosProdutos();
}
}
public void pesquisar()
{
produtosFiltrados = produtoRep.porNomeProduto(this.nomeProduto);
}
public void selecionar(Produto pProduto)
{
RequestContext.getCurrentInstance().closeDialog(pProduto);
}
public void abrirDlgProduto()
{
Map<String, Object> opcoes = new HashMap<>();
opcoes.put("modal", true);
opcoes.put("resizable", false);
opcoes.put("contentHeight", 470);
opcoes.put("contentWidth", 870);
RequestContext.getCurrentInstance().openDialog("/produto/dlgConsultaProduto.jsf", opcoes, null);
}
public String getNomeProduto()
{
return nomeProduto;
}
public void setNomeProduto(String nomeProduto)
{
this.nomeProduto = nomeProduto;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
public List<Produto> getProdutosFiltrados()
{
return produtosFiltrados;
}
public void setProdutosFiltrados(List<Produto> produtosFiltrados)
{
this.produtosFiltrados = produtosFiltrados;
}
}
<file_sep>package controller;
public enum UnidadeMedida
{
UN, KG, GR, ML, LT, MM
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import util.jsf.FacesUtil;
import model.Produto;
public class ProdutoRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Produto adicionar(Produto produto)
{
return manager.merge(produto);
}
public Produto remover(Produto produto)
{
try
{
manager.remove(produto);
manager.flush();
}catch(PersistenceException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
return produto;
}
public Produto porId(Long id)
{
return manager.find(Produto.class, id);
}
public Produto porCodigoBarras(String codigo)
{
return manager.createQuery("from Produto where cdbarras like :codigobarras", Produto.class)
.setParameter("codigobarras", codigo.toUpperCase()+"%")
.getSingleResult();
}
public List<Produto> porListCodigoBarras(String codigo)
{
return manager.createQuery("from Produto where upper(cdbarras) like :codigo", Produto.class)
.setParameter("codigo",codigo.toUpperCase()+"%")
.getResultList();
}
public List<Produto> porNomeProduto(String nome)
{
return manager.createQuery("from Produto where upper(nmproduto) like :nome", Produto.class)
.setParameter("nome", nome.toUpperCase()+"%")
.getResultList();
}
public List<Produto> todosProdutos()
{
return manager.createQuery("from Produto", Produto.class).getResultList();
}
}
<file_sep>package converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
import repository.ProdutoRepository;
import service.NegocioException;
import util.cdi.CDIServiceLocator;
import util.jsf.FacesUtil;
import model.Produto;
@FacesConverter(forClass=Produto.class)
public class ProdutoConverter implements Converter
{
@Inject
private ProdutoRepository prodrep;
public ProdutoConverter()
{
prodrep = CDIServiceLocator.getBean(ProdutoRepository.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
Produto retorno = null;
if(value != null)
{
Long id = new Long(value);
retorno = prodrep.porId(id);
return retorno;
}
return null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
String retorno = null;
if(value != null)
{
try
{
retorno = String.valueOf(((Produto) value).getIdProduto());
}catch(NegocioException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
}
return retorno;
}
}
<file_sep>package controller;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import service.CadastroGrupoUsuarioService;
import util.jsf.FacesUtil;
import model.GrupoUsuario;
@Named
@ViewScoped
public class GrupoUsuarioBean implements Serializable
{
private static final long serialVersionUID = 1L;
private GrupoUsuario grupoSelecionado;
private GrupoUsuario grupo = new GrupoUsuario();
@Inject
private CadastroGrupoUsuarioService grupoService;
public GrupoUsuarioBean()
{
limpar();
}
public void limpar()
{
grupo = new GrupoUsuario();
}
public void salvar()
{
grupoService.salvar(this.grupo);
limpar();
FacesUtil.addInfoMessage("Grupo de Usuários Salvo Com Sucesso.");
}
public void excluir()
{
grupoService.remover(grupoSelecionado);
FacesUtil.addErrorMessage("Grupo de Usuários excluído Com Sucesso.");
}
public List<GrupoUsuario> visualizar()
{
return grupoService.todos();
}
public Boolean isEditando()
{
return grupo.getIdGrupoUsuario() != null;
}
public GrupoUsuario getGrupoSelecionado()
{
return grupoSelecionado;
}
public void setGrupoSelecionado(GrupoUsuario grupoSelecionado)
{
this.grupoSelecionado = grupoSelecionado;
}
public GrupoUsuario getGrupo()
{
return grupo;
}
public void setGrupo(GrupoUsuario grupo)
{
this.grupo = grupo;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
}
<file_sep>package service;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import model.Produto;
import repository.ProdutoRepository;
import util.jpa.Transactional;
public class CadastroProdutoService implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private ProdutoRepository produtorep;
@Transactional
public Produto salvar(Produto produto)
{
return produtorep.adicionar(produto);
}
@Transactional
public Produto excluir(Produto produto)
{
produto = produtorep.porId(produto.getIdProduto());
return produtorep.remover(produto);
}
public List<Produto> todos()
{
return produtorep.todosProdutos();
}
}
<file_sep>package model;
public enum TipoRegimeEmpresa
{
SIMPLES, NORMAL
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import util.jsf.FacesUtil;
import model.Categoria;
public class CategoriaRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Categoria adicionar(Categoria categoria)
{
return manager.merge(categoria);
}
public Categoria remover(Categoria categoria)
{
try
{
manager.remove(categoria);
manager.flush();
} catch (PersistenceException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
return categoria;
}
public Categoria porId(Long id)
{
return manager.find(Categoria.class, id);
}
public List<Categoria> todasCategorias()
{
return manager.createQuery("from Categoria", Categoria.class).getResultList();
}
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import util.jsf.FacesUtil;
import model.Convenio;
public class ConvenioRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Convenio adicionar(Convenio convenio)
{
return manager.merge(convenio);
}
public Convenio remover(Convenio convenio)
{
try
{
manager.remove(convenio);
manager.flush();
}catch (PersistenceException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
return convenio;
}
public Convenio porId(Long id)
{
return manager.find(Convenio.class, id);
}
public List<Convenio> todosConvenios()
{
return manager.createQuery("from Convenio", Convenio.class).getResultList();
}
}
<file_sep>package service;
import java.io.Serializable;
import javax.inject.Inject;
import repository.PreVendaRepository;
import model.PreVenda;
import model.StatusPreVenda;
public class EmissaoPedidoService implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private PreVendaService preVendaService;
@Inject
private PreVendaRepository preVendaRep;
public PreVenda emitir(PreVenda prevenda)
{
prevenda = this.preVendaService.salvar(prevenda);
if(prevenda.isNaoEmissivel())
{
throw new NegocioException("Pré Venda Não Pode Ser Emitida");
}
prevenda.setDsstatus(StatusPreVenda.EMITIDO);
prevenda = this.preVendaRep.adicionar(prevenda);
return prevenda;
}
}
<file_sep>package service;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import model.Fornecedor;
import repository.FornecedorRepository;
import util.jpa.Transactional;
public class CadastroFornecedorService implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private FornecedorRepository fornecedorrep;
@Transactional
public Fornecedor salvar(Fornecedor fornecedor)
{
return fornecedorrep.adicionar(fornecedor);
}
@Transactional
public Fornecedor excluir(Fornecedor fornecedor)
{
fornecedor = fornecedorrep.porId(fornecedor.getIDFornecedor());
fornecedorrep.remover(fornecedor);
return fornecedor;
}
public List<Fornecedor> listarTodos()
{
return fornecedorrep.todosFornecedores();
}
}
<file_sep>package controller;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.context.RequestContext;
import repository.ClienteRepository;
import model.Cliente;
@Named
@ViewScoped
public class SelectCliente implements Serializable
{
@Inject
private ClienteRepository clienteRep;
private static final long serialVersionUID = 1L;
private String nome;
private List<Cliente> clientesFiltrados;
public void inicializar()
{
clientesFiltrados = clienteRep.todosCliente();
}
public void pesquisar()
{
clientesFiltrados = clienteRep.porNomeCliente(this.nome);
}
public void abrirDlgCliente()
{
Map<String, Object> opcoes = new HashMap<>();
opcoes.put("modal", true);
opcoes.put("resizable", false);
opcoes.put("contentHeight", 470);
RequestContext.getCurrentInstance().openDialog("/cliente/dlgConsultaCliente.jsf", opcoes, null);
}
public void selecionar(Cliente cliente)
{
RequestContext.getCurrentInstance().closeDialog(cliente);
}
public String getNome()
{
return nome;
}
public void setNome(String nome)
{
this.nome = nome;
}
public List<Cliente> getClientesFiltrados()
{
return clientesFiltrados;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
}
<file_sep>package converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import repository.UsuarioRepository;
import service.NegocioException;
import util.cdi.CDIServiceLocator;
import util.jsf.FacesUtil;
import model.Usuario;
@FacesConverter(forClass=Usuario.class)
public class UsuarioConverter implements Converter
{
private UsuarioRepository usuarioRep;
public UsuarioConverter()
{
usuarioRep = CDIServiceLocator.getBean(UsuarioRepository.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
Usuario retorno = null;
if(value != null)
{
Long id = new Long(value);
retorno = usuarioRep.porId(id);
}
return retorno;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
String retorno = null;
if(value != null)
{
try
{
retorno = String.valueOf(((Usuario) value).getIdUsuario());
}catch(NegocioException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
}
return retorno;
}
}
<file_sep>package util.jpa;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
@ApplicationScoped // Uma instância por aplicação !!
public class EntityManagerProducer
{
private EntityManagerFactory factory;
public EntityManagerProducer()
{
// Instancio uma factory
factory = Persistence.createEntityManagerFactory("ExodoDB");
System.out.println("EntityManager Criado");
}
@Produces
@RequestScoped // Cria a cada nova requisição;
public EntityManager createEntityManager()
{
// Retorna um EntityManager de uma factory
System.out.println("Factory Criado");
return factory.createEntityManager();
}
public void closeEntityManager(@Disposes EntityManager manager) // @Disposes -> Gatilho disparado quando finalizamos um escopo.
{
manager.close();
}
}
<file_sep>package model;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name="CONVENIO")
public class Convenio implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long idConvenio;
@NotNull
@Column(name="nmconvenio", length=100)
private String nmconvenio;
@NotNull
@NotBlank
@NotEmpty
@Column(name="rzsocial", length=150, nullable=false)
private String rzsocial;
@Column(name="nucnpj", length=24, nullable=false)
private String nucnpj;
@Column(name="nuinscest", length=20, nullable=false)
private String nuinscest;
@Column(name="nuinscmunicipal", length=20, nullable=false)
private String nuinscmunicipal;
@NotNull
@Column(name="dsEndereco", length=150, nullable=false)
private String dsendereco;
@NotNull
@Column(name="nuendereco", length=10, nullable=false)
private String nuendereco;
@Column(name="dscomplemento", length=10)
private String dscomplemento;
@NotNull
@Column(name="nmBairro", length=100, nullable=false)
private String nmbairro;
@NotNull
@Column(name="nmcidade", length=100, nullable=false)
private String nmcidade;
@NotNull
@Column(name="nucep", length=15, nullable=false)
private String nucep;
@Column(name="nufone", length=20)
private String nufone;
@Column(name="nucelular", length=20)
private String nucelular;
@Column(name="nmcontato", length=100, nullable=false)
@NotNull(message="Informe o Nome do Contato/ Responsável Pela Empresa")
private String nmcontato;
@Column(name="dsemailcontato", length=150, nullable=false)
@NotNull(message="Informe o e-mail do Contato da Empresa")
@Email
private String dsemailcontato;
@Column(name="nufoneContato", length=14, nullable=true)
private String nufoneContato;
@Column(name="vlDescontoMinimo", precision=8, scale=2)
private BigDecimal vlDescontoMinimo;
@Column(name="vlDescontoMaximo", precision=8, scale=2)
private BigDecimal vlDescontoMaximo;
@NotNull
@ManyToOne(optional=false)
@JoinColumn(name="idufconvenio")
private UF uf;
public Long getIdConvenio()
{
return idConvenio;
}
public void setIdConvenio(Long idConvenio)
{
this.idConvenio = idConvenio;
}
public String getNmconvenio()
{
return nmconvenio;
}
public void setNmconvenio(String nmconvenio)
{
this.nmconvenio = nmconvenio.toUpperCase();
}
public String getRzsocial()
{
return rzsocial;
}
public void setRzsocial(String rzsocial)
{
this.rzsocial = rzsocial.toUpperCase();
}
public String getNucnpj()
{
return nucnpj;
}
public void setNucnpj(String nucnpj)
{
this.nucnpj = nucnpj;
}
public String getNuinscest()
{
return nuinscest;
}
public void setNuinscest(String nuinscest)
{
this.nuinscest = nuinscest.toUpperCase();
}
public String getNuinscmunicipal()
{
return nuinscmunicipal;
}
public void setNuinscmunicipal(String nuinscmunicipal)
{
this.nuinscmunicipal = nuinscmunicipal.toUpperCase();
}
public String getDsendereco()
{
return dsendereco;
}
public void setDsendereco(String dsendereco)
{
this.dsendereco = dsendereco.toUpperCase();
}
public String getNuendereco()
{
return nuendereco;
}
public void setNuendereco(String nuendereco)
{
this.nuendereco = nuendereco.toUpperCase();
}
public String getDscomplemento()
{
return dscomplemento;
}
public void setDscomplemento(String dscomplemento)
{
this.dscomplemento = dscomplemento.toUpperCase();
}
public String getNmbairro()
{
return nmbairro;
}
public void setNmbairro(String nmbairro)
{
this.nmbairro = nmbairro.toUpperCase();
}
public String getNmcidade()
{
return nmcidade;
}
public void setNmcidade(String nmcidade)
{
this.nmcidade = nmcidade.toUpperCase();
}
public String getNucep()
{
return nucep;
}
public void setNucep(String nucep)
{
this.nucep = nucep;
}
public String getNufone()
{
return nufone;
}
public void setNufone(String nufone)
{
this.nufone = nufone;
}
public String getNucelular()
{
return nucelular;
}
public void setNucelular(String nucelular)
{
this.nucelular = nucelular;
}
public String getNmcontato()
{
return nmcontato;
}
public void setNmcontato(String nmcontato)
{
this.nmcontato = nmcontato.toUpperCase();
}
public String getDsemailcontato()
{
return dsemailcontato;
}
public void setDsemailcontato(String dsemailcontato)
{
this.dsemailcontato = dsemailcontato.toLowerCase();
}
public String getNufoneContato()
{
return nufoneContato;
}
public void setNufoneContato(String nufoneContato)
{
this.nufoneContato = nufoneContato;
}
public BigDecimal getVlDescontoMinimo()
{
return vlDescontoMinimo;
}
public void setVlDescontoMinimo(BigDecimal vlDescontoMinimo)
{
this.vlDescontoMinimo = vlDescontoMinimo;
}
public BigDecimal getVlDescontoMaximo()
{
return vlDescontoMaximo;
}
public void setVlDescontoMaximo(BigDecimal vlDescontoMaximo)
{
this.vlDescontoMaximo = vlDescontoMaximo;
}
public UF getUf()
{
return uf;
}
public void setUf(UF uf)
{
this.uf = uf;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((idConvenio == null) ? 0 : idConvenio.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Convenio other = (Convenio) obj;
if (idConvenio == null) {
if (other.idConvenio != null)
return false;
} else if (!idConvenio.equals(other.idConvenio))
return false;
return true;
}
}
<file_sep>package curso;
import javax.enterprise.context.Dependent;
@Dependent // Esse Bean é dependente de quem o Injeta
public class calculadoraPreco
{
public double calcularPreco(double pQuantidade, double pValorUnitario)
{
return pQuantidade * pValorUnitario;
}
}
<file_sep>package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="ITCOMPRA")
public class ItCompra implements Serializable
{
private static final long serialVersionUID = 1L;
private Long id;
private Produto produto;
private BigDecimal qtitem;
private BigDecimal vlunitario;
private BigDecimal alicms;
private BigDecimal vlbaseicms;
private BigDecimal vlicms;
private BigDecimal vlicmssubtrib;
private BigDecimal alipi;
private BigDecimal vlbaseipi;
private BigDecimal vlipi;
private String cst;
private String ncm;
private String dsembalagem;
private String dslote;
private Date dtfabricacao;
private Date dtvencimento;
private BigDecimal prdesconto;
private BigDecimal vldesconto;
private BigDecimal vltotal;
private BigDecimal vlproduto;
private Compra compra;
public static long getSerialversionuid()
{
return serialVersionUID;
}
@Id
@GeneratedValue
public Long getId()
{
return id;
}
@ManyToOne
@JoinColumn(name="idcompra", nullable=false)
public Compra getCompra()
{
return compra;
}
@NotNull
@ManyToOne
@JoinColumn(name="idproduto", nullable=false)
public Produto getProduto()
{
return produto;
}
@Column(name="qtitem", precision=10, scale=2)
public BigDecimal getQtitem()
{
return qtitem;
}
@Column(name="vlunitario", precision=10, scale=2)
public BigDecimal getVlunitario()
{
return vlunitario;
}
@Column(name="vldesconto", precision=10, scale=2)
public BigDecimal getVldesconto()
{
return vldesconto;
}
@Column(name="vltotal", precision=10, scale=2)
public BigDecimal getVltotal()
{
return vltotal;
}
@Column(name="alicms", precision=10, scale=2)
public BigDecimal getAlicms()
{
return alicms;
}
@Column(name="vlbaseicms", precision=10, scale=2)
public BigDecimal getVlbaseicms()
{
return vlbaseicms;
}
@Column(name="vlicms", precision=10, scale=2)
public BigDecimal getVlicms()
{
return vlicms;
}
@Column(name="vlicmssubtrib", precision=10, scale=2)
public BigDecimal getVlicmssubtrib()
{
return vlicmssubtrib;
}
@Column(name="alipi", precision=10, scale=2)
public BigDecimal getAlipi()
{
return alipi;
}
@Column(name="vlipi", precision=10, scale=2)
public BigDecimal getVlipi()
{
return vlipi;
}
@Column(name="cst", length=5)
public String getCst()
{
return cst;
}
@Column(name="ncm", length=15)
public String getNcm()
{
return ncm;
}
@Column(name="dsembalagem", length=30)
public String getDsembalagem()
{
return dsembalagem;
}
@NotNull
@Column(name="dslote", length=40)
public String getDslote()
{
return dslote;
}
@Column(name="dtfabricacao")
@Temporal(TemporalType.DATE)
public Date getDtfabricacao()
{
return dtfabricacao;
}
@Column(name="dtvencimento")
@Temporal(TemporalType.DATE)
public Date getDtvencimento()
{
return dtvencimento;
}
@Transient
public boolean isProdutoAssociado()
{
return this.getProduto() != null && this.getProduto().getIdProduto() != null;
}
@Transient
public BigDecimal getValorTotal()
{
BigDecimal vlcalculado = BigDecimal.ZERO;
BigDecimal vdesconto = BigDecimal.ZERO;
BigDecimal vlicms = BigDecimal.ZERO;
vlcalculado = BigDecimal.ZERO;
vlproduto = BigDecimal.ZERO;
vdesconto = BigDecimal.ZERO;
vlbaseicms = BigDecimal.ZERO;
vlicms = BigDecimal.ZERO;
vlicmssubtrib = BigDecimal.ZERO;
vlbaseipi = BigDecimal.ZERO;
vlipi = BigDecimal.ZERO;
if(this.getProduto() != null && this.getProduto().getIdProduto() != null)
{
if(this.getVlunitario().doubleValue() > 0 || this.getQtitem().doubleValue() > 0 )
{
System.out.println("Quantidade do item: "+this.getQtitem());
System.out.println("Vlr Unitario do item: "+this.getVlunitario());
System.out.println("IdProduto: "+this.getProduto().getIdProduto());
System.out.println("Produto: "+this.getProduto().getNmproduto());
// Calcula valor total e desconto
vlcalculado = this.getVlunitario().multiply(this.getQtitem());
vlproduto = vlcalculado;
vdesconto = (vlcalculado.multiply(this.getPrdesconto().divide(new BigDecimal(100))));
// Calcula o icms !!
vlbaseicms = vlcalculado;
vlicms = (vlcalculado.multiply(this.getAlicms().divide(new BigDecimal(100))));
// Calcula o icms sub trib !!
vlicmssubtrib = vlcalculado;
// Calcula IPI !!
vlbaseipi = vlcalculado;
vlipi = (vlcalculado.multiply(this.getAlipi().divide(new BigDecimal(100))));
vlcalculado = vlcalculado.subtract(vdesconto);
// armazena os valores calculados !!
this.setVltotal(vlcalculado);
this.setVlproduto(vlproduto);
this.setVldesconto(vdesconto);
this.setVlbaseicms(vlbaseicms);
this.setVlicms(vlicms);
this.setVlicmssubtrib(vlicmssubtrib);
this.setVlbaseipi(vlbaseipi);
this.setVlipi(vlipi);
}
}
return vlcalculado;
}
public void setCompra(Compra compra)
{
this.compra = compra;
}
public void setId(Long id)
{
this.id = id;
}
public void setProduto(Produto produto)
{
this.produto = produto;
}
public void setQtitem(BigDecimal qtitem)
{
this.qtitem = qtitem;
}
public void setVlunitario(BigDecimal vlunitario)
{
this.vlunitario = vlunitario;
}
public void setAlicms(BigDecimal alicms)
{
this.alicms = alicms;
}
public void setVlbaseicms(BigDecimal vlbaseicms)
{
this.vlbaseicms = vlbaseicms;
}
public void setVlicms(BigDecimal vlicms)
{
this.vlicms = vlicms;
}
public void setVlicmssubtrib(BigDecimal vlicmssubtrib)
{
this.vlicmssubtrib = vlicmssubtrib;
}
public void setAlipi(BigDecimal alipi)
{
this.alipi = alipi;
}
public void setVlipi(BigDecimal vlipi)
{
this.vlipi = vlipi;
}
public void setCst(String cst)
{
this.cst = cst;
}
public void setNcm(String ncm)
{
this.ncm = ncm;
}
public void setDsembalagem(String dsembalagem)
{
this.dsembalagem = dsembalagem;
}
public void setDslote(String dslote)
{
this.dslote = dslote;
}
public void setDtfabricacao(Date dtfabricacao)
{
this.dtfabricacao = dtfabricacao;
}
public void setDtvencimento(Date dtvencimento)
{
this.dtvencimento = dtvencimento;
}
public void setVldesconto(BigDecimal vldesconto)
{
this.vldesconto = vldesconto;
}
public void setVltotal(BigDecimal vltotal)
{
this.vltotal = vltotal;
}
public BigDecimal getVlbaseipi()
{
return vlbaseipi;
}
public void setVlbaseipi(BigDecimal vlbaseipi)
{
this.vlbaseipi = vlbaseipi;
}
public BigDecimal getPrdesconto()
{
return prdesconto;
}
public void setPrdesconto(BigDecimal prdesconto)
{
this.prdesconto = prdesconto;
}
public BigDecimal getVlproduto()
{
return vlproduto;
}
public void setVlproduto(BigDecimal vlproduto)
{
this.vlproduto = vlproduto;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItCompra other = (ItCompra) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import model.Empresa;
public class EmpresaRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Empresa adicionar(Empresa empresa)
{
// salva no banco e retorna uma nova instância já persistida com Id.
System.out.println("Antes de salvar. Veja Retorno da Empresa: "+empresa.getUf().getIduf());
return manager.merge(empresa);
}
public List<Empresa> todos()
{
TypedQuery<Empresa> query = manager.createQuery("from Empresa", Empresa.class);
return query.getResultList();
}
public Empresa porId(Long id)
{
return manager.find(Empresa.class, id);
}
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import util.jsf.FacesUtil;
import model.GrupoUsuario;
public class GrupoUsuarioRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public GrupoUsuario adicionar(GrupoUsuario grupo)
{
return manager.merge(grupo);
}
public GrupoUsuario excluir(GrupoUsuario grupo)
{
try
{
manager.remove(grupo);
manager.flush();
}catch(PersistenceException e)
{
FacesUtil.addErrorMessage("Não Foi Possível Excluir o Grupo de Usuário "+grupo.getNmgrupoUsuario()+". Mensagem: "+e.getMessage());
}
return grupo;
}
public List<GrupoUsuario> todos()
{
TypedQuery<GrupoUsuario> query = manager.createQuery("from GrupoUsuario", GrupoUsuario.class);
return query.getResultList();
}
public GrupoUsuario porId(Long id)
{
return manager.find(GrupoUsuario.class, id);
}
public List<GrupoUsuario> porNomeGrupo(String nome)
{
return manager.createQuery("from GrupoUsuario where nmgrupousuario like :nome", GrupoUsuario.class)
.setParameter("nome", nome.toUpperCase()+"%")
.getResultList();
}
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import util.jsf.FacesUtil;
import model.Cliente;
public class ClienteRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Cliente adicionar(Cliente cliente)
{
System.out.println("Repository: "+cliente.getNomeCliente());
return manager.merge(cliente);
}
public Cliente remover(Cliente cliente)
{
try
{
manager.remove(cliente);
manager.flush();
} catch (PersistenceException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
return cliente;
}
public Cliente porId(Long id)
{
return manager.find(Cliente.class, id);
}
public List<Cliente> porNomeCliente(String nome)
{
return this.manager.createQuery("from Cliente where upper(nmcliente) like :nome", Cliente.class)
.setParameter("nome", nome.toUpperCase() + "%")
.getResultList();
}
public List<Cliente> todosCliente()
{
return manager.createQuery("from Cliente",Cliente.class).getResultList();
}
}
<file_sep>package model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="USUARIO")
public class Usuario
{
@Id
@GeneratedValue
private Long IdUsuario;
@Column(name="nmusuario", length=30)
private String nmusuario;
@Column(name="nmlogin", length=15)
private String nmlogin;
@Column(name="dssenha", length=30)
private String dssenha;
@Column(name="dsemail", length=150)
private String dsemail;
@Temporal(TemporalType.DATE)
private Date dtnascimento;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "usuario_grupo", joinColumns = @JoinColumn(name="idusuario"),
inverseJoinColumns = @JoinColumn(name = "idgrupousuario"))
private List<GrupoUsuario> grupoUsuario;
public List<GrupoUsuario> getGrupoUsuario()
{
return grupoUsuario;
}
public void setGrupoUsuario(List<GrupoUsuario> grupoUsuario)
{
this.grupoUsuario = grupoUsuario;
}
public Long getIdUsuario()
{
return IdUsuario;
}
public void setIdUsuario(Long idUsuario)
{
IdUsuario = idUsuario;
}
public String getNmusuario()
{
return nmusuario;
}
public void setNmusuario(String nmusuario)
{
this.nmusuario = nmusuario;
}
public String getDsemail()
{
return dsemail;
}
public void setDsemail(String dsemail)
{
this.dsemail = dsemail;
}
public String getDssenha()
{
return dssenha;
}
public void setDssenha(String dssenha)
{
this.dssenha = dssenha;
}
public String getNmlogin()
{
return nmlogin;
}
public void setNmlogin(String nmlogin)
{
this.nmlogin = nmlogin;
}
public Date getDtnascimento()
{
return dtnascimento;
}
public void setDtnascimento(Date dtnascimento)
{
this.dtnascimento = dtnascimento;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((IdUsuario == null) ? 0 : IdUsuario.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Usuario other = (Usuario) obj;
if (IdUsuario == null) {
if (other.IdUsuario != null)
return false;
} else if (!IdUsuario.equals(other.IdUsuario))
return false;
return true;
}
}
<file_sep>package model;
public enum TipoCategoria
{
MEDICAMENTOS, PERFUMARIA, COSMETICOS, OUTROS
}
<file_sep>package service;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import model.Cliente;
import util.jpa.Transactional;
import repository.ClienteRepository;
public class CadastroClienteService implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private ClienteRepository clirep;
@Transactional
public Cliente salvar(Cliente cliente)
{
System.out.println("@Transactional - Cliente: "+cliente.getNomeCliente());
return clirep.adicionar(cliente);
}
@Transactional
public Cliente excluir(Cliente cliente)
{
cliente = clirep.porId(cliente.getIDCliente());
return clirep.remover(cliente);
}
public List<Cliente>listarTodos()
{
return this.clirep.todosCliente();
}
}
<file_sep>package service;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import model.Convenio;
import repository.ConvenioRepository;
import util.jpa.Transactional;
public class CadastroConvenioService implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
public ConvenioRepository conveniorep;
@Transactional
public Convenio salvar(Convenio convenio)
{
return conveniorep.adicionar(convenio);
}
@Transactional
public Convenio excluir(Convenio convenio)
{
convenio = conveniorep.porId(convenio.getIdConvenio());
return conveniorep.remover(convenio);
}
public List<Convenio> listarTodos()
{
return conveniorep.todosConvenios();
}
}
<file_sep>mail.server.host=smtp.gmail.com
mail.server.port=465
mail.enable.ssl=true
mail.auth=true
mail.username=<EMAIL>
mail.password=<PASSWORD><file_sep>package controller;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import model.Substancia;
import service.CadastroSubstanciaService;
import util.jsf.FacesUtil;
@Named
@SessionScoped
public class SubstanciaBean implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private CadastroSubstanciaService substanciaserv;
private Substancia substancia;
private Substancia substanciaSelecionada;
public SubstanciaBean()
{
limpar();
}
public void limpar()
{
substancia = new Substancia();
substanciaSelecionada = new Substancia();
}
public void novo()
{
limpar();
}
public void salvar()
{
this.substanciaserv.salvar(substancia) ;
limpar();
FacesUtil.addInfoMessage("Substância Cadastrada Com Sucesso");
}
public void excluir()
{
this.substanciaserv.excluir(substanciaSelecionada);
limpar();
FacesUtil.addInfoMessage("Substância Excluída");
}
public List<Substancia> visualizar()
{
return this.substanciaserv.todos();
}
public Boolean isEditando()
{
return this.substancia.getIdSubstancia() != null;
}
public Substancia getSubstancia()
{
return substancia;
}
public void setSubstancia(Substancia substancia)
{
this.substancia = substancia;
}
public Substancia getSubstanciaSelecionada()
{
return substanciaSelecionada;
}
public void setSubstanciaSelecionada(Substancia substanciaSelecionada)
{
this.substanciaSelecionada = substanciaSelecionada;
}
}
<file_sep>package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name="CLIENTE")
public class Cliente implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long IDCliente;
@NotNull
@NotBlank
@NotEmpty
@Column(name="nmcliente", length=100, nullable=false)
private String nomeCliente;
@NotNull
@NotBlank
@NotEmpty
@Column(name="rzsocial", length=150, nullable=false)
private String rzsocial;
@Column(name="nucpf", length=24, nullable=true)
private String nucpf;
@Column(name="nuIdentidade", length=10, nullable=true)
private String nuIdentidade;
@Column(name="nucnpj", length=24, nullable=false)
private String nucnpj;
@Column(name="nuinscEstadual", length=20, nullable=false)
private String nuinscestadual;
@Column(name="nuinscmunicipal", length=20, nullable=false)
private String nuinscmunicipal;
@Column(name="cdMunIBGE", length=20, nullable=false)
private String cdmunibge;
@NotNull
@Column(name="dsEndereco", length=150, nullable=false)
private String dsendereco;
@NotNull
@Column(name="nuendereco", length=10, nullable=false)
private String nuendereco;
@Column(name="dscomplemento", length=10)
private String dscomplemento;
@NotNull
@Column(name="nmBairro", length=100, nullable=false)
private String nmbairro;
@NotNull
@Column(name="nmcidade", length=100, nullable=false)
private String nmcidade;
@NotNull
@Column(name="nucep", length=15, nullable=false)
private String nucep;
@Column(name="nufone", length=20)
private String nufone;
@Column(name="nucelular", length=20)
private String nucelular;
@Column(name="dsemail", length=150)
private String dsemail;
@Temporal(TemporalType.DATE)
private Date dtnascimento;
@Temporal(TemporalType.DATE)
private Date dtcadastro;
@Column(name="nmconjuge", length=50)
private String nmconjuge;
@Column(name="nmnaturalidade", length=50)
private String nmnaturalidade;
@Column(name="nmpai", length=50)
private String nmpai;
@Column(name="nmmae", length=50)
private String nmmae;
@Column(name="vlLimite", precision=8, scale=2)
private BigDecimal vllimite;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name="tpcliente", nullable=false, length=10)
private TipoPessoa tipo;
@Enumerated(EnumType.STRING)
@Column(length=12, name="dsSexo")
private Sexo sexo;
@Enumerated(EnumType.STRING)
@Column(name="dsEstadoCivil", length=20)
private EstadoCivil estadocivil;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name="dsStatus", length=10)
private StatusPessoa status;
@NotNull
@ManyToOne(optional=false)
@JoinColumn(name="idufcliente")
private UF uf;
@NotNull
@ManyToOne(optional=false)
@JoinColumn(name="IDCONVENIO")
private Convenio convenio;
public Long getIDCliente()
{
return IDCliente;
}
public void setIDCliente(Long iDCliente)
{
IDCliente = iDCliente;
}
public String getNomeCliente()
{
return nomeCliente;
}
public void setNomeCliente(String nomeCliente)
{
this.nomeCliente = nomeCliente.toUpperCase();
}
public String getRzsocial()
{
return rzsocial;
}
public void setRzsocial(String rzsocial)
{
this.rzsocial = rzsocial.toUpperCase();
}
public String getNucpf()
{
return nucpf;
}
public void setNucpf(String nucpf)
{
this.nucpf = nucpf.toUpperCase();
}
public String getNuIdentidade()
{
return nuIdentidade;
}
public void setNuIdentidade(String nuIdentidade)
{
this.nuIdentidade = nuIdentidade.toUpperCase();
}
public String getNucnpj()
{
return nucnpj;
}
public void setNucnpj(String nucnpj)
{
this.nucnpj = nucnpj.toUpperCase();
}
public String getNuinscestadual()
{
return nuinscestadual;
}
public void setNuinscestadual(String nuinscestadual)
{
this.nuinscestadual = nuinscestadual.toUpperCase();
}
public String getNuinscmunicipal()
{
return nuinscmunicipal;
}
public void setNuinscmunicipal(String nuinscmunicipal)
{
this.nuinscmunicipal = nuinscmunicipal.toUpperCase();
}
public String getCdmunibge()
{
return cdmunibge;
}
public void setCdmunibge(String cdmunibge)
{
this.cdmunibge = cdmunibge.toUpperCase();
}
public String getDsendereco()
{
return dsendereco;
}
public void setDsendereco(String dsendereco)
{
this.dsendereco = dsendereco.toUpperCase();
}
public String getNuendereco()
{
return nuendereco;
}
public void setNuendereco(String nuendereco)
{
this.nuendereco = nuendereco.toUpperCase();
}
public String getDscomplemento()
{
return dscomplemento;
}
public void setDscomplemento(String dscomplemento)
{
this.dscomplemento = dscomplemento.toUpperCase();
}
public String getNmbairro()
{
return nmbairro;
}
public void setNmbairro(String nmbairro)
{
this.nmbairro = nmbairro.toUpperCase();
}
public String getNmcidade()
{
return nmcidade;
}
public void setNmcidade(String nmcidade)
{
this.nmcidade = nmcidade.toUpperCase();
}
public String getNucep()
{
return nucep;
}
public void setNucep(String nucep)
{
this.nucep = nucep.toUpperCase();
}
public String getNufone()
{
return nufone;
}
public void setNufone(String nufone)
{
this.nufone = nufone.toUpperCase();
}
public String getNucelular()
{
return nucelular;
}
public void setNucelular(String nucelular)
{
this.nucelular = nucelular;
}
public String getDsemail()
{
return dsemail;
}
public void setDsemail(String dsemail)
{
this.dsemail = dsemail.toLowerCase();
}
public Date getDtnascimento()
{
return dtnascimento;
}
public void setDtnascimento(Date dtnascimento)
{
this.dtnascimento = dtnascimento;
}
public Date getDtcadastro()
{
return dtcadastro;
}
public void setDtcadastro(Date dtcadastro)
{
this.dtcadastro = (new Date());
}
public String getNmconjuge()
{
return nmconjuge;
}
public void setNmconjuge(String nmconjuge)
{
this.nmconjuge = nmconjuge.toUpperCase();
}
public String getNmnaturalidade()
{
return nmnaturalidade;
}
public void setNmnaturalidade(String nmnaturalidade)
{
this.nmnaturalidade = nmnaturalidade.toUpperCase();
}
public String getNmpai()
{
return nmpai;
}
public void setNmpai(String nmpai)
{
this.nmpai = nmpai.toUpperCase();
}
public String getNmmae()
{
return nmmae;
}
public void setNmmae(String nmmae)
{
this.nmmae = nmmae.toUpperCase();
}
public BigDecimal getVllimite()
{
return vllimite;
}
public void setVllimite(BigDecimal vllimite)
{
this.vllimite = vllimite;
}
public TipoPessoa getTipo()
{
return tipo;
}
public void setTipo(TipoPessoa tipo)
{
this.tipo = tipo;
}
public Sexo getSexo()
{
return sexo;
}
public void setSexo(Sexo sexo)
{
this.sexo = sexo;
}
public EstadoCivil getEstadocivil()
{
return estadocivil;
}
public void setEstadocivil(EstadoCivil estadocivil)
{
this.estadocivil = estadocivil;
}
public StatusPessoa getStatus()
{
return status;
}
public void setStatus(StatusPessoa status)
{
this.status = status;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
public UF getUf()
{
return uf;
}
public void setUf(UF uf)
{
this.uf = uf;
}
public Convenio getConvenio()
{
return convenio;
}
public void setConvenio(Convenio convenio)
{
this.convenio = convenio;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((IDCliente == null) ? 0 : IDCliente.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cliente other = (Cliente) obj;
if (IDCliente == null) {
if (other.IDCliente != null)
return false;
} else if (!IDCliente.equals(other.IDCliente))
return false;
return true;
}
}
<file_sep>package controller;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import model.Convenio;
import model.UF;
import repository.UFRepository;
import service.CadastroConvenioService;
import util.jsf.FacesUtil;
@Named
@SessionScoped
public class ConvenioBean implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private CadastroConvenioService convenioService;
@Inject
private UFRepository ufrep;
private Convenio convenio;
private Convenio convenioSelecionado;
private UF uf = new UF();
private List<UF> ufs;
public ConvenioBean()
{
limpar();
}
public void inicializar()
{
if(FacesUtil.isNotPostBack())
{
ufs = ufrep.buscarUFs();
}
}
public void limpar()
{
convenio = new Convenio();
convenioSelecionado = new Convenio();
ufs = null;
}
public void novo()
{
limpar();
}
public void salvar()
{
this.convenio = convenioService.salvar(this.convenio);
limpar();
FacesUtil.addInfoMessage("Convênio Cadastrado Com Sucesso.");
}
public void excluir()
{
System.out.println("convenioBean - excluir: "+convenioSelecionado.getNmconvenio());
this.convenio = convenioService.excluir(convenioSelecionado);
limpar();
FacesUtil.addInfoMessage("Dados da Empresa Conveniada Excluída Com Sucesso");
}
public List<Convenio> visualizar()
{
return convenioService.listarTodos();
}
public Boolean isEditando()
{
return this.convenio.getIdConvenio() != null;
}
public Convenio getConvenio()
{
return convenio;
}
public void setConvenio(Convenio convenio)
{
this.convenio = convenio;
}
public Convenio getConvenioSelecionado()
{
return convenioSelecionado;
}
public void setConvenioSelecionado(Convenio convenioSelecionado)
{
this.convenioSelecionado = convenioSelecionado;
}
public List<UF> getUfs()
{
return ufs;
}
public void setUfs(List<UF> ufs)
{
this.ufs = ufs;
}
public UF getUf()
{
return uf;
}
public void setUf(UF uf)
{
this.uf = uf;
}
}
<file_sep>package controller;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import repository.EmpresaRepository;
import repository.UFRepository;
import service.CadastroEmpresaService;
import util.jsf.FacesUtil;
import model.Empresa;
import model.TipoRegimeEmpresa;
import model.UF;
@Named
@SessionScoped
public class EmpresaBean implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private UFRepository ufrepo;
@Inject
private EmpresaRepository emprepo;
@Inject
private CadastroEmpresaService cadastroEmpresaService;
private List<UF> ufs;
private List<Empresa> empresas;
private Empresa empresa = new Empresa();
private Empresa empresaSelecionada = new Empresa();
private UF uf = new UF();
public EmpresaBean()
{
limpar();
}
public void inicializar()
{
System.out.println("Inicializando");
if(FacesUtil.isNotPostBack())
{
ufs = ufrepo.buscarUFs();
}
}
public void visualizarEmpreas()
{
if(FacesUtil.isNotPostBack())
{
empresas = emprepo.todos();
}
}
public void salvar()
{
System.out.println("UF Selecionada: "+uf.getDssigla()+" - "+uf.getIduf());
System.out.println("Chamando o método Salvar");
this.empresa = cadastroEmpresaService.salvar(this.empresa);
limpar();
FacesUtil.addInfoMessage("Informações da Empresa Salvo Com Sucesso.");
}
public void limpar()
{
empresa = new Empresa();
ufs = null;
}
public Empresa getEmpresa()
{
return empresa;
}
public void setEmpresa(Empresa empresa)
{
this.empresa = empresa;
}
public UF getUf()
{
return uf;
}
public void setUf(UF uf)
{
this.uf = uf;
}
public List<UF> getUfs()
{
return ufs;
}
public UFRepository getUfrepo()
{
return ufrepo;
}
public void setUfrepo(UFRepository ufrepo)
{
this.ufrepo = ufrepo;
}
public CadastroEmpresaService getCadastroEmpresaService()
{
return cadastroEmpresaService;
}
public void setCadastroEmpresaService(
CadastroEmpresaService cadastroEmpresaService)
{
this.cadastroEmpresaService = cadastroEmpresaService;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
public void setUfs(List<UF> ufs)
{
this.ufs = ufs;
}
public TipoRegimeEmpresa[] getTiposRegime()
{
return TipoRegimeEmpresa.values();
}
public List<Empresa> getEmpresas()
{
return empresas;
}
public Empresa getEmpresaSelecionada()
{
System.out.println(empresaSelecionada.getNmempresa());
return empresaSelecionada;
}
public void setEmpresaSelecionada(Empresa empresaSelecionada)
{
this.empresaSelecionada = empresaSelecionada;
}
}
<file_sep>package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="PREVENDA")
public class PreVenda implements Serializable
{
private static final long serialVersionUID = 1L;
private Long id;
private String nuprevenda;
private Cliente cliente;
private Usuario vendedor;
private Date dtcadastro;
private StatusPreVenda dsstatus = StatusPreVenda.ABERTO;
private BigDecimal vlfrete = BigDecimal.ZERO;
private BigDecimal vldesconto = BigDecimal.ZERO;
private BigDecimal vltotal = BigDecimal.ZERO;
private List<ItPreVenda> itens = new ArrayList<>();
@Id
@GeneratedValue
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
@Column(name="nuprevenda", length=10)
public String getNuprevenda()
{
return nuprevenda;
}
public void setNuprevenda(String nuprevenda)
{
this.nuprevenda = nuprevenda;
}
@NotNull
@ManyToOne
@JoinColumn(name="idcliente", nullable=false)
public Cliente getCliente()
{
return cliente;
}
public void setCliente(Cliente cliente)
{
this.cliente = cliente;
}
@NotNull
@ManyToOne
@JoinColumn(name="idvendedor", nullable=false)
public Usuario getVendedor()
{
return vendedor;
}
public void setVendedor(Usuario vendedor)
{
this.vendedor = vendedor;
}
@NotNull
@Column(name="dtcadastro")
@Temporal(TemporalType.DATE)
public Date getDtcadastro()
{
return dtcadastro;
}
public void setDtcadastro(Date dtcadastro)
{
this.dtcadastro = dtcadastro;
}
@NotNull
@Enumerated(EnumType.STRING)
@Column(name="dsstatus", nullable=false, length=20)
public StatusPreVenda getDsstatus()
{
return dsstatus;
}
public void setDsstatus(StatusPreVenda dsstatus)
{
this.dsstatus = dsstatus;
}
@Column(name="vlfrete", precision = 10, scale = 2)
public BigDecimal getVlfrete()
{
return vlfrete;
}
public void setVlfrete(BigDecimal vlfrete)
{
this.vlfrete = vlfrete;
}
@Column(name="vldesconto", precision = 10, scale = 2)
public BigDecimal getVldesconto()
{
return vldesconto;
}
public void setVldesconto(BigDecimal vldesconto)
{
this.vldesconto = vldesconto;
}
@Column(name="vltotal", precision = 10, scale = 2)
public BigDecimal getVltotal()
{
return vltotal;
}
public void setVltotal(BigDecimal vltotal)
{
this.vltotal = vltotal;
}
public static long getSerialversionuid()
{
return serialVersionUID;
}
@OneToMany(mappedBy="prevenda", cascade=CascadeType.ALL, orphanRemoval=true, fetch = FetchType.LAZY)
public List<ItPreVenda> getItens()
{
return itens;
}
public void setItens(List<ItPreVenda> itens)
{
this.itens = itens;
}
@Transient
public boolean isValorTotalNegativo()
{
return this.getValorSubtotal().compareTo(BigDecimal.ZERO) < 0;
}
@Transient
public boolean isNovo()
{
return getId() == null;
}
@Transient
public boolean isExistente()
{
return !isNovo();
}
@Transient
public boolean isNaoEmissivel()
{
return !this.isEmissivel();
}
@Transient
public boolean isEmissivel()
{
return this.isExistente();
}
public void removerItemVazio()
{
ItPreVenda primeiroItem = this.getItens().get(0);
if(primeiroItem != null && primeiroItem.getProduto().getIdProduto() == null)
{
this.getItens().remove(0);
}
}
public void recalcularValorTotal()
{
BigDecimal total = BigDecimal.ZERO;
BigDecimal desconto = BigDecimal.ZERO;
total = total.add(this.getVlfrete()).subtract(this.getVldesconto());
this.setVltotal(total);
for(ItPreVenda item: this.getItens())
{
if(item.getProduto() != null && item.getProduto().getIdProduto() != null)
{
total = total.add(item.getValorTotal());
desconto = desconto.add(item.getVldesconto());
}
}
total = total.subtract(desconto);
this.setVltotal(total);
this.setVldesconto(desconto);
}
@Transient
public BigDecimal getValorSubtotal()
{
return this.getVltotal().subtract(this.getVlfrete()).add(this.getVldesconto());
}
public void adicionarItemVazio()
{
Produto produto = new Produto();
ItPreVenda item = new ItPreVenda();
item.setProduto(produto);
item.setPrevenda(this);
item.setQtitem(BigDecimal.ZERO);
item.setVlunitario(produto.getVlvenda());
// Cria a primeira linha para que ela seja editável.
this.getItens().add(0, item);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PreVenda other = (PreVenda) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import util.jsf.FacesUtil;
import model.Fornecedor;
public class FornecedorRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public Fornecedor adicionar(Fornecedor fornecedor)
{
return manager.merge(fornecedor);
}
public Fornecedor remover(Fornecedor fornecedor)
{
try
{
manager.remove(fornecedor);
manager.flush();
}catch (PersistenceException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
return fornecedor;
}
public List<Fornecedor> porRazaoSocial(String razao)
{
return this.manager.createQuery("from Fornecedor where upper(rzsocial) like :razao", Fornecedor.class)
.setParameter("razao", razao.toUpperCase()+"%")
.getResultList();
}
public List<Fornecedor> todosFornecedores()
{
return manager.createQuery("from Fornecedor", Fornecedor.class).getResultList();
}
public Fornecedor porId(Long id)
{
return manager.find(Fornecedor.class, id);
}
}
<file_sep>package curso;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.enterprise.inject.Produces;
public class FormatadorData
{
@Produces
@Brasil
public DateFormat getFormatadorDataBrasil()
{
return new SimpleDateFormat("DD 'de' MMMM 'de' YYYY", new Locale("pt", "BR"));
}
@Produces
public DateFormat getFormatadorDataEua()
{
return new SimpleDateFormat("MMMM, dd, yyyy", Locale.US);
}
}
<file_sep>package controller;
import java.io.Serializable;
import java.util.Locale;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import repository.ClienteRepository;
import model.Cliente;
import com.outjected.email.api.MailMessage;
import com.outjected.email.impl.templating.velocity.VelocityTemplate;
import util.jsf.FacesUtil;
import util.mail.Mailer;
@Named
@SessionScoped
public class ClienteEnvioEmailBean implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private Mailer mailer;
@Inject
private ClienteRepository cliRep;
public void enviarEmailCliente(Long idcliente)
{
Cliente cliente = new Cliente();
cliente = cliRep.porId(idcliente);
System.out.println("Ficha do Cliente Enviado Por e-mail: "+cliente.getNomeCliente());
MailMessage message = mailer.novaMensagem();
message.to("<EMAIL>")
.subject("Dados do Cliente")
.bodyHtml(new VelocityTemplate(getClass().getResourceAsStream("/emails/cadastroCliente.template")))
.put("cliente", cliente)
.put("locale", new Locale("pt", "BR"))
.send();
FacesUtil.addInfoMessage("Ficha de Cliente Enviada Por e-mail Com Sucesso");
}
}
<file_sep>package converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import repository.GrupoUsuarioRepository;
import service.NegocioException;
import util.cdi.CDIServiceLocator;
import util.jsf.FacesUtil;
import model.GrupoUsuario;
@FacesConverter(forClass=GrupoUsuario.class)
public class GrupoUsuarioConverter implements Converter
{
private GrupoUsuarioRepository grupoUsuarioRep;
public GrupoUsuarioConverter()
{
grupoUsuarioRep = CDIServiceLocator.getBean(GrupoUsuarioRepository.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
GrupoUsuario retorno = null;
if(value != null)
{
Long id = new Long(value);
retorno = grupoUsuarioRep.porId(id);
}
return retorno;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
String retorno = null;
if(value != null)
{
try
{
retorno = String.valueOf(((GrupoUsuario) value).getIdGrupoUsuario());
}catch(NegocioException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
}
return retorno;
}
}
<file_sep>package repository;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import service.NegocioException;
import model.UF;
public class UFRepository implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;
public List<UF> buscarUFs()
{
return manager.createQuery("from UF", UF.class).getResultList();
}
public UF porId(Long id)
{
System.out.println("Id da UF a Ser Excluida: "+id);
return manager.find(UF.class, id);
}
public UF adicionar(UF uf)
{
return manager.merge(uf);
}
public UF remover(UF uf)
{
try
{
manager.remove(uf);
//Tudo que tiver pendente de execução (marcado para exclusão por exemplo), será executado !
manager.flush();
}catch(PersistenceException p)
{
throw new NegocioException("Produto Não Pode Ser Excluído");
}
return uf;
}
}
<file_sep>package util.jsf;
import java.io.IOException;
import java.util.Iterator;
import javax.faces.FacesException;
import javax.faces.application.ViewExpiredException;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// Estamos criando um tratador de exceção do JSF. Herda de ExceptionHandlerWrapper !!
public class jsfManipuladorExcecao extends ExceptionHandlerWrapper
{
private static Log log = LogFactory.getLog(jsfManipuladorExcecao.class);
private ExceptionHandler wrapped;
public jsfManipuladorExcecao(ExceptionHandler wrapped)
{
this.wrapped = wrapped;
}
@Override
public ExceptionHandler getWrapped()
{
return this.wrapped;
}
@Override
public void handle() throws FacesException // Método que será chamado quando houver alguma exceção
{
// Classe que permite a iteração de ExceptionQueueEvent. Colocaremos todas as excecções de eventos enfileirados.
Iterator<ExceptionQueuedEvent> eventos = getUnhandledExceptionQueuedEvents().iterator();
while(eventos.hasNext())
{
ExceptionQueuedEvent event = eventos.next();
// Pego a origem da exceção contextualizada.
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
// retorna exatamente a exceção
Throwable exception = context.getException();
// Eliminar da lista do Iterator
boolean manipulado = false;
try
{
if(exception instanceof ViewExpiredException) // Verifico se a exceção veio de uma instância do ViewExpiredException
{
manipulado = true;
redirect("/login.jsf");
}else
{
manipulado = true;
log.error("Erro de Sistema." +exception.getMessage(), exception);
redirect("/Erro.jsf");
}
}finally
{
if(manipulado)
{
eventos.remove();
}
}
}
getWrapped().handle();
}
private void redirect(String page)
{
try
{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
String contextPath = externalContext.getRequestContextPath(); // retorno a raiz da nossa aplicação: Exodo
externalContext.redirect(contextPath + page);
facesContext.responseComplete();
}catch(IOException e)
{
throw new FacesException(e);
}
}
}
<file_sep>package converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import model.Cliente;
import repository.ClienteRepository;
import service.NegocioException;
import util.cdi.CDIServiceLocator;
import util.jsf.FacesUtil;
@FacesConverter(forClass=Cliente.class)
public class ClienteConverter implements Converter
{
private ClienteRepository clirep;
public ClienteConverter()
{
clirep = CDIServiceLocator.getBean(ClienteRepository.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
Cliente retorno = null;
if(value !=null)
{
Long id = new Long(value);
retorno = this.clirep.porId(id);
return retorno;
}
return null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
String resultado = null;
if(value != null)
{
try
{
resultado = String.valueOf(((Cliente) value).getIDCliente());
}catch (NegocioException e)
{
FacesUtil.addErrorMessage(e.getMessage());
}
}
return resultado;
}
}
<file_sep>package model;
public enum Sexo
{
MASCULINO, FEMININO, INDEFINIDO
}
<file_sep>package service;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import model.Substancia;
import repository.SubstanciaRepository;
import util.jpa.Transactional;
public class CadastroSubstanciaService implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private SubstanciaRepository substanciarep;
@Transactional
public Substancia salvar(Substancia substancia)
{
return substanciarep.adicionar(substancia);
}
@Transactional
public Substancia excluir(Substancia substancia)
{
substancia = substanciarep.porId(substancia.getIdSubstancia());
return substanciarep.remover(substancia);
}
public List<Substancia> todos()
{
return substanciarep.todasSubstancias();
}
}
| 16e2db019e859e00c27880e7fabae6588125cfb3 | [
"Java",
"Maven POM",
"INI"
] | 43 | Java | plinioleitecosta/exodo | 9685718e51c7a4da02571de2dc61fb30f28d952d | 8427b30609efc91b4bd79a1f1a7aae88995e5316 |
refs/heads/master | <file_sep>#!/bin/sh
OUTDIR=$1
for YEAR in "2008" "2009"
do
gdalwarp -cutline sa.shp -crop_to_cutline "nightlight/F16${YEAR}.v4b_web.stable_lights.avg_.tif" "nightlight/${YEAR}.tif"
done
for YEAR in "2010" "2011" "2012" "2013"
do
gdalwarp -cutline sa.shp -crop_to_cutline "/gpw-v4-population-count_${YEAR}.tif" "nightlight/${YEAR}.tif"
done
<file_sep>#!/bin/sh
SIZE=$1
OUTDIR=$2
for YEAR in "2011" #"2015" # "2011" "2012" "2013" "2014" "2015"
do
gdal_rasterize -burn 1 -tr $SIZE $SIZE -l "Global_3G_${YEAR}12" "Mobile Coverage Explorer WGS84 ${YEAR}12 - ESRI SHAPE/Data/Global_3G_${YEAR}12.shp" "${OUTDIR}/${YEAR}.tif"
done
<file_sep>#!/bin/sh
docker run -v ${PWD}:/home/jovyan/work --env-file .env -e SPARK_OPTS="--driver-memory 4g --jars target/scala-2.11/Pipeline.jar" -it --rm -p 8888:8888 jupyter/all-spark-notebook start-notebook.sh --NotebookApp.token=
<file_sep># Inequality Pipeline
## Introduction
This repo consists of the primary part of the data processing pipeline built for a couple of projects regarding calculating levels of inequality from satelite imagery. This is a Scala/Spark application, which is currently being run on AWS and now on Marenostrum via their custom Spark framework. It relies very heavily on [Geotrellis](https://github.com/locationtech/geotrellis), a spark geoprocessing framework.
The rest of the readme will be ordered "chronologically", documenting the steps required to go from data to calculations. I will try to highlight where work is most needed, and give some logic as to why things are structured the way they are, but there will naturally be some gaps. The codebase is quite small, and after reading this things should be fairly clear.
## Input Data
Everything we do comes from 2 separate sources of satellite imagery, both provided in raster format: one is satellite imagery of nightlight with the level of luminosity encoded from 0 to 63, the other is a constructed raster file with an estimate of the population living in the space of every pixel. There are two sources of population data, with different resolutions/origins/etc. The nightlight data also changes through time, with older files having a lower resolution.
All of these files are stored on Marenostrum's distributed file system, and currently on AWS S3 as well. I have not run the majority of this pipeline with anything but 2012/2013 data from nightlight and 2013 population data from the Landsat project.
The other type of data is best thought of as vector data (shapefiles, for instance): the areas in which we wish to aggregate data in the inequality calculations. Ideally this should be injested at-run-time, so the calculations can be run on any shapefile. Currently, we can injest either rasters or shapefiles, but have been testing primarily with rasters (this is TODO, more on this in the IO section).
## Preprocessing / Resampling
The nightlight and the population rasters do not have the same origins, and as such, we cannot simply place them on top of one another without preprocessing first. The basic idea is to create a process that will work with all raster images: resample all of them onto one common grid. Essentially this looks like:
* Define the common grid (an origin, extents, and pixel size). For robustness, one should probably pick a resolution that is higher than the resolution of any of the inputs, so that we are upsampling, and losing as little information as is reasonable.
* Use GDAL to resample the different rasters onto this grid. The docker container for GDAL is great and running it through its CLI is simple and seems to scale reasonably well. You will need to choose a different resampling scheme for the different data types: nightlight should be sampled as an image, i.e. bicubic interpolation, while the population will need to use something like nearest-neighbors (after which you will need to scale the value by multiplying by (target-pixel-area/source-pixel-area)).
Note that this area of the pipeline has NOT been formalized/built yet. I have simply run this ad-hoc for a few of the files, and have been working on those. This should be formalized somehow. It is tempting to do it on-demand in Geotrellis, but after some investigation it proved slower and buggier than simply using GDAL as a separate stage. I encourage further research into how to do this, however.
## Some Scripts for Preprocessing
#### Rasterizing a vector format.
* -a gives the layer you want to turn into the raster value
* -tr gives the pizel size
* -te gives the extent
```{sh}
gdal_rasterize -a ADM0_CODE -tr 0.0083333 0.0083333 path/to/countries.shp -te __ __ __ __ /path/to/countries.tif
```
#### Resampling
To resample, use gdalwarp.
* -ot target type (we use Float32 for both nightlight and population).
```{sh}
gdalwarp -tr SIZE SIZE -ot Float32 -te __ __ __ __ /path/to/infile.tif /path/to/outfile.tif
```
#### Reformatting
```{sh}
gdal_translate /path/to/infile.adf /path/to/outfile.tif
```
## I/O
Take a look at the IO object. Here you can see we were originally supporting S3, and have since begun the transition to Marenostrum's GPFS.
Currently shapefiles for aggregation areas are first being converted to GeoTiff format onto the same grid. There is some code in the IO class for reading shapefiles directly, and you will see in the code that you can choose the input as raster or vector, but the vector reading has not been updated to run on Marenostrum. This should be done, and tested so that this can be provided in shape rather than raster format.
## Wealth Rasters
The first part of generating the calculations is to create what can be considered an "intermediate artifact": a 2-band raster file in which one band is some proxy for wealth-per-population in that pixel (for example nightlight/population, possibly with some othe transformations), while the second band is simply the population.
The Wealth object has a main function that creates these wealth rasters and writes them into a GeoTif format, which is extremely valuable for considering the problems inherent with these data sources. For the research itself, the ability to create a wealth raster which adequately reflects wealth-per-population is crucial and non-trivial given the problems with the data. Once we have wealth rasters, the rest of the pipeline is much more stable: it consists of running calculations, of which more can be expected to be added, but which in general should be fairly stable.
One major challenge has to do with top and bottom coding of the data: nightlight peaks at a value of 63, while wealth, and population, have no upper limit. Similarly, pixels with populations of under 1 should not be used in the calculation, but also maybe those with less then 2, or 3, or...?
Currently, the only implemented methods for handling this are "crushing" the bottom (choosing the population level below which we throw out the pixel) and "topcoding" the population rasters (so that they also have an upper-truncated value: a very ad-hoc method, only useful for observing the affects of this problem).
## Grouping By Shapes
The first step in the calculations is grouping the data by the shape.
A major performance choice: do we aggregate data of one shape into to the same partition, and run calculations in parallel, or balance them evenly accross partitions, and run each step of the calculation in parallel? Currently, I implemented the latter, which is naturally very robust to extremely large and uneven sized shapes. This may or may not be the correct choice.
The GroupByShape module provides the tools for grouping both when given a raster file for the shapes (currently used), and when given a vector file for the shapes.
## Gini / Growth Calculations
Gini and Growth are the two main objects for the two main calculations. Both have a main class with a shit-ton of CLI arguments that should really be moved into a config file. Both also have a lot of shared code in that CLI parsing and prepping that should be moved somewhere.
Both follow the same basic process: read the raster files, create wealth rasters, group the data in the wealth rasters by the provided shapes, create an RDD with those values, then loop through the shapes and run the calculation on each shape, and then print out a CSV of the calculations at the end.
## Tests
Most of the test coverage is focused on the Gini/Growth calculations doing what we want, as they are simply mathematical calculations that by nature fail silently, this is important to build on, in my opinion at least, as it's nothing more than a start!
## Giving it a go
spark-submit --class edu.upf.inequality.pipeline.Growth /path/to/Pipeline.jar false /path/shapes.tif false 256 256 1024 /path/nl-2013-small.tif /path/pop-2013-small.tif 3 252 480s /path/small-3-252
<file_sep># Pipeline
## Random TODO
* Check missing values in LANDSCAN!!! (-999999)
* memory leaks??? Hadoop file reader???
## ETL - GDAL C TOOL
* Automate whole process
* Bash Script for Convert Landscan to GeoTiff.
* Landscan convert to float, resample NN, divide by 4
* NL -- convert to float, resample bicubic-spine
## Wealth Rasters / Inspection
* make multiband raster of wealth for entire world.
## Growth
* Double check invariance against multiple runs
* Put Doubles everywhere
## Performance
* Check performance of repartitioning after Wealth or GroupByShape
* Try with proper big resampled rasters
<file_sep>gini <- function(x, weights=rep(1,length=length(x))){
ox <- order(x)
x <- x[ox]
# zip and sort
weights <- weights[ox]/sum(weights)
# cumsum weights
p <- cumsum(weights)
# zip, map, cumsum
nu <- cumsum(weights*x)
# normalize nu by sum...
n <- length(nu)
nu <- nu / nu[n]
# filter RDD's by index (zip with index first)
# zip and reduce _ + _ on both separate
sum(nu[-1]*p[-n]) - sum(nu[-n]*p[-1])
}
# SCALA TESTS
gini(rep(1, 10), 1:10) # 0.0
gini(c(1,1,5,5,10,10), c(10,10,1,1,10,10)) # 0.4099379
gini(c(0.00001,1,5,5,10,10), c(1000,10,1,1,10,10)) # 0.9781078
| ee452d0fe305deb38111fd5665d56f9a9924a8ee | [
"Markdown",
"R",
"Shell"
] | 6 | Shell | nandanrao/inequality-pipeline | 4b385f837f67d0c160647a5598706e81d32df307 | 47f0df3274f9842e2d16367a997f9b18ae32f531 |
refs/heads/master | <repo_name>FoxxxHunters/elasticsearch-jaso-analyzer<file_sep>/README.md
# Korean Jaso Analyzer for elasticsearch 2.3.x
## ES Plugin change
>* AbstractPlugin => Plugin
>* [plugin-descriptor.properties]
(https://www.elastic.co/guide/en/elasticsearch/plugins/current/plugin-authors.html#plugin-authors) 프로퍼타 파일 형식 변경
*[https://github.com/imotov/elasticsearch-native-script-example](https://github.com/imotov/elasticsearch-native-script-example)
## changed
* ES 1.7x -> 2.3
## install
~~~shell
$ gradle build buildPluginZip
~~~
###### 자동완성용 한글 자소분석기입니다. elasticsearch 2.3.x 에서 테스트 되었습니다
###### *설치*
```
bin/plugin --url http://nonstop.pe.kr/elasticsearch/elasticsearch-jaso-analyzer-1.0.2.zip --install jaso-analyzer
```
###### *삭제 (필요시)*
```
bin/plugin --remove jaso-analyzer
```
###### *인덱스 삭제 (필요시)*
```
curl -XDELETE 'http://localhost:9200/jaso'
```
###### *Korean Jaso Analyer 설정 및 인덱스 생성 (기본 자소검색용)*
```
curl -XPUT localhost:9200/jaso/ -d '{
"settings": {
"index": {
"analysis": {
"filter": {
"suggest_filter": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 50
}
},
"analyzer": {
"suggest_search_analyzer": {
"type": "custom",
"tokenizer": "jaso_tokenizer"
},
"suggest_index_analyzer": {
"type": "custom",
"tokenizer": "jaso_tokenizer",
"filter": [
"suggest_filter"
]
}
}
}
}
}
}'
```
###### *Korean Jaso Analyer 설정 및 인덱스 생성 (한,영오타 및 초성토큰 추출이 필요할 때..)*
```
curl -XPUT localhost:9200/jaso/ -d '{
"settings": {
"index": {
"analysis": {
"filter": {
"suggest_filter": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 50
}
},
"tokenizer": {
"jaso_search_tokenizer": {
"type": "jaso_tokenizer",
"mistype": true,
"chosung": false
},
"jaso_index_tokenizer": {
"type": "jaso_tokenizer",
"mistype": true,
"chosung": true
}
},
"analyzer": {
"suggest_search_analyzer": {
"type": "custom",
"tokenizer": "jaso_search_tokenizer"
},
"suggest_index_analyzer": {
"type": "custom",
"tokenizer": "jaso_index_tokenizer",
"filter": [
"suggest_filter"
]
}
}
}
}
}
}'
```
###### *인덱스 맵핑*
```
curl -XPUT 'http://localhost:9200/jaso/_mapping/test' -d '{
"properties": {
"name": {
"type": "string",
"store": true,
"index_analyzer": "suggest_index_analyzer",
"search_analyzer": "suggest_search_analyzer"
}
}
}'
```
###### *인덱스타임 분석기 테스트*
```
curl -XGET 'localhost:9200/jaso/_analyze?analyzer=suggest_index_analyzer&pretty' -d '최일규 Hello'
```
###### *쿼리타임 분석기 테스트*
```
curl -XGET 'localhost:9200/jaso/_analyze?analyzer=suggest_search_analyzer&pretty' -d '최일규 Hello'
```
###### *문서생성*
```
curl -XPOST http://localhost:9200/jaso/test/ -d '{
"name":"<NAME>"
}'
curl -XPOST http://localhost:9200/jaso/test/ -d '{
"name":"초아"
}'
```
###### *문서검색*
```
curl -XPOST 'http://localhost:9200/jaso/test/_search?pretty' -d '{
"query" : {
"match" : { "name" : "초" }
}
}'
curl -XPOST 'http://localhost:9200/jaso/test/_search?pretty' -d '{
"query" : {
"match" : { "name" : "ㅊㅇㄱ" }
}
}'
```<file_sep>/build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
sourceCompatibility = 1.7
compileJava.options.encoding = 'UTF-8'
version = '1.0.2'
jar {
manifest {
attributes 'Implementation-Title': 'Elasticsearch Jaso Analyzer Plugin',
'Implementation-Version': version
}
}
repositories {
mavenCentral()
}
dependencies {
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
compile 'org.elasticsearch:elasticsearch:2.3.3'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
test {
systemProperties 'property': 'value'
}
uploadArchives {
repositories {
flatDir {
dirs 'repos'
}
}
}
//task dist(type:Zip){
// from jar.outputs.files
//}
task buildPluginZip(type: Zip, dependsOn:[':jar']) {
baseName = 'jaso-analyzer-plugin'
classifier = 'plugin'
from files(libsDir)
from 'src/main/resources'
}
// define artifacts
artifacts {
archives buildPluginZip
}
[ compileJava, compileTestJava ]*.options*.encoding = 'UTF-8'
[ compileJava, compileTestJava ]*.options*.compilerArgs = ['-Xlint:-options']
<file_sep>/src/main/java/org/elasticsearch/analysis/JasoDecomposer.java
package org.elasticsearch.analysis;
/**
* 자동완성용 자소분해 (자소분해 with WhiteSpace)
* @author 최일규
* @since 2016-02-10
*/
public class JasoDecomposer {
//초성(19자) ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ
static String[] chosungKor = { "ㄱ", "ㄱㄱ", "ㄴ" , "ㄷ" , "ㄷㄷ" , "ㄹ", "ㅁ" , "ㅂ" , "ㅂㅂ" , "ㅅ" , "ㅅㅅ" , "ㅇ" , "ㅈ" , "ㅈㅈ" , "ㅊ" , "ㅋ" , "ㅌ", "ㅍ" , "ㅎ" };
//중성(21자) ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ(9) ㅙ(10) ㅚ(11) ㅛ ㅜ ㅝ(14) ㅞ(15) ㅟ(16) ㅠ ㅡ ㅢ(19) ㅣ
static String[] jungsungKor = { "ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅗㅏ", "ㅗㅐ" , "ㅗㅣ" , "ㅛ" , "ㅜ" , "ㅜㅓ" , "ㅜㅔ" , "ㅜㅣ", "ㅠ" , "ㅡ" , "ㅡㅣ" , "ㅣ" };
//종성(28자) <없음> ㄱ ㄲ ㄳ(3) ㄴ ㄵ(5) ㄶ(6) ㄷ ㄹ ㄺ(9) ㄻ(10) ㄼ(11) ㄽ(12) ㄾ(13) ㄿ(14) ㅀ(15) ㅁ ㅂ ㅄ(18) ㅅ ㅆ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ
static String[] jongsungKor = { " ", "ㄱ", "ㄱㄱ", "ㄱㅅ" , "ㄴ" , "ㄴㅈ", "ㄴㅎ" , "ㄷ" , "ㄹ" , "ㄹㄱ" , "ㄹㅁ" , "ㄹㅂ" , "ㄹㅅ" , "ㄹㅌ" , "ㄹㅍ" , "ㄹㅎ" , "ㅁ" , "ㅂ" , "ㅂㅅ" , "ㅅ" , "ㅅㅅ" , "ㅇ" , "ㅈ" , "ㅊ" , "ㅋ" , "ㅌ", "ㅍ" , "ㅎ" };
static String[] chosungEng = { "r", "R", "s", "e", "E", "f", "a", "q", "Q" , "t" , "T" , "d" , "w" , "W" , "c" , "z" , "x" , "v" , "g" };
static String[] jungsungEng = { "k", "o", "i", "O", "j", "p", "u", "P", "h" , "hk" , "ho" , "hl" , "y" , "n" , "nj" , "np" , "nl" , "b" , "m" , "ml" , "l" };
static String[] jongsungEng = { "", "r", "R", "rt", "s", "sw", "sg", "e" , "f" , "fr" , "fa" , "fq" , "ft" , "fx" , "fv" , "fg" , "a" , "q" , "qt", "t" , "T" , "d" , "w" , "c" , "z" , "x" , "v" , "g" };
static String[] mistyping = { "ㅁ", "ㅠ", "ㅊ", "ㅇ", "ㄷ", "ㄹ", "ㅎ", "ㅗ" , "ㅑ" , "ㅓ" , "ㅏ" , "ㅣ" , "ㅡ" , "ㅜ" , "ㅐ" , "ㅔ" , "ㅂ" , "ㄱ" , "ㄴ" , "ㅅ" , "ㅕ" , "ㅍ" , "ㅈ" , "ㅌ" , "ㅛ" , "ㅋ" };
public String runJasoDecompose(String originStr, TokenizerOptions options) {
if(!originStr.isEmpty()) {
//공백, lowercase 처리
originStr = originStr.replace(" ", "");
originStr = originStr.toLowerCase();
char[] termBuffer = originStr.toCharArray();
StringBuffer korBuffer = new StringBuffer();
StringBuffer engBuffer = new StringBuffer();
StringBuffer chosungBuffer = new StringBuffer();
StringBuffer mistypingBuffer = new StringBuffer();
StringBuffer etcBuffer = new StringBuffer();
StringBuffer returnBuffer = new StringBuffer();
//첫글자가 한글일때만 초성분해
boolean firstCharType = false;
if(termBuffer. length > 0)
firstCharType = isHangul(Character.toString(termBuffer[0]));
//자소포함여부
boolean jaso = isJaso(originStr);
//한글포함여부
boolean hangul = isHangul(originStr);
//영문포함여부
boolean english = isEnglish(originStr);
int strLen = originStr.length();
int cho;
int jung;
int jong;
for(int i = 0; i < termBuffer. length; i++) {
char ch = termBuffer[i];
//가(AC00)~힣(D7A3) 에 속한 글자면 분해
if(ch >= 0xAC00 && ch <= 0xD7A3 && !jaso) {
//Unicode 값으로 환산한다.
int uniValue = ch - 0xAC00;
jong = uniValue % 28; //종성
cho = ((uniValue - jong) / 28) / 21; //초성
jung = ((uniValue - jong) / 28) % 21; //중성
//한글초성
korBuffer.append(chosungKor[cho]);
//한글에 대한 초성처리 (일반적으로 색인시 초성을 담는다.)
if(options.isChosung() && firstCharType) {
//초성은 2자이상일때 포함
if(strLen >= 2)
chosungBuffer.append(chosungKor[cho]);
}
//한글문장에 대한 영문오타처리 (ㄱ -> r)
if(options.isMistype()) {
engBuffer.append(chosungEng[cho].toLowerCase());
}
//한글중성
korBuffer.append(jungsungKor[jung]);
//한글문장에 대한 영문오타처리 (ㅏ-> k)
if(options.isMistype()) {
engBuffer.append(jungsungEng[jung].toLowerCase());
}
//받침이 있으면
if(jong != 0) {
korBuffer.append(jongsungKor[jong]);
//한글문장에 대한 영문오타처리 (ㄲ -> R)
if(options.isMistype()) {
engBuffer.append(jongsungEng[jong].toLowerCase());
}
}
} else {
if(options.isMistype()) {
if (!jaso) {
if (hangul) {
korBuffer.append(ch);
}
engBuffer.append(ch);
}
} else {
if (!jaso) {
if (hangul) {
korBuffer.append(ch);
} else {
engBuffer.append(ch);
}
}
}
//영문문장에 대한 한글오타처리 (hello -> ㅗ디ㅣㅐ)
if(options.isMistype() && !hangul) {
int index;
if(ch >= 0x61 && ch <= 0x7A) {
//소문자
index = (int) ch-97;
mistypingBuffer.append(mistyping[index]);
} else if (ch >= 0x41 && ch <= 0x5A) {
//대문자
index = (int) ch-65;
mistypingBuffer.append(mistyping[index]);
} else {
if(hangul || english)
mistypingBuffer.append(ch);
}
}
}
//추가적인 예외상황으로 추가 토큰처리 (ㅗ디ㅣㅐ -> ㅗㄷㅣㅣㅐ 자소분해)
if(jaso) {
if(ch >= 0xAC00 && ch <= 0xD7A3) {
//Unicode 값으로 환산한다.
int uniValue = ch - 0xAC00;
jong = uniValue % 28; //종성
cho = ((uniValue - jong) / 28) / 21; //초성
jung = ((uniValue - jong) / 28) % 21; //중성
etcBuffer.append(chosungKor[cho]);
etcBuffer.append(jungsungKor[jung]);
//받침이 있으면
if(jong != 0) {
etcBuffer.append(jongsungKor[jong]);
}
} else if(isJaso(Character.toString(ch))) {
//복자음 강제분리
switch(ch) {
case 'ㄲ': etcBuffer.append("ㄱㄱ"); break;
case 'ㄳ': etcBuffer.append("ㄱㅅ"); break;
case 'ㄵ': etcBuffer.append("ㄴㅈ"); break;
case 'ㄶ': etcBuffer.append("ㄴㅎ"); break;
case 'ㄺ': etcBuffer.append("ㄹㄱ"); break;
case 'ㄻ': etcBuffer.append("ㄹㅁ"); break;
case 'ㄼ': etcBuffer.append("ㄹㅂ"); break;
case 'ㄽ': etcBuffer.append("ㄹㅅ"); break;
case 'ㄾ': etcBuffer.append("ㄹㅌ"); break;
case 'ㄿ': etcBuffer.append("ㄹㅍ"); break;
case 'ㅀ': etcBuffer.append("ㄹㅎ"); break;
case 'ㅄ': etcBuffer.append("ㅂㅅ"); break;
default: etcBuffer.append(ch);
}
} else {
etcBuffer.append(ch);
}
}
}
//결과 조합
if(korBuffer.length() > 0) {
returnBuffer.append(korBuffer.toString());
returnBuffer.append(" ");
}
if(engBuffer.length() > 0) {
returnBuffer.append(engBuffer.toString());
returnBuffer.append(" ");
}
if(mistypingBuffer.length() > 0) {
returnBuffer.append(mistypingBuffer.toString());
returnBuffer.append(" ");
}
if(chosungBuffer.length() > 0) {
returnBuffer.append(chosungBuffer.toString());
returnBuffer.append(" ");
}
if(etcBuffer.length() > 0) {
returnBuffer.append(etcBuffer.toString());
returnBuffer.append(" ");
}
return returnBuffer.toString().trim();
} else {
return "";
}
}
/**
* 문자열에 한글포함 여부
* @param str
* @return
*/
private boolean isHangul(String str) {
return str.matches(".*[ㄱ-ㅎㅏ-ㅣ가-힣]+.*" );
}
/**
* 문자열에 영문포함 여부
* @param str
* @return
*/
private boolean isEnglish(String str) {
return str.matches(".*[a-zA-Z]+.*");
}
/**
* 문자열에 초성,중성 포함 여부
* @param str
* @return
*/
private boolean isJaso(String str) {
return str.matches(".*[ㄱ-ㅎㅏ-ㅣ]+.*");
}
} | 144081d7b80cd7ee45661260a0dc52fe72ce4b51 | [
"Markdown",
"Java",
"Gradle"
] | 3 | Markdown | FoxxxHunters/elasticsearch-jaso-analyzer | 3a4edd05e2e58f7083b925f530d5e551bacb9c82 | 1ef2dfd38cd311c80fac9b9cf11f10b9b4be89cd |
refs/heads/master | <repo_name>godconfidence/phaser<file_sep>/v3/src/utils/bounds/GetOffsetX.js
/**
* The amount the Game Object is visually offset from its x coordinate.
* This is the same as `width * anchor.x`.
* It will only be > 0 if anchor.x is not equal to zero.
*
* @property {number} offsetX
* @readOnly
*/
var GetOffsetX = function (gameObject)
{
return gameObject.width * gameObject.anchorX;
};
module.exports = GetOffsetX;
<file_sep>/v3/src/gameobjects/graphics/GraphicsWebGLRenderer.js
var Commands = require('./Commands');
var Earcut = require('./earcut');
var pathArray = [];
var cos = Math.cos;
var sin = Math.sin;
var sqrt = Math.sqrt;
var Point = function (x, y)
{
this.x = x;
this.y = y;
};
var Path = function (x, y)
{
this.points = [];
this.pointsLength = 1;
this.points[0] = new Point(x, y);
};
var lerp = function (norm, min, max)
{
return (max - min) * norm + min;
};
var renderLine = function (
/* start and end of line */
ax, ay, bx, by,
/* buffers */
vertexBufferF32, vertexBufferU32, vertexDataBuffer,
/* camera scroll */
cameraScrollX, cameraScrollY,
/* Camera transform */
a, b, c, d, e, f,
/* line properties */
lineColor, lineAlpha, lineWidth,
/* vertex count and limits */
vertexCount, maxVertices,
/* batch */
shapeBatch,
/* Game Object transform */
srcX, srcY, srcScaleX, srcScaleY, srcRotation
)
{
if (vertexCount + 6 > maxVertices)
{
shapeBatch.flush();
vertexCount = 0;
}
shapeBatch.vertexCount = vertexCount + 6;
ax -= cameraScrollX;
bx -= cameraScrollX;
ay -= cameraScrollY;
by -= cameraScrollY;
var vertexOffset = vertexDataBuffer.allocate(9 * 6);
var dx = bx - ax;
var dy = by - ay;
var len = sqrt(dx * dx + dy * dy);
var l0 = lineWidth * (by - ay) / len;
var l1 = lineWidth * (ax - bx) / len;
var lx0 = bx - l0;
var ly0 = by - l1;
var lx1 = ax - l0;
var ly1 = ay - l1;
var lx2 = bx + l0;
var ly2 = by + l1;
var lx3 = ax + l0;
var ly3 = ay + l1;
var x0 = lx0 * a + ly0 * c + e;
var y0 = lx0 * b + ly0 * d + f;
var x1 = lx1 * a + ly1 * c + e;
var y1 = lx1 * b + ly1 * d + f;
var x2 = lx2 * a + ly2 * c + e;
var y2 = lx2 * b + ly2 * d + f;
var x3 = lx3 * a + ly3 * c + e;
var y3 = lx3 * b + ly3 * d + f;
vertexBufferF32[vertexOffset++] = x0;
vertexBufferF32[vertexOffset++] = y0;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x1;
vertexBufferF32[vertexOffset++] = y1;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x2;
vertexBufferF32[vertexOffset++] = y2;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x1;
vertexBufferF32[vertexOffset++] = y1;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x3;
vertexBufferF32[vertexOffset++] = y3;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x2;
vertexBufferF32[vertexOffset++] = y2;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
return [
x0, y0,
x1, y1,
x2, y2,
x3, y3
];
};
var GraphicsWebGLRenderer = function (renderer, src, interpolationPercentage, camera)
{
if (this.renderMask !== this.renderFlags)
{
return;
}
var shapeBatch = renderer.shapeBatch;
var vertexDataBuffer = shapeBatch.vertexDataBuffer;
var vertexBufferF32 = vertexDataBuffer.floatView;
var vertexBufferU32 = vertexDataBuffer.uintView;
var vertexOffset = 0;
var cameraScrollX = camera.scrollX;
var cameraScrollY = camera.scrollY;
var srcX = src.x;
var srcY = src.y;
var srcScaleX = src.scaleX;
var srcScaleY = src.scaleY;
var srcRotation = src.rotation;
var commandBuffer = src.commandBuffer;
var value;
var lineAlpha = 1.0;
var fillAlpha = 1.0;
var lineColor = 0;
var fillColor = 0;
var lineWidth = 1.0;
var cameraMatrix = camera.matrix.matrix;
var a = cameraMatrix[0];
var b = cameraMatrix[1];
var c = cameraMatrix[2];
var d = cameraMatrix[3];
var e = cameraMatrix[4];
var f = cameraMatrix[5];
var lastPath = null;
var iteration = 0;
var iterStep = 0.01;
var tx = 0;
var ty = 0;
var ta = 0;
var x, y, radius, startAngle, endAngle, anticlockwise;
var width, height, txw, tyh;
var vertexCount = shapeBatch.vertexCount;
var polygon = [];
var x0, y0, x1, y1, x2, y2;
var tx0, ty0, tx1, ty1, tx2, ty2;
var v0, v1, v2;
var polygonIndex;
var path;
var pathLength;
var point;
var maxVertices = shapeBatch.maxVertices;
renderer.setBatch(shapeBatch, null);
for (var cmdIndex = 0, cmdLength = commandBuffer.length; cmdIndex < cmdLength; ++cmdIndex)
{
var cmd = commandBuffer[cmdIndex];
switch(cmd)
{
case Commands.ARC:
x = commandBuffer[cmdIndex + 1];
y = commandBuffer[cmdIndex + 2];
radius = commandBuffer[cmdIndex + 3];
startAngle = commandBuffer[cmdIndex + 4];
endAngle = commandBuffer[cmdIndex + 5];
anticlockwise = commandBuffer[cmdIndex + 6];
while (iteration < 1)
{
ta = lerp(iteration, startAngle, endAngle);
tx = x + cos(ta) * radius;
ty = y + sin(ta) * radius;
if (iteration === 0)
{
lastPath = new Path(tx, ty);
pathArray.push(lastPath);
}
else
{
lastPath.points.push(new Point(tx, ty));
}
iteration += iterStep;
}
cmdIndex += 6;
break;
case Commands.LINE_STYLE:
lineWidth = commandBuffer[cmdIndex + 1];
lineColor = commandBuffer[cmdIndex + 2];
lineAlpha = commandBuffer[cmdIndex + 3];
cmdIndex += 3;
break;
case Commands.FILL_STYLE:
fillColor = commandBuffer[cmdIndex + 1];
fillAlpha = commandBuffer[cmdIndex + 2];
cmdIndex += 2;
break;
case Commands.BEGIN_PATH:
pathArray.length = 0;
break;
case Commands.CLOSE_PATH:
if (lastPath !== null && lastPath.points.length > 0)
{
var firstPoint = lastPath.points[0];
// var lastPoint = lastPath.points[lastPath.points.length - 1];
lastPath.points.push(firstPoint);
lastPath = new Path(x, y);
pathArray.push(lastPath);
}
break;
case Commands.FILL_PATH:
for (var pathArrayIndex = 0, pathArrayLength = pathArray.length;
pathArrayIndex < pathArrayLength;
++pathArrayIndex)
{
path = pathArray[pathArrayIndex].points;
pathLength = path.length;
for (var pathIndex = 0;
pathIndex < pathLength;
++pathIndex)
{
point = path[pathIndex];
polygon.push(point.x, point.y);
}
polygonIndex = Earcut(polygon);
for (var index = 0, length = polygonIndex.length; index < length; index += 3)
{
v0 = polygonIndex[index + 0] * 2;
v1 = polygonIndex[index + 1] * 2;
v2 = polygonIndex[index + 2] * 2;
if (vertexCount + 3 > maxVertices)
{
shapeBatch.flush();
vertexCount = 0;
}
vertexOffset = vertexDataBuffer.allocate(9 * 3);
vertexCount += 3;
x0 = polygon[v0 + 0] - cameraScrollX;
y0 = polygon[v0 + 1] - cameraScrollY;
x1 = polygon[v1 + 0] - cameraScrollX;
y1 = polygon[v1 + 1] - cameraScrollY;
x2 = polygon[v2 + 0] - cameraScrollX;
y2 = polygon[v2 + 1] - cameraScrollY;
tx0 = x0 * a + y0 * c + e;
ty0 = x0 * b + y0 * d + f;
tx1 = x1 * a + y1 * c + e;
ty1 = x1 * b + y1 * d + f;
tx2 = x2 * a + y2 * c + e;
ty2 = x2 * b + y2 * d + f;
vertexBufferF32[vertexOffset++] = tx0;
vertexBufferF32[vertexOffset++] = ty0;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = tx1;
vertexBufferF32[vertexOffset++] = ty1;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = tx2;
vertexBufferF32[vertexOffset++] = ty2;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
}
polygon.length = 0;
}
break;
case Commands.STROKE_PATH:
// All of these vars are already defined (except polylines, last, curr, point0 and point1)
var pathArrayLength = pathArray.length;
var lineWidth = lineWidth * 0.5;
var pathArrayIndex, path, pathLength, pathIndex, point0, point1;
var polylines = [];
var lineColor = lineColor;
var index, length, last, curr;
var x0, y0, x1, y1, x2, y2, offset, position, color;
for (pathArrayIndex = 0; pathArrayIndex < pathArrayLength; ++pathArrayIndex)
{
path = pathArray[pathArrayIndex].points;
pathLength = path.length;
for (pathIndex = 0; pathIndex + 1 < pathLength; pathIndex += 1)
{
point0 = path[pathIndex];
point1 = path[pathIndex + 1];
polylines.push(renderLine(
point0.x, point0.y, point1.x, point1.y,
vertexBufferF32, vertexBufferU32, vertexDataBuffer,
cameraScrollX, cameraScrollY,
a, b, c, d, e, f,
lineColor, lineAlpha, lineWidth,
vertexCount, maxVertices,
shapeBatch,
srcX, srcY, srcScaleX, srcScaleY, srcRotation
));
vertexCount = shapeBatch.vertexCount;
}
if (pathArray[pathArrayIndex] === this._lastPath)
{
for (index = 1, length = polylines.length; index < length; ++index)
{
last = polylines[index - 1];
curr = polylines[index];
if (vertexCount + 6 > maxVertices)
{
shapeBatch.flush();
vertexCount = 0;
}
vertexOffset = vertexDataBuffer.allocate(9 * 6);
vertexCount += 6;
x0 = last[2 * 2 + 0] - cameraScrollX;
y0 = last[2 * 2 + 1] - cameraScrollY;
x1 = last[2 * 0 + 0] - cameraScrollX;
y1 = last[2 * 0 + 1] - cameraScrollY;
x2 = curr[2 * 3 + 0] - cameraScrollX;
y2 = curr[2 * 3 + 1] - cameraScrollY;
vertexBufferF32[vertexOffset++] = x0;
vertexBufferF32[vertexOffset++] = y0;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x1;
vertexBufferF32[vertexOffset++] = y1;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x2;
vertexBufferF32[vertexOffset++] = y2;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
x0 = last[2 * 0 + 0] - cameraScrollX;
y0 = last[2 * 0 + 1] - cameraScrollY;
x1 = last[2 * 2 + 0] - cameraScrollX;
y1 = last[2 * 2 + 1] - cameraScrollY;
x2 = curr[2 * 1 + 0] - cameraScrollX;
y2 = curr[2 * 1 + 1] - cameraScrollY;
vertexBufferF32[vertexOffset++] = x0;
vertexBufferF32[vertexOffset++] = y0;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x1;
vertexBufferF32[vertexOffset++] = y1;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x2;
vertexBufferF32[vertexOffset++] = y2;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexCount += 6;
}
}
else
{
for (index = 0, length = polylines.length; index < length; ++index)
{
last = polylines[index - 1] || polylines[polylines.length - 1];
curr = polylines[index];
if (vertexCount + 6 > maxVertices)
{
shapeBatch.flush();
vertexCount = 0;
}
vertexOffset = vertexDataBuffer.allocate(9 * 6);
vertexCount += 6;
x0 = last[2 * 2 + 0] - cameraScrollX;
y0 = last[2 * 2 + 1] - cameraScrollY;
x1 = last[2 * 0 + 0] - cameraScrollX;
y1 = last[2 * 0 + 1] - cameraScrollY;
x2 = curr[2 * 3 + 0] - cameraScrollX;
y2 = curr[2 * 3 + 1] - cameraScrollY;
vertexBufferF32[vertexOffset++] = x0;
vertexBufferF32[vertexOffset++] = y0;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x1;
vertexBufferF32[vertexOffset++] = y1;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x2;
vertexBufferF32[vertexOffset++] = y2;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
x0 = last[2 * 0 + 0] - cameraScrollX;
y0 = last[2 * 0 + 1] - cameraScrollY;
x1 = last[2 * 2 + 0] - cameraScrollX;
y1 = last[2 * 2 + 1] - cameraScrollY;
x2 = curr[2 * 1 + 0] - cameraScrollX;
y2 = curr[2 * 1 + 1] - cameraScrollY;
vertexBufferF32[vertexOffset++] = x0;
vertexBufferF32[vertexOffset++] = y0;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x1;
vertexBufferF32[vertexOffset++] = y1;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = x2;
vertexBufferF32[vertexOffset++] = y2;
vertexBufferU32[vertexOffset++] = lineColor;
vertexBufferF32[vertexOffset++] = lineAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexCount += 6;
}
}
polylines.length = 0;
}
break;
case Commands.FILL_RECT:
if (vertexCount + 6 > maxVertices)
{
shapeBatch.flush();
vertexCount = 0;
}
vertexOffset = vertexDataBuffer.allocate(9 * 6);
vertexCount += 6;
x = commandBuffer[cmdIndex + 1] - cameraScrollX;
y = commandBuffer[cmdIndex + 2] - cameraScrollY;
var xw = x + commandBuffer[cmdIndex + 3];
var yh = y + commandBuffer[cmdIndex + 4];
tx = x * a + y * c + e;
ty = x * b + y * d + f;
txw = xw * a + yh * c + e;
tyh = xw * b + yh * d + f;
vertexBufferF32[vertexOffset++] = tx;
vertexBufferF32[vertexOffset++] = ty;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = tx;
vertexBufferF32[vertexOffset++] = tyh;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = txw;
vertexBufferF32[vertexOffset++] = tyh;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = tx;
vertexBufferF32[vertexOffset++] = ty;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = txw;
vertexBufferF32[vertexOffset++] = tyh;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
vertexBufferF32[vertexOffset++] = txw;
vertexBufferF32[vertexOffset++] = ty;
vertexBufferU32[vertexOffset++] = fillColor;
vertexBufferF32[vertexOffset++] = fillAlpha;
vertexBufferF32[vertexOffset++] = srcX;
vertexBufferF32[vertexOffset++] = srcY;
vertexBufferF32[vertexOffset++] = srcScaleX;
vertexBufferF32[vertexOffset++] = srcScaleY;
vertexBufferF32[vertexOffset++] = srcRotation;
cmdIndex += 4;
break;
case Commands.LINE_TO:
if (lastPath !== null)
{
lastPath.points.push(new Point(commandBuffer[cmdIndex + 1], commandBuffer[cmdIndex + 2]));
}
else
{
lastPath = new Path(commandBuffer[cmdIndex + 1], commandBuffer[cmdIndex + 2]);
pathArray.push(lastPath);
}
cmdIndex += 2;
break;
case Commands.MOVE_TO:
lastPath = new Path(commandBuffer[cmdIndex + 1], commandBuffer[cmdIndex + 2]);
pathArray.push(lastPath);
cmdIndex += 2;
break;
default:
console.error('Phaser: Invalid Graphics Command ID ' + cmd);
break;
}
}
shapeBatch.vertexCount = vertexCount;
pathArray.length = 0;
};
module.exports = GraphicsWebGLRenderer;
<file_sep>/v3/src/renderer/webgl/batches/shape/VertexShader.js
module.exports = [
'uniform mat4 u_view_matrix;',
'attribute vec2 a_position;',
'attribute vec4 a_color;',
'attribute float a_alpha;',
'attribute vec2 a_translate;',
'attribute vec2 a_scale;',
'attribute float a_rotation;',
'varying vec4 v_color;',
'varying float v_alpha;',
'void main () {',
' float c = cos(a_rotation);',
' float s = sin(a_rotation);',
' vec2 t_position = vec2(a_position.x * c - a_position.y * s, a_position.x * s + a_position.y * c);',
' gl_Position = u_view_matrix * vec4(t_position * a_scale + a_translate, 1.0, 1.0);',
' v_color = a_color;',
' v_alpha = a_alpha;',
'}'
].join('\n');
<file_sep>/v3/src/components/Origin.js
// Origin Component
// Values are given in pixels, not percent
var Origin = {
originX: 0,
originY: 0,
setOrigin: function (x, y)
{
if (x === undefined) { x = 0; }
if (y === undefined) { y = x; }
this.originX = x;
this.originY = y;
return this;
},
setOriginToCenter: function ()
{
this.originX = this.frame.centerX;
this.originY = this.frame.centerY;
}
};
module.exports = Origin;
<file_sep>/v3/src/checksum.js
var CHECKSUM = {
build: '8a9ef8e0-ffb0-11e6-922a-fdf541bc229e'
};
module.exports = CHECKSUM; | c4205106084cbaabace0b90863c98b483f25fdfd | [
"JavaScript"
] | 5 | JavaScript | godconfidence/phaser | d034f2381ff72d422e9cdcd410a383d3ec45f119 | 110eee5887c062f7f1c267ca7f379d55d4f43046 |
refs/heads/master | <file_sep><h1>FriendFinder</h1>
<h4>Link</h4>
<p>https://intense-sierra-15811.herokuapp.com/</p>
<h4>Technology used</h4>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>Javascript</li>
<li>Express</li>
<li>Path</li>
</ul>
<h2>Description</h2>
<p>Friend FInder is an application that allows you to find a new friend based on answering the same survey questions. Click start on the homepage to be redirected to the survey. You will have to enter your name and supply an image link into the form, then proceed to answering all of the questions.</p>
<p>Be sure to answer all questions accurately to get the best result. There is form validation, so if you fail to fill in a portion of the survey, you will be prompted to fill in that part of the survey before proceeding. Once you submit your responses, the application will search through all previously entered friends to find your best match.</p>
<h2>Development</h2>
<p>This app uses bootstrap for the layout and styling, as well as for the modal which shows your friend match. It also uses a combination of express and path in order to communicate with the back end and post/get results to and from the custom made friends API made of an array of objects with other friends name, image, and survey answers.</p>
<h2>Future Development</h2>
<p>In the near future, I would like to implement a database in order to store users and their responses. At the moment, when a user submits their survey, it is stored in an existing array, and is only available to match for that session.</p><file_sep>var friends = require("../data/friends");
module.exports = function(app) {
app.get("/api/friends", function(req, res) {
res.json(friends);
});
app.post("/api/friends", function(req, res) {
let newFriend = req.body;
let newFriendTotal = 0;
for (let i = 0; i < newFriend.scores.length; i++) {
newFriend.scores[i] = parseInt(newFriend.scores[i]);
newFriendTotal += newFriend.scores[i];
}
let bestFriend = 49;
let index = 0;
let friendTotal = 0;
for (let j = 0; j < friends.length; j++) {
let friendDiff = 0;
for (let k = 0; k < friends[j].scores.length; k++) {
friendTotal += friends[j].scores[k];
friendDiff = Math.abs(newFriendTotal - friendTotal);
}
if (friendDiff <= bestFriend) {
bestFriend = friendDiff;
index = j;
}
friendTotal = 0;
}
friends.push(newFriend);
res.json(friends[index]);
});
} | 3de1f4a8567231e5e57c7aaf91f3bb3a67c719bf | [
"Markdown",
"JavaScript"
] | 2 | Markdown | cdvincent/FriendFinder | 51eadaad4db596263d1971b43806bd270709c58a | ad4cdb29caa3c425d77ae7dfe10912e3d5675721 |
refs/heads/master | <file_sep># Blog Sem Nome
## exemplos de:
- Java versão 8 ou superior: [build.gradle](https://github.com/alexNeto/blog-sem-nome/blob/master/build.gradle#L10)
- JPA com Hibernate 5 ou superior: [build.gradle](https://github.com/alexNeto/blog-sem-nome/blob/master/build.gradle#L21)
- Padrão MVC:
- [model: TopicoServico.java](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/java/com/blog/topico/TopicoServico.java)
- [view: topico.jsp](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/topico.jsp)
- [controller: TopicoControlador](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/java/com/blog/topico/TopicoControlador.java)
- Servlet anotados: [TopicoControlador](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/java/com/blog/topico/TopicoControlador.java#L14)
- Java Server Page: [topico.jsp](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/topico.jsp)
- Javascript Closure: [autenticacao.js](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/js/autenticacao.js#L47)
- Javascript DOM handler: [autenticacao.js](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/js/autenticacao.js#L90)
- Javascript event listner: [autenticacao.js](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/js/autenticacao.js#L129)
- Javascript para criar elementos do DOM dinâmcamente: [principal.js](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/js/principal.js#L79)
- Utilização de JQuery: [autenticacao.js](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/js/autenticacao.js#L3)
- Marcação HTML5: [genrencia.jsp](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/gerencia.jsp)
- Fonte externa no CSS: [fonts.css](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/css/fonts.css) [fonts](https://github.com/alexNeto/blog-sem-nome/tree/master/src/main/webapp/src/assets/fonts)
- Media Query com CSS: [mestre.css](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/webapp/src/css/mestre.css#L27)
- Configuração do MySQL: [persistence.xml](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/resources/META-INF/persistence.xml)
# Dependencias
- gradle (estou usando 4.3.1)
- tomcat v8.0
- MariaDB (estou usando o 10.2.19-MariaDB)
# Executando
- `$ git clone https://github.com/alexNeto/blog-sem-nome.git` ou baixe o zip e extraia o projeto
- `$ cd blog-sem-nome; gradle build`
- Crie um `database` com o nome de blog, `create database blog;`
- atualize as credenciais do banco de dados no [persistence.xml](https://github.com/alexNeto/blog-sem-nome/blob/master/src/main/resources/META-INF/persistence.xml) de acordo com as configurações do seu banco
- Use o plugin do tomcat do eclipse ou netbeans para rodar o tomcat, ou copie e cole o `blog.war` da pasta `build/libs` para a pasta webapp do seu tomcat
- acesse o link configurado do seu tomcat com o caminho /blog
<file_sep>package com.blog.utilitario;
import java.io.PrintWriter;
public class RespostaPadrao {
public static void json(PrintWriter resposta) {
PrintWriter returno = resposta;
returno.print("{\"status\": 200}");
returno.flush();
}
}
<file_sep>"use strict";
function apagarUsuario(identificador) {
const dado = {
identificador: identificador
};
post("restrito/gerenciar", dado, recarrega, recarrega);
function recarrega() {
location.reload();
}
}
function apagarTopico() {
const dado = {
identificador: identificadorTopico
};
get("restrito/gerenciar/topico", dado, sucesso);
function sucesso(dado) {
location.reload();
mudarParaConteudo(false);
paraTopo();
}
}
function novoTopico() {
post("restrito/gerenciar/topico", pegaDadosTopico(), sucesso);
function sucesso(dado) {
document.getElementById("titulo").value = ""
document.getElementById("texto-topico").value = ""
location.reload();
}
function pegaDadosTopico() {
return {
titulo: censura(document.getElementById("titulo").value),
conteudo: censura(document.getElementById("texto-topico").value)
};
}
}
function apagarComentario(identificador) {
const dado = {
identificador: identificador
};
get("comentario", dado, sucesso);
function sucesso(dado) {
location.reload();
}
}<file_sep>package com.blog.gerenciar;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.blog.usuario.Usuario;
import com.blog.usuario.UsuarioServico;
import com.blog.utilitario.RespostaPadrao;
import com.google.common.collect.Lists;
@WebServlet("/restrito/gerenciar")
public class GerenciaControlador extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8792656053291940932L;
@Override
protected void doGet(HttpServletRequest requisicao, HttpServletResponse resposta)
throws ServletException, IOException {
UsuarioServico usuarioServico = new UsuarioServico();
List<Usuario> usuarios = Lists.reverse(usuarioServico.pegaTodos());
requisicao.setAttribute("usuarios", usuarios);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/gerencia.jsp");
rd.forward(requisicao, resposta);
}
@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
throws ServletException, IOException {
UsuarioServico usuario = new UsuarioServico();
usuario.apagaUsuario(Long.valueOf(requisicao.getParameter("identificador")));
resposta.setContentType("application/json");
RespostaPadrao.json(resposta.getWriter());
resposta.setStatus(200);
}
}
<file_sep>"use strict";
function paraTopo() {
window.scrollTo(0, 0);
}
function encontra(texto, chave) {
return texto.indexOf(chave) !== -1 ? true : false;
}
function mostrarAreaDeComentar() {
document.getElementById("comentar").hidden = !document.getElementById(
"comentar"
).hidden;
}
function comentar() {
post("comentario", pegaComentario(), sucesso);
function sucesso(dado) {
limpaComentario();
location.reload();
}
function limpaComentario() {
document.getElementById("texto-comentario").value = "";
}
}
function pegaComentario() {
return {
conteudo: censura(document.getElementById("texto-comentario").value),
identificadorTopico: pegaIdentificadorTopico()
};
}
function pegaIdentificadorTopico() {
let url = new URL(window.location.href);
return url.searchParams.get("topico");
}
function podeEditar() {
return $("comentarios").html() == undefined;
}
function editarTopico() {
painelEdicao();
document.getElementById("titulo-edicao").value = document.getElementById(
"titulo"
).innerHTML;
document.getElementById("texto-topico").value = document.getElementById(
"conteudo"
).innerHTML;
mostrarCamposEdicaoTopico(true);
}
function mostrarCamposEdicaoTopico(mostrar) {
document.getElementById("topico-estatico").hidden = mostrar;
document.getElementById("topico-editavel").hidden = !mostrar;
}
function cancelarEdicao() {
mostrarCamposEdicaoTopico(false);
}
function enviarTopico() {
const dado = {
identificador: pegaIdentificadorTopico(),
titulo: censura(document.getElementById("titulo-edicao").value),
conteudo: censura(document.getElementById("texto-topico").value)
};
if (podeEditar()) post("restrito/gerenciar/topico/edicao", dado, sucesso);
}
function sucesso(dado) {
location.reload();
}
function painelEdicao() {
const topicoEditavel = document.getElementById("topico-editavel");
topicoEditavel.innerHTML = `
<section class="margem-conteudo-principal borda topicos">
<article class="borda">
<div class="conteudo">
<input type="text" name="titulo" id="titulo-edicao" placeholder="Título">
<textarea name="texto-comentario" id="texto-topico" placeholder="Escreva algo..."></textarea>
</div>
<div class="botao-ler">
<button id="formulario-comentar" class="botao borda botao-header" onclick="cancelarEdicao()">Cancelar</button>
<button id="formulario-comentar" class="botao borda botao-header" onclick="enviarTopico()">Enviar</button>
</div>
</article>
</section>
`;
}
function apagarComentario(identificador) {
post("restrito/gerenciar/comentario/apagar", pegaDados(), sucesso)
function pegaDados() {
return {
identificador: identificador
};
}
}<file_sep>package com.blog.comentario;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import com.blog.nucleo.ConexaoFabrica;
public class ComentarioDaoJpa implements ComentarioDao {
private static ComentarioDaoJpa instancia;
private EntityManager gerenciadorEntidade;
public static ComentarioDaoJpa pegaInstancia() {
if (instancia == null) {
instancia = new ComentarioDaoJpa();
}
return instancia;
}
private ComentarioDaoJpa() {
gerenciadorEntidade = ConexaoFabrica.pegaGerenciadorEntidade();
}
@Override
public Comentario inserir(Comentario Comentario) {
Comentario novoComentario = Comentario;
try {
gerenciadorEntidade.getTransaction().begin();
gerenciadorEntidade.persist(novoComentario);
gerenciadorEntidade.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
gerenciadorEntidade.getTransaction().rollback();
novoComentario = null;
}
return novoComentario;
}
@Override
public Comentario encontrarPeloIdentificador(Long id) {
return gerenciadorEntidade.find(Comentario.class, id);
}
@Override
public List<Comentario> encontrarPeloIdentificadorTopico(Long identificador) {
TypedQuery<Comentario> query = gerenciadorEntidade
.createQuery("FROM Comentario u WHERE u.identificadorTopico=:identificadorTopico", Comentario.class);
query.setParameter("identificadorTopico", identificador);
try {
return query.getResultList();
} catch (NoResultException e) {
return null;
}
}
@Override
public List<Comentario> encontrarPeloApelido(String apelido) {
TypedQuery<Comentario> query = gerenciadorEntidade.createQuery("FROM Comentario u WHERE u.apelido=:apelido",
Comentario.class);
query.setParameter("apelido", apelido);
try {
return query.getResultList();
} catch (NoResultException e) {
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public List<Comentario> encontrarTodos() {
return gerenciadorEntidade.createQuery("FROM " + Comentario.class.getName()).getResultList();
}
@Override
public Comentario atualizar(Comentario comentario) {
// TODO - implements
return null;
}
@Override
public boolean apaga(Comentario Comentario) {
Boolean result = true;
try {
gerenciadorEntidade.getTransaction().begin();
Comentario ComentarioParaDeletar = gerenciadorEntidade.find(Comentario.class,
Comentario.getIdentificador());
gerenciadorEntidade.remove(ComentarioParaDeletar);
gerenciadorEntidade.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
gerenciadorEntidade.getTransaction().rollback();
result = false;
}
return result;
}
@Override
public boolean apagaPeloIdentificador(Long id) {
Boolean result = true;
try {
Comentario Comentario = encontrarPeloIdentificador(id);
apaga(Comentario);
} catch (Exception ex) {
ex.printStackTrace();
result = false;
}
return result;
}
}
<file_sep>package com.blog.autenticacao.autenticacao;
import javax.servlet.http.HttpServletRequest;
import com.blog.usuario.UsuarioServico;
public class AutenticacaoServico {
protected String fazAutenticacao(HttpServletRequest requisicao) {
String usuario = requisicao.getParameter("apelido");
String senha = requisicao.getParameter("senha");
UsuarioServico usuarioServico = new UsuarioServico();
return usuarioServico.encontrar(usuario, senha);
}
}
<file_sep>package com.blog.nucleo;
public enum TipoUsuario {
ADM, NORMAL;
}<file_sep>package com.blog.usuario;
import com.blog.nucleo.Dao;
public interface UsuarioDao extends Dao<Usuario> {
public Usuario encontrarPeloNome(String nomeUsuario);
}<file_sep>"use strict";
const ajaxBody = (url, dado, type = "GET", sucesso, falha) => ({
url: pegaUrl() + url,
data: dado,
type: type,
dataType: "json",
success: sucesso,
error: falha !== undefined ? falha : erro
});
function get(url, dado, sucesso, falha) {
$.ajax(ajaxBody(url, dado, "GET", sucesso, falha));
}
function post(url, dado, sucesso, falha) {
$.ajax(ajaxBody(url, dado, "POST", sucesso, falha));
}
function erro(xhr, status, error) {
console.log("TODO - implements");
console.log(xhr, status, error);
}
function pegaUrl() {
return window.location.protocol + "//" + window.location.host + "/blog/";
}<file_sep>package com.blog.comentario;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.blog.utilitario.RespostaPadrao;
@WebServlet("/comentario")
public class ComentarioControlador extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -112315248180092748L;
@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
throws ServletException, IOException {
ComentarioServico comentario = new ComentarioServico();
if (comentario.salvaComentario(requisicao))
resposta.setStatus(200);
else
resposta.setStatus(200);
resposta.setContentType("application/json");
RespostaPadrao.json(resposta.getWriter());
}
@Override
protected void doGet(HttpServletRequest requisicao, HttpServletResponse resposta)
throws ServletException, IOException {
ComentarioServico comentario = new ComentarioServico();
comentario.apagaComentario(requisicao.getParameter("identificador"));
resposta.setStatus(200);
}
}
<file_sep>apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'java-library'
apply plugin: "eclipse"
apply plugin: "war"
group = 'com.blog'
version = '0.0.1'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile 'javax.servlet:javax.servlet-api:3.1.0'
compile group: 'jstl', name: 'jstl', version:'1.2'
compile group: 'org.hibernate', name: 'hibernate-core', version:'5.3.6.Final'
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version:'5.3.6.Final'
compile group: 'mysql', name: 'mysql-connector-java', version:'8.0.12'
compile group: 'org.json', name: 'json', version:'20180813'
compile group: 'com.thedeanda', name: 'lorem', version:'2.1'
compile group: 'com.google.guava', name: 'guava', version:'26.0-jre'
}
war {
archiveName = 'blog.war'
}<file_sep>package com.blog.usuario;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import com.blog.nucleo.ConexaoFabrica;
public class UsuarioDaoJpa implements UsuarioDao {
private static UsuarioDaoJpa instance;
private EntityManager entityManager;
public static UsuarioDaoJpa pegaInstancia() {
if (instance == null) {
instance = new UsuarioDaoJpa();
}
return instance;
}
private UsuarioDaoJpa() {
entityManager = ConexaoFabrica.pegaGerenciadorEntidade();
}
@Override
public Usuario inserir(Usuario usuario) {
Usuario novoUsuario = usuario;
try {
entityManager.getTransaction().begin();
entityManager.persist(novoUsuario);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
novoUsuario = null;
}
return novoUsuario;
}
@Override
public Usuario encontrarPeloIdentificador(Long id) {
return entityManager.find(Usuario.class, id);
}
public Usuario encontrarPeloNome(String apelido) {
TypedQuery<Usuario> query = entityManager.createQuery("FROM Usuario u WHERE u.apelido=:apelido", Usuario.class);
query.setParameter("apelido", apelido);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
@Override
public List<Usuario> encontrarTodos() {
return entityManager.createQuery("FROM " + Usuario.class.getName()).getResultList();
}
@Override
public Usuario atualizar(Usuario usuario) {
// TODO - implements
return null;
}
@Override
public boolean apaga(Usuario usuario) {
Boolean result = true;
try {
entityManager.getTransaction().begin();
Usuario usuarioParaDeletar = entityManager.find(Usuario.class, usuario.getIdentificador());
entityManager.remove(usuarioParaDeletar);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
result = false;
}
return result;
}
@Override
public boolean apagaPeloIdentificador(Long id) {
Boolean result = true;
try {
Usuario usuario = encontrarPeloIdentificador(id);
apaga(usuario);
} catch (Exception ex) {
ex.printStackTrace();
result = false;
}
return result;
}
}<file_sep>package com.blog.topico;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.blog.comentario.Comentario;
@Entity
@Table(name = "topico")
public class Topico {
@Id
@GeneratedValue
private Long identificador;
@Column
private String titulo;
@Column(columnDefinition = "text")
private String conteudo;
@Column
private String dataCriacao;
@Transient
private List<Comentario> comentarios;
public List<Comentario> getComentarios() {
return comentarios;
}
public void setComentarios(List<Comentario> comentarios) {
this.comentarios = comentarios;
}
public Long getIdentificador() {
return identificador;
}
public void setIdentificador(Long identificador) {
this.identificador = identificador;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getConteudo() {
return conteudo;
}
public String getConteudoTamanho200() {
return conteudo.substring(0, getConteudo().length() > 200 ? 200 : getConteudo().length());
}
public void setConteudo(String conteudo) {
this.conteudo = conteudo;
}
public String getDataCriacao() {
return dataCriacao;
}
public void setDataCriacao(String dataCriacao) {
this.dataCriacao = dataCriacao;
}
}
<file_sep>package com.blog.topico;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import com.blog.nucleo.ConexaoFabrica;
public class TopicoDaoJpa implements TopicoDao {
private static TopicoDaoJpa instance;
private EntityManager entityManager;
public static TopicoDaoJpa pegaInstancia() {
if (instance == null) {
instance = new TopicoDaoJpa();
}
return instance;
}
private TopicoDaoJpa() {
entityManager = ConexaoFabrica.pegaGerenciadorEntidade();
}
@Override
public Topico inserir(Topico topico) {
Topico novoTopico = topico;
try {
entityManager.getTransaction().begin();
entityManager.persist(novoTopico);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
novoTopico = null;
}
return novoTopico;
}
@Override
public Topico encontrarPeloIdentificador(Long identificador) {
return entityManager.find(Topico.class, identificador);
}
@Override
public Topico encontrarPeloIdentificador(String identificador) {
return entityManager.find(Topico.class, Long.valueOf(identificador));
}
@Override
public List<Topico> encontrarTodos() {
return entityManager.createQuery("FROM " + Topico.class.getName()).getResultList();
}
@Override
public Topico atualizar(Topico topico) {
EntityTransaction transacao = entityManager.getTransaction();
transacao.begin();
Topico novoTopico = this.encontrarPeloIdentificador(topico.getIdentificador());
novoTopico.setConteudo(topico.getConteudo());
novoTopico.setTitulo(topico.getTitulo());
transacao.commit();
return null;
}
@Override
public boolean apaga(Topico topico) {
Boolean result = true;
try {
entityManager.getTransaction().begin();
Topico topicoParaDeletar = entityManager.find(Topico.class, topico.getIdentificador());
entityManager.remove(topicoParaDeletar);
entityManager.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
result = false;
}
return result;
}
@Override
public boolean apagaPeloIdentificador(Long identificador) {
Boolean result = true;
try {
Topico topico = encontrarPeloIdentificador(identificador);
apaga(topico);
} catch (Exception ex) {
ex.printStackTrace();
result = false;
}
return result;
}
}
| 7ba167ff842ef0b28ce829314495610ab298deb1 | [
"Markdown",
"Java",
"JavaScript",
"Gradle"
] | 15 | Markdown | alexNeto-zz/blog-sem-nome | 38f11a965f39af1167f7c5f80c05f1a5fa7fd560 | 2e8125ff47e11e8d4d342cf2eb118e9eb0133b6b |
refs/heads/master | <repo_name>estaf90/aoc19<file_sep>/src/day2.py
from pathlib import Path
from utils import load_data, intcode_computer
data = load_data(Path(Path(__file__).parent, '..', 'data', 'day2.txt'))
data = data[0].split(',')
# Convert to integers
intcode_program_default = [int(item) for item in data]
print('-- Part 1 --')
# make copy of program
intcode_program = [item for item in intcode_program_default]
intcode_program[1] = 12
intcode_program[2] = 2
# read the intcode program with an intcode computer
intcode_computer(intcode_program)
print('The value left at position 0 after restoration is: ', intcode_program[0])
print('-- Part 2 --')
# make copy of program
output = 19690720
for noun in range(len(intcode_program_default)):
for verb in range(len(intcode_program_default)):
intcode_program = [item for item in intcode_program_default]
intcode_program[1] = noun
intcode_program[2] = verb
intcode_computer(intcode_program)
if intcode_program[0] == output:
print(f'Solution is: {100*noun+verb}\nFound for noun={noun} and verb={verb}')
break<file_sep>/src/utils.py
def load_data(path):
with open(path, 'r') as f:
data = []
for row in f:
data.append(row.rstrip())
return data
def intcode_computer(data):
"""Used to read incode programs"""
i = 0 # instruction pointer
cont = True
while cont:
if data[i] == 99: # opcode STOP
cont = False
elif data[i] == 1: # opcode ADD
instr = data[i:i+4]
data[instr[3]] = data[instr[1]] + data[instr[2]]
i += len(instr)
elif data[i] == 2: # opcode MULTIPLY
instr = data[i:i+4]
data[instr[3]] = data[instr[1]] * data[instr[2]]
i += len(instr)
else:
raise ValueError(f'Not understood value of {data[i]}')<file_sep>/src/day1.py
from pathlib import Path
from utils import load_data
def fuel_module(mass, fuel_included=False):
fuel = int(mass/3)-2
if not fuel_included:
return fuel
else: # go recursive
if fuel <=0:
return 0
else:
return fuel + fuel_module(fuel, fuel_included=True)
def main():
# load data
datapath = Path(Path(__file__).parent, '..', 'data', 'day1.txt')
data = load_data(datapath)
# convert to integers
data = [int(item) for item in data]
print('-- Part 1 --')
# total fuel required
fuel = sum([fuel_module(item) for item in data])
print(f'Total fuel requirement is: {fuel}')
print('-- Part 2 --')
# total fuel required
fuel = sum([fuel_module(item, fuel_included=True) for item in data])
print(f'Total fuel requirement (including fuel weight) is: {fuel}')
if __name__ == '__main__':
main() | 6ecdbbd5fa33e33a8a0d48f6e281393b3cb70456 | [
"Python"
] | 3 | Python | estaf90/aoc19 | a6f27a84ce7b52882a51ac0a2d69696951974bdd | ea2b7ad468aef6e922880901b80f7fbee073573b |
refs/heads/master | <file_sep>/**
* Genereer een willekeurig geheel getal tussen 20 en 50 (grenzen inbegrepen)
* en schrijf één van de volgende boodschappen naar de Console:
* Het willekeurig getal ligt in het interval [20,30[
* Het willekeurig getal ligt in het interval [30,40[
* Het willekeurig getal ligt in het interval [40,50]
*/
<file_sep>/**
* Vraag 2
* Een string bevat twee getallen die van elkaar gescheiden zijn door een min-teken.
* Haal het tweede getal uit de string en tel er 10 bij op.
* Je code moet algemeen bruikbaar zijn. Ze moet bijvoorbeeld ook werken als het min-teken verplaatst wordt.
* In het onderstaande geval moet er afgeprint worden in de console: Het resultaat is 4869
*/
// const orderNumber = '14284-4859';
/* Oplossing */
'use strict';
const orderNumber = '14284-4859';
const indexOfSecondNumber = orderNumber.indexOf('-') + 1;
// Je gebruikt beter substring() ipv substr() => MDN
// De expliciete conversie van de string naar een number met behulp van de Number-functie
// is hier wel degelijk nodig.
const res = Number(orderNumber.substring(indexOfSecondNumber)) + 10;
console.log(`Het resultaat is ${res}`);
<file_sep>/**
* Vraag 5
* Waarom wordt in onderstaand programma console.log() niet uitgevoerd?
*/
'use strict';
const a = '5';
const b = 5;
/* Oplossing */
// != en == voeren een 'type conversion' uit vooraleer te vergelijken.
// !== en === doen dit niet. Indien het 'data type' verschilt retourneren ze false.
// Gebruik bij voorkeur !== en ===, tenzij je weet wat je doet...
if (a !== b) {
console.log(`De string '5' is verschillend van het getal 5.`);
}
<file_sep>/**
* Vraag 3
* Vraag een getal aan de gebruiker en beeld in de console een aantal regels af met hartjes (♥),
* zoals in onderstaand voorbeeld.
*
* Voorbeeld:
*
* INPUT:
* Hoeveel regels met hartjes moeten er afgeprint worden? 4 regels
*
* OUTPUT:
* START PROGRAM
* ♥
* ♥♥
* ♥♥♥
* ♥♥♥♥
* END PROGRAM
*/
<file_sep>/**
* Vraag 1
* In de programmacode hieronder zijn sommige 'best practices' niet toegepast.
* Pas de programmacode aan zodat de geziene 'best practices' worden toegepast.
*/
// var WelcomeMessage = 'Hallo';
// name = prompt('Ho<NAME>?');
// console.log(WelcomeMessage + ' ' + name);
/* Oplossing */
// gebruik strict mode
'use strict';
// Gebruik 'const' en 'let' in plaats van 'var'.
// Class names laten we beginnen met een hoofdletter,
// maar namen van variabelen beginnen we met een kleine letter.
const welcomeMessage = 'Hallo';
// // Declareer een variabele altijd expliciet met const of let
// // en sluit een const statement af met een puntkomma;
const yourName = prompt('Ho<NAME>?');
// Gebruik template literals om de leesbaarheid te verhogen.
console.log(`${welcomeMessage} ${yourName}`);
<file_sep>/**
* Vraag 1
* In de programmacode hieronder zijn sommige 'best practices' niet toegepast.
* Pas de programmacode aan zodat de geziene 'best practices' worden toegepast.
*/
var WelcomeMessage = 'Hallo';
yourName = prompt('Hoe heet je?');
console.log(WelcomeMessage + ' ' + yourName);
<file_sep>/**
* Genereer een willekeurig geheel getal tussen 20 en 50 (grenzen inbegrepen)
* en schrijf één van de volgende boodschappen naar de Console:
* Het willekeurig getal ligt in het interval [20,30[
* Het willekeurig getal ligt in het interval [30,40[
* Het willekeurig getal ligt in het interval [40,50]
*/
/* Oplossing */
// We gebruiken Math.random() in combinatie met Math.floor()
// om willekeurige gehele getallen te genereren.
// We genereren eerst een willekeurig getal tussen 0 en 30 en
// tellen daarbij 20 op.
'use strict';
const randomNumber = Math.floor(Math.random() * 31) + 20;
let interval;
if (randomNumber < 30) {
interval = '[20,30[';
} else if (randomNumber < 40) {
interval = '[30,40[';
} else {
interval = '[40,50]';
}
console.log(`Het willekeurig getal ligt in het interval ${interval}`);
<file_sep>/**
* Vraag 3
* Vraag een getal aan de gebruiker en beeld in de console een aantal regels af met hartjes (♥),
* zoals in onderstaand voorbeeld.
*
* Voorbeeld:
*
* INPUT:
* Hoeveel regels met hartjes moeten er afgeprint worden? 4 regels
*
* OUTPUT:
* START PROGRAM
* ♥
* ♥♥
* ♥♥♥
* ♥♥♥♥
* END PROGRAM
*/
/* Oplossing */
'use strict';
const numberOfLines = parseInt(
prompt('Hoeveel regels met hartjes moeten er afgeprint worden?')
);
console.log('START PROGRAM');
for (let i = 0; i < numberOfLines; i++) {
// Een hartje ♥ kan je ook als Unicode code point (UTF-16 code) opgeven.
console.log('\u2665'.repeat(i + 1)); //of gebruik nog een for-statement
}
console.log('END PROGRAM');
| 5c3b7f7d616cafea81a200723c6da58984c3712f | [
"JavaScript"
] | 8 | JavaScript | StefCaeldries/01driloefeningen | 5e730658e6db1defc9cbde4357f872ed7dcdd263 | 511ae934335edcec2c23f7164fff90d9f97ae76f |
refs/heads/master | <repo_name>baiboat/mxnet<file_sep>/Drow_box
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import glob
import re
import cv2
class Draw(object):
def __init__(self, txt_path, img_path, save_path):
self.txt_path = txt_path
self.img_path = img_path
self.save_path = save_path
self.file_path_txt = glob.glob(r'%s/*.txt' % self.txt_path)
self.file_path_jpg = glob.glob(r'%s/*.png' % self.img_path)
def draw_box(self):
#match pattern like ['(160, 182) - (302, 431)', '(420, 171) - (535, 486)']
pattern_box = re.compile('\(\d+, \d+\) - \(\d+, \d+\)')
#match pattern like '160'
pattern_coordinate = re.compile('\d+')
try:
for i, path in enumerate(self.file_path_txt):
img = cv2.imread(self.file_path_jpg[i])
assert isinstance(path, object)
f = open(path)
content = f.read()
boxes = pattern_box.findall(content)
#all_bbox like [[xmin, ymin, xmax, ymax],...]
all_bbox = [[int(each) for each in pattern_coordinate.findall(box)] for box in boxes]
for bbox in all_bbox:
xmin, ymin, xmax, ymax = bbox
cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0,255,0), 4)
cv2.imwrite(self.save_path % i, img)
except IOError:
print u"error no such file or path"
if __name__=="__main__":
dir_txt = r"G:\gluon\PennFudanPed\Annotation"
dir_jpg = r"G:\gluon\PennFudanPed\PNGImages"
save_path = r'G:\gluon\PennFudanPed\new_img_%d.png'
draw = Draw(dir_txt, dir_jpg, save_path)
draw.draw_box()
<file_sep>/reg_gluon.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import autograd, gluon, init, nd
from mxnet.gluon import data as gdata, loss as gloss, nn
n_train = 20
n_test = 100
num_inputs = 200
true_w = nd.ones((num_inputs, 1)) * 0.01
true_b = 0.05
features = nd.random.normal(shape=(n_train+n_test, num_inputs))
labels = nd.dot(features, true_w) + true_b
labels += nd.random.normal(scale=0.01, shape=labels.shape)
train_features, test_features = features[:n_train, :], features[n_train:, :]
train_labels, test_labels = labels[:n_train], labels[n_train:]
num_epochs = 10
learning_rate = 0.003
batch_size = 1
train_iter = gdata.DataLoader(gdata.ArrayDataset(
train_features, train_labels), batch_size, shuffle=True)
loss = gloss.L2Loss()
def fit_and_plot(weight_decay):
net = nn.Sequential()
net.add(nn.Dense(1))
net.initialize(init.Normal(sigma=1))
# 对权重参数做 L2 范数正则化,即权重衰减。
trainer_w = gluon.Trainer(net.collect_params('.*weight'), 'sgd', {
'learning_rate': learning_rate, 'wd': weight_decay})
# 不对偏差参数做 L2 范数正则化。
trainer_b = gluon.Trainer(net.collect_params('.*bias'), 'sgd', {
'learning_rate': learning_rate})
train_ls = []
test_ls = []
for _ in range(num_epochs):
for X, y in train_iter:
with autograd.record():
l = loss(net(X), y)
l.backward()
# 对两个 Trainer 实例分别调用 step 函数。
trainer_w.step(batch_size)
trainer_b.step(batch_size)
train_ls.append(loss(net(train_features),
train_labels).mean().asscalar())
test_ls.append(loss(net(test_features),
test_labels).mean().asscalar())
gb.semilogy(range(1, num_epochs+1), train_ls, 'epochs', 'loss',
range(1, num_epochs+1), test_ls, ['train', 'test'])
return 'w[:10]:', net[0].weight.data()[:,:10], 'b:', net[0].bias.data()
fit_and_plot(0)<file_sep>/image-augmentation.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#%matplotlib inline
import sys
sys.path.insert(0, '..')
import gluonbook as gb
from mxnet import nd, image, gluon, init
from mxnet.gluon.data.vision import transforms
img = image.imread('G:/gluon/mxnet/img/cat1.jpg')
gb.plt.imshow(img.asnumpy())
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
Y = [aug(img) for _ in range(num_cols*num_rows)]
gb.show_images(Y, num_rows, num_cols,scale)
apply(img, transforms.RandomFlipLeftRight())
shape_aug = transforms.RandomResizedCrop((200, 200), scale=(.1, 1), ratio=(.5, 2))
apply(img, shape_aug)
apply(img, transforms.RandomLighting(.5))
apply(img, transforms.RandomHue(.5))
train_augs = transforms.Compose([
transforms.RandomFlipLeftRight(),
transforms.ToTensor(),
])
test_augs = transforms.Compose([
transforms.ToTensor(),
])
def load_cifar10(is_train, augs, batch_size):
return gluon.data.DataLoader(gluon.data.vision.CIFAR10(
train=is_train).transform_first(augs),
batch_size=batch_size, shuffle=is_train, num_workers=2)
def train(train_augs, test_augs, lr=.1):
batch_size = 256
ctx = gb.try_all_gpus()
net = gb.resnet18(10)
net.initialize(ctx=ctx, init=init.Xavier())
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':lr})
loss = gluon.loss.SoftmaxCrossEntropyLoss()
train_data = load_cifar10(True, train_augs, batch_size)
test_data = load_cifar10(False, test_augs, batch_size)
gb.train(train_data, test_data, net, loss, trainer, ctx, num_epochs=8)
train(train_augs, test_augs)<file_sep>/cnn_gluon.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from mxnet.gluon import nn
from mxnet import gluon
import sys
sys.path.append('..')
import utils
net = nn.Sequential()
with net.name_scope():
net.add(
nn.Conv2D(channels=20, kernel_size=5, activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Conv2D(channels=50, kernel_size=3, activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Flatten(),
nn.Dense(128, activation='relu'),
nn.Dense(10, activation='relu')
)
ctx = utils.try_gpu()
net.initialize(ctx=ctx)
batch_size = 256
num_epochs = 5
train_data, test_data = utils.load_data_fashion_mnist()
loss = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.5})
utils.train(train_data, test_data, net, loss, trainer, ctx, num_epochs)
<file_sep>/drop_gluon.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append("..")
import gluonbook as gb
from mxnet import autograd, gluon, init, nd
from mxnet.gluon import loss as gloss, nn
drop_prob1 = 0.2
drop_prob2 = 0.5
net = nn.Sequential()
with net.name_scope():
net.add(
nn.Dense(256, activation='relu'),
nn.Dropout((drop_prob1)),
nn.Dense(256, activation='relu'),
nn.Dropout((drop_prob2)),
nn.Dense(10)
)
net.initialize(init.Normal(sigma=0.01))
num_epochs = 5
batch_size = 256
train_iter, test_iter = gb.load_data_fashion_mnist()
loss = gloss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.05})
gb.train_cpu(net, train_iter, test_iter, loss, num_epochs, batch_size,
None, None, trainer)
<file_sep>/kaggle-dog-version2
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import shutil
import os
import pandas as pd
import mxnet as mx
from mxnet import autograd
from mxnet import gluon
from mxnet import image
from mxnet import init
from mxnet import nd
from mxnet.gluon.data import vision
from mxnet.gluon.model_zoo import vision as models
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import warnings
import mxnet as mx
from mxnet import gluon
from mxnet import ndarray as nd
from mxnet import autograd
from mxnet.gluon import nn
import h5py
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
ctx = mx.gpu(
warnings.filterwarnings("ignore")
df = pd.read_csv('labels.csv')
path = 'for_train'
if os.path.exists(path):
shutil.rmtree(path)
for i, (fname, breed) in df.iterrows():
path2 = '%s/%s' % (path, breed)
if not os.path.exists(path2):
os.makedirs(path2)
os.symlink('../../train/%s.jpg' % fname, '%s/%s.jpg' % (path2, fname))
df = pd.read_csv('sample_submission.csv')
path = 'for_test'
breed = '0'
if os.path.exists(path):
shutil.rmtree(path)
for fname in df['id']:
path2 = '%s/%s' % (path, breed)
if not os.path.exists(path2):
os.makedirs(path2)
os.symlink('../../test/%s.jpg' % fname, '%s/%s.jpg' % (path2, fname))
ctx = mx.gpu()
preprocessing = [
image.ForceResizeAug((224, 224)),
image.ColorNormalizeAug(mean=nd.array([0.485, 0.456, 0.406]), std=nd.array([0.229, 0.224, 0.225]))
]
def transform(data, label):
data = data.astype('float32') / 255
for pre in preprocessing:
data = pre(data)
data = nd.transpose(data, (2, 0, 1))
return data, nd.array([label]).asscalar().astype('float32')
def get_features(net, data):
features = []
labels = []
for X, y in tqdm(data):
feature = net.features(X.as_in_context(ctx))
features.append(feature.asnumpy())
labels.append(y.asnumpy())
features = np.concatenate(features, axis=0)
labels = np.concatenate(labels, axis=0)
return features, labels
preprocessing[0] = image.ForceResizeAug((224,224))
imgs = vision.ImageFolderDataset('for_train', transform=transform)
data = gluon.data.DataLoader(imgs, 64)
features_vgg, labels = get_features(models.vgg16_bn(pretrained=True, ctx=ctx), data)
features_resnet, _ = get_features(models.resnet152_v1(pretrained=True, ctx=ctx), data)
features_densenet, _ = get_features(models.densenet161(pretrained=True, ctx=ctx), data)
import h5py
with h5py.File('features.h5', 'w') as f:
f['vgg'] = features_vgg
f['resnet'] = features_resnet
f['densenet'] = features_densenet
f['inception'] = features_inception
f['labels'] = labels
preprocessing[0] = image.ForceResizeAug((224,224))
imgs = vision.ImageFolderDataset('for_test', transform=transform)
data = gluon.data.DataLoader(imgs, 64)
features_vgg, _ = get_features(models.vgg16_bn(pretrained=True, ctx=ctx), data)
features_resnet, _ = get_features(models.resnet152_v1(pretrained=True, ctx=ctx), data)
features_densenet, _ = get_features(models.densenet161(pretrained=True, ctx=ctx), data)
preprocessing[0] = image.ForceResizeAug((299,299))
imgs_299 = vision.ImageFolderDataset('for_test', transform=transform)
data_299 = gluon.data.DataLoader(imgs_299, 64)
features_inception, _ = get_features(models.inception_v3(pretrained=True, ctx=ctx), data)
with h5py.File('features_test.h5', 'w') as f:
f['vgg'] = features_vgg
f['resnet'] = features_resnet
f['densenet'] = features_densenet
f['inception'] = features_inception
def accuracy(output, labels):
return nd.mean(nd.argmax(output, axis=1) == labels).asscalar()
def evaluate(net, data_iter):
loss, acc, n = 0., 0., 0.
steps = len(data_iter)
for data, label in data_iter:
data, label = data.as_in_context(ctx), label.as_in_context(ctx)
output = net(data)
acc += accuracy(output, label)
loss += nd.mean(softmax_cross_entropy(output, label)).asscalar()
return loss/steps, acc/steps
with h5py.File('features.h5', 'r') as f:
features_vgg = np.array(f['vgg'])
features_resnet = np.array(f['resnet'])
features_densenet = np.array(f['densenet'])
features_inception = np.array(f['inception'])
labels = np.array(f['labels'])
features_resnet = features_resnet.reshape(features_resnet.shape[:2])
features_inception = features_inception.reshape(features_inception.shape[:2])
features = np.concatenate([features_resnet, features_densenet, features_inception], axis=-1)
X_train, X_val, y_train, y_val = train_test_split(features, labels, test_size=0.2)
dataset_train = gluon.data.ArrayDataset(nd.array(X_train), nd.array(y_train))
dataset_val = gluon.data.ArrayDataset(nd.array(X_val), nd.array(y_val))
batch_size = 128
data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle=True)
data_iter_val = gluon.data.DataLoader(dataset_val, batch_size)
net = nn.Sequential()
with net.name_scope():
net.add(nn.Dense(256, activation='relu'))
net.add(nn.Dropout(0.5))
net.add(nn.Dense(120))
net.initialize(ctx=ctx)
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': 1e-4, 'wd': 1e-5})
for epoch in range(50):
train_loss = 0.
train_acc = 0.
steps = len(data_iter_train)
for data, label in data_iter_train:
data, label = data.as_in_context(ctx), label.as_in_context(ctx)
with autograd.record():
output = net(data)
loss = softmax_cross_entropy(output, label)
loss.backward()
trainer.step(batch_size)
train_loss += nd.mean(loss).asscalar()
train_acc += accuracy(output, label)
val_loss, val_acc = evaluate(net, data_iter_val)
print("Epoch %d. loss: %.4f, acc: %.2f%%, val_loss %.4f, val_acc %.2f%%" % (
epoch + 1, train_loss / steps, train_acc / steps * 100, val_loss, val_acc * 100))
<file_sep>/softmax_regression_gluon.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from mxnet import gluon
from mxnet import autograd as ag, init
from mxnet import ndarray as nd
import gluonbook as gb
from mxnet.gluon import loss as gloss, nn
batch_size = 256
train_iter, test_iter = gb.load_data_fashion_mnist(batch_size)
net = nn.Sequential()
net.add(nn.Flatten())
net.add(nn.Dense(10))
net.initialize(init.Normal(sigma=0.01))
loss = gloss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.1})
num_epochs = 5
gb.train_cpu(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, trainer)
<file_sep>/reg_scratch.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import autograd, gluon, nd
n_train = 20
n_test = 100
num_input = 200
true_w = nd.ones((num_input, 1)) * 0.01
true_b = 0.05
features = nd.random.normal(shape=(n_train + n_test, num_input))
labels = nd.dot(features, true_w) + true_b
labels += nd.random.normal(scale=0.01, shape=labels.shape)
train_feature, test_feature = features[:n_train, :], features[n_train:, :]
train_label, test_label = labels[:n_train], labels[n_train:]
def get_params():
w = nd.random.normal(scale=1, shape=(num_input, 1))
b = nd.zeros(shape=(1,))
params = [w, b]
for param in params:
param.attach_grad()
return params
def l2_penalty(w):
return (w**2).sum() / 2
batch_size = 1
num_epochs = 10
lr = 0.003
net = gb.linreg
loss = gb.squared_loss
#InlineBackend.figure_format = 'retina'
gb.plt.rcParams['figure.figsize'] = (3.5, 2.5)
def fit_and_plot(lambd):
w, b = params = get_params()
train_ls = []
test_ls = []
for _ in range(num_epochs):
for X, y in gb.data_iter(batch_size, n_train, features, labels):
with autograd.record():
l = loss(net(X, w, b), y) + lambd * l2_penalty(w)
l.backward()
gb.sgd(params, lr, batch_size)
train_ls.append(loss(net(train_feature, w, b),
train_label).mean().asscalar())
test_ls.append(loss(net(test_feature, w, b),
test_label).mean().asscalar())
gb.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss',
range(1, num_epochs + 1), test_ls, ['train', 'test'])
return 'w[:10]:', w[:10].T, 'b:', b
fit_and_plot(lambd=5)
<file_sep>/softmax_regression_scratch.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import autograd as ag
from mxnet import ndarray as nd
from mxnet.gluon import data as gdata
def transform(feature, label):
return feature.astype('float32') / 255, label.astype('float32')
mnist_train = gdata.vision.FashionMNIST(train=True, transform=transform)
mnist_test = gdata.vision.FashionMNIST(train=False, transform=transform)
batch_size = 256
def get_text_labels(labels):
text_labels = [
't-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'
]
return [text_labels[int(i)] for i in labels]
def show_fashion_imgs(images):
n = images.shape[0]
_,figs = gb.plt.subplots(1, n, figsize=(15, 15))
for i in range(n):
figs[i].imshow(images[i].reshape((28,28)).asnumpy())
figs[i].axes.get_xaxis().set_visible(False)
figs[i].axes.get_yaxis().set_visible(False)
gb.plt.show()
X, y = mnist_train[0:9]
show_fashion_imgs(X)
train_iter = gdata.DataLoader(mnist_train, batch_size, shuffle=True)
test_iter = gdata.DataLoader(mnist_test, batch_size, shuffle=False)
num_input = 784
num_output = 10
w = nd.random.normal(scale=0.01, shape=(num_input, num_output))
b = nd.zeros(shape=(1, num_output))
params = [w, b]
for param in params:
param.attach_grad()
def softmax(X):
exp = X.exp()
partition = exp.sum(axis=1, keepdims=True)
return exp / partition
def net(X):
return softmax(nd.dot(X.reshape((-1, num_input)), w) + b)
def cross_entropy(y_hat, y):
return -nd.pick(y_hat.log(), y)
def accuracy(y_hat, y):
return (y_hat.argmax(axis=1) == y).mean().asscalar()
def evaluate_accuracy(data_iter, net):
acc = 0
for X,y in data_iter:
acc += accuracy(net(X), y)
return acc / len(data_iter)
num_epochs = 5
lr = 0.1
loss = cross_entropy
def train_cpu(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, trainer=None):
for epoch in range(1, num_epochs + 1):
train_l_sum = 0
train_acc_sum = 0
for X, y in train_iter:
with ag.record():
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
if trainer is None:
gb.sgd(params, lr, batch_size)
else:
trainer.step(batch_size)
train_l_sum += l.mean().asscalar()
train_acc_sum += accuracy(y_hat, y)
test_acc = evaluate_accuracy(test_iter, net)
print("epoch %d, loss %.4f, train acc %.3f, test acc %.3f"
% (epoch, train_l_sum / len(train_iter),
train_acc_sum / len(train_iter), test_acc))
train_cpu(net, train_iter, test_iter, loss, num_epochs, batch_size, params,lr)<file_sep>/NiN.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from mxnet.gluon import nn
def mlpconv(channels, kernel_size, padding, strides=1, max_pooling=True):
out = nn.Sequential()
out.add(
nn.Conv2D(channels=channels, kernel_size=kernel_size, strides=strides, padding=padding, activation='relu'),
nn.Conv2D(channels=channels, kernel_size=1, strides=strides, padding=0, activation='relu'),
nn.Conv2D(channels=channels, kernel_size=1, strides=strides, padding=0, activation='relu'),
)
if max_pooling:
out.add(nn.MaxPool2D(pool_size=3, strides=2))
return out
net = nn.Sequential()
with net.name_scope():
net.add(
mlpconv(channels=96, kernel_size=11, padding=0, strides=4),
mlpconv(channels=256, kernel_size=5, padding=2),
mlpconv(channels=384, kernel_size=3, padding=1),
nn.Dropout(.5),
mlpconv(10, 3, 1, max_pooling=False),
nn.GlobalAvgPool2D(),
nn.Flatten()
)
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import gluon
from mxnet import init
train_data, test_data = gb.load_data_fashion_mnist(batch_size=64, resize=224)
ctx = gb.try_gpu()
net.initialize(ctx=ctx, init=init.Xavier())
loss = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.1})
gb.train(train_data, test_data, net, loss, trainer, ctx, 5)<file_sep>/Alexnet.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from mxnet.gluon import nn
net = nn.Sequential()
with net.name_scope():
net.add(
nn.Conv2D(channels=96, kernel_size=11, strides=4, activation='relu'),
nn.MaxPool2D(pool_size=3, strides=2),
nn.Conv2D(256, kernel_size=5, padding=2, activation='relu'),
nn.MaxPool2D(pool_size=3, strides=2),
nn.Conv2D(channels=384, kernel_size=3, padding=1, activation='relu'),
nn.Conv2D(channels=384, kernel_size=3, padding=1, activation='relu'),
nn.Conv2D(channels=256, kernel_size=3, padding=1, activation='relu'),
nn.MaxPool2D(pool_size=3, strides=2),
nn.Flatten(),
nn.Dense(4096, activation='relu'),
nn.Dropout(0.5),
nn.Dense(4096, activation='relu'),
nn.Dropout(0.5),
nn.Dense(10)
)
import gluonbook as gb
from mxnet import autograd, gluon, init, nd
from mxnet.gluon import loss as gloss
import sys
sys.path.append('..')
import utils
ctx = utils.try_gpu()
net.initialize()
train_iter, test_iter = utils.load_data_fashion_mnist(batch_size=64, resize=224)
loss = gloss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.05})
utils.train(test_iter, test_iter, net, loss, trainer, ctx, num_epochs=1)
<file_sep>/mlp_gluon.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import autograd, gluon, nd, init
from mxnet.gluon import loss as gloss, nn
net = nn.Sequential()
net.add(nn.Flatten())
net.add(nn.Dense(256, activation='relu'))
net.add(nn.Dense(10))
net.initialize(init.Normal(sigma=0.01))
batch_size = 256
train_iter, test_iter = gb.load_data_fashion_mnist(batch_size)
loss = gloss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.01})
num_epochs = 5
gb.train_cpu(net, train_iter, test_iter, loss, num_epochs, batch_size,None, None, trainer)<file_sep>/linear_regression_scratchcopy.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import mxnet.ndarray as nd
import mxnet.autograd as ag
import random
num_examples = 1000
num_input = 2
ture_w = [2, -3.4]
ture_b = 4.2
features = nd.random.normal(scale=1, shape=(num_examples, num_input))
labels = ture_w[0] * features[:, 0] + ture_w[1] * features[:, 1] + ture_b
labels += nd.random.normal(scale=0.01, shape=labels.shape)
batch_size = 10
def data_iter(num_examples, batch_size, features, labels):
index = list(range(num_examples))
random.shuffle(index)
for i in range(0, num_examples, batch_size):
j = index(i:i+batch_size)
yield features.take(j), labels.take(j)
w = nd.random.normal(scale=1, shape=(1,num_input))
b = nd.zeros(shape=(1, ))
param = [w,b]
def net(X, w, b):
return nd.dot(X, w) + b
def squred_loss(Y_hat, Y):
return (Y_hat - Y) ** 2 / 2
def sgd(params, lr):
for param in params:
param[:] = param - lr * param.grad
lr = 0.01
epochs = 5
total_loss = 0
for i in range(epochs):
for X,Y in data_iter(num_examples, batch_size, features, labels)
with ag.record():
Y_hat = net(X, w, b)
loss = squred_loss(Y_hat, Y)
loss.backward()
sgd([w,b], lr)
print "epoch %d loss is %f"%(i,loss(net(features, w, b)).means().asnumpy())
<file_sep>/linear-regression-scratch.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import mxnet.ndarray as nd
import mxnet.autograd as ag
import random
num_inputs = 2
num_examples = 1000
true_w = [2,-3.4]
true_b = 4.2
features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))
labels = true_w[0] * features[:,0] + true_w[1] * features[:,1] + true_b
labels += nd.random.normal(scale=0.01, shape=labels.shape)
batch_size = 10
def data_iter(batch_size, num_examples, features, labels):
indices = list(range(num_examples))
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
j = nd.array(indices[i: min(i+batch_size, num_examples)])
yield features.take(j), labels.take(j)
w = nd.random.normal(scale=0.01, shape=(num_inputs, 1))
b = nd.zeros(shape=(1,))
params = [w,b]
for param in params:
param.attach_grad()
def net(X, w, b,):
return nd.dot(X, w) + b
def squared_loss(Y_hat, Y):
return (Y_hat - Y.reshape(Y_hat.shape)) ** 2 / 2
def sgd(params, lr, batch_size):
for param in params:
param[:] = param - lr * param.grad / batch_size
lr = 0.01
epochs = 10
total_loss = 0
for i in range(epochs):
for X,Y in data_iter(batch_size, num_examples, features, labels):
with ag.record():
Y_hat = net(X, w, b)
loss = squared_loss(Y_hat, Y)
loss.backward()
sgd([w,b], lr, batch_size)
print "epoch %d total_loss is %f"% (i+1,squared_loss(net(features, w, b), labels).mean().asnumpy())
print true_w, w
print true_b, b
<file_sep>/cnn_scratch.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
from mxnet import ndarray as nd, autograd
from mxnet import gluon
from utils import load_data_fashion_mnist, accuracy, evaluate_accuracy
import gluonbook as gb
batch_size = 256
train_data, test_data = load_data_fashion_mnist(batch_size)
import mxnet as mx
try:
ctx = mx.gpu()
_ = nd.zreos((1, ),ctx=ctx)
except:
ctx = mx.cpu()
weight_scale = 0.01
W1 = nd.random.normal(shape=(20, 1, 5, 5), scale=weight_scale, ctx=ctx)
b1 = nd.zeros(W1.shape[0], ctx=ctx)
W2 = nd.random.normal(shape=(50, 20, 3, 3), scale=weight_scale, ctx=ctx)
b2 = nd.zeros(W2.shape[0], ctx=ctx)
W3 = nd.random.normal(shape=(1250, 128), scale=weight_scale, ctx=ctx)
b3 = nd.zeros(W3.shape[1], ctx=ctx)
W4 = nd.random.normal(shape=(128, 10), scale=weight_scale, ctx=ctx)
b4 = nd.zeros(W4.shape[1], ctx=ctx)
params = [W1, b1, W2, b2, W3, b3, W4, b4]
for param in params:
param.attach_grad()
def net(X, verbose=False):
X = X.as_in_context(W1.context)
h1_conv = nd.Convolution(data=X, weight=W1, bias=b1, kernel=W1.shape[2:], num_filter=W1.shape[0])
h1_activation = nd.relu(h1_conv)
h1 = nd.Pooling(data=h1_activation, pool_type="max", kernel=(2,2), stride=(2,2))
h2_conv = nd.Convolution(data=h1, weight=W2, bias=b2, kernel=W2.shape[2:], num_filter=W2.shape[0])
h2_activation = nd.relu(h2_conv)
h2 = nd.Pooling(data=h2_activation, pool_type="max", kernel=(2, 2), stride=(2, 2))
h2 = nd.flatten(h2)
h3_linear = nd.dot(h2, W3) + b3
h3 = nd.relu(h3_linear)
h4_linear = nd.dot(h3, W4) + b4
if verbose:
print('1st conv block:', h1.shape)
print('2nd conv block:', h2.shape)
print('1st dense:', h3.shape)
print('2nd dense:', h4_linear.shape)
print('output:', h4_linear)
return h4_linear
for data, _ in train_data:
net(data, verbose=True)
break
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()
learning_rate = .2
epochs = 5
for _ in range(epochs):
train_loss = 0.
train_acc = 0.
for data,label in train_data:
label = label.as_in_context(ctx)
with autograd.record():
Y_hat = net(data)
l = softmax_cross_entropy(Y_hat)
l.backward()
gb.sgd(params, learning_rate, batch_size)
train_loss += nd.mean(l).asscalar()
train_acc += accuracy(Y_hat, label)
test_acc = evaluate_accuracy(test_data, net, ctx)
print("Epoch %d. Loss: %f, Train acc %f, Test acc %f" % (
epoch, train_loss / len(train_data),
train_acc / len(train_data), test_acc))
<file_sep>/dropout_scratch.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import autograd, gluon, nd
from mxnet.gluon import loss as gloss
def dropout(X, drop_prob):
assert 0 <= drop_prob <= 1
keep_prob = 1 - drop_prob
if keep_prob == 0:
return X.zeros_like()
mask = nd.random.uniform(0, 1, X.shape) < keep_prob
return mask * X / keep_prob
num_inputs = 784
num_outputs = 10
num_hiddens1 = 256
num_hiddens2 = 256
W1 = nd.random.normal(scale=0.01, shape=(num_inputs, num_hiddens1))
b1 = nd.zeros(num_hiddens1)
W2 = nd.random.normal(scale=0.01, shape=(num_hiddens1, num_hiddens2))
b2 = nd.zeros(num_hiddens2)
W3 = nd.random.normal(scale=0.01, shape=(num_hiddens2, num_outputs))
b3 = nd.zeros(num_outputs)
params = [W1, b1, W2, b2, W3, b3]
for param in params:
param.attach_grad()
drop_prob1 = 0.2
drop_prob2 = 0.5
def net(X):
X = X.reshape(-1, num_inputs)
H1 = (nd.dot(X, W1) + b1).relu()
if autograd.is_training():
H1 = dropout(H1, drop_prob1)
H2 = (nd.dot(H1, W2) + b2).relu()
if autograd.is_training():
H2 = dropout(H2, drop_prob2)
return nd.dot(H2, W3) + b3
num_epochs = 5
lr = 0.5
batch_size = 256
loss = gloss.SoftmaxCrossEntropyLoss()
train_iter, test_iter = gb.load_data_fashion_mnist(batch_size)
gb.train_cpu(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)
<file_sep>/mlp_scratch.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import gluonbook as gb
from mxnet import ndarray as nd
from mxnet.gluon import loss as gloss
from mxnet import autograd as ag
import utils
batch_size = 256
train_iter, test_iter = gb.load_data_fashion_mnist(batch_size)
num_input = 28 * 28
num_output = 10
hidden = 20
scale_param = 0.01
w1 = nd.random.normal(scale=scale_param, shape=(num_input, hidden))
b1 = nd.zeros(shape=(hidden, ))
w2 = nd.random.normal(scale=scale_param, shape=(hidden, num_output))
b2 = nd.zeros(shape=(num_output, ))
params = [w1, b1, w2, b2]
for param in params:
param.attach_grad()
def relu(X):
return nd.maximum(X, 0)
def net(X):
X = X.reshape((-1, num_input))
h1 = relu(nd.dot(X, w1) + b1)
output = nd.dot(h1, w2) + b2
return output
loss = gloss.SoftmaxCrossEntropyLoss()
epochs = 5
learning_rate = 0.01
train_loss = 0.
train_acc = 0.
for i in range(epochs):
for X,Y in train_iter:
with ag.record():
Y_hat = net(X)
l = loss(Y_hat, Y)
l.backward()
utils.SGD(params, learning_rate / batch_size)
train_loss += nd.mean(l).asscalar()
train_acc += utils.accuracy(Y_hat, Y)
test_acc = utils.evaluate_accuracy(test_iter, net)
print "Epoch %d train_loss %f train_acc %f test_acc %f" % (i, train_loss/len(train_iter), train_acc/len(train_iter), test_acc)
<file_sep>/kaggle-dog
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
sys.path.append('..')
import collections
import datetime
import gluonbook as gb
import math
from mxnet import autograd, gluon, init, nd
from mxnet.gluon import data as gdata, loss as gloss, model_zoo, nn
from mxnet.gluon.data.vision import transforms
import numpy as np
import os
import shutil
import zipfile
from collections import Counter
demo = False
data_dir = '../data/kaggle_dog'
if demo:
zipfiles= ['train_valid_test_tiny.zip']
else:
zipfiles= ['train.zip', 'test.zip', 'labels.csv.zip']
for f in zipfiles:
with zipfile.ZipFile(data_dir + '/' + f, 'r') as z:
z.extractall(data_dir)
def reorg_dog_data(data_dir, label_file, train_dir, test_dir, input_dir,
valid_ratio):
# 读取训练数据标签。
with open(os.path.join(data_dir, label_file), 'r') as f:
# 跳过文件头行(栏名称)。
lines = f.readlines()[1:]
tokens = [l.rstrip().split(',') for l in lines]
idx_label = dict(((idx, label) for idx, label in tokens))
labels = set(idx_label.values())
num_train = len(os.listdir(os.path.join(data_dir, train_dir)))
# 训练集中数量最少一类的狗的数量。
min_num_train_per_label = (
Counter(idx_label.values()).most_common()[:-2:-1][0][1])
# 验证集中每类狗的数量。
num_valid_per_label = math.floor(min_num_train_per_label * valid_ratio)
label_count = dict()
def mkdir_if_not_exist(path):
if not os.path.exists(os.path.join(*path)):
os.makedirs(os.path.join(*path))
# 整理训练和验证集。
for train_file in os.listdir(os.path.join(data_dir, train_dir)):
idx = train_file.split('.')[0]
label = idx_label[idx]
mkdir_if_not_exist([data_dir, input_dir, 'train_valid', label])
shutil.copy(os.path.join(data_dir, train_dir, train_file),
os.path.join(data_dir, input_dir, 'train_valid', label))
if label not in label_count or label_count[label] < num_valid_per_label:
mkdir_if_not_exist([data_dir, input_dir, 'valid', label])
shutil.copy(os.path.join(data_dir, train_dir, train_file),
os.path.join(data_dir, input_dir, 'valid', label))
label_count[label] = label_count.get(label, 0) + 1
else:
mkdir_if_not_exist([data_dir, input_dir, 'train', label])
shutil.copy(os.path.join(data_dir, train_dir, train_file),
os.path.join(data_dir, input_dir, 'train', label))
# 整理测试集。
mkdir_if_not_exist([data_dir, input_dir, 'test', 'unknown'])
for test_file in os.listdir(os.path.join(data_dir, test_dir)):
shutil.copy(os.path.join(data_dir, test_dir, test_file),
os.path.join(data_dir, input_dir, 'test', 'unknown'))
if demo:
# 注意:此处使用小数据集为便于网页编译。
input_dir = 'train_valid_test_tiny'
# 注意:此处相应使用小批量。对Kaggle的完整数据集可设较大的整数,例如128。
batch_size = 2
else:
label_file = 'labels.csv'
train_dir = 'train'
test_dir = 'test'
input_dir = 'train_valid_test'
batch_size = 128
valid_ratio = 0.1
reorg_dog_data(data_dir, label_file, train_dir, test_dir, input_dir,
valid_ratio)
transform_train = transforms.Compose([
# transforms.CenterCrop(32)
# transforms.RandomFlipTopBottom(),
# transforms.RandomColorJitter(brightness=0.0, contrast=0.0, saturation=0.0, hue=0.0),
# transforms.RandomLighting(0.0),
# transforms.Cast('float32'),
# 将图片按比例放缩至短边为256像素
transforms.Resize(256),
# 随机按照scale和ratio裁剪,并放缩为224x224的正方形
transforms.RandomResizedCrop(224, scale=(0.08, 1.0), ratio=(3.0/4.0, 4.0/3.0)),
# 随机左右翻转图片
transforms.RandomFlipLeftRight(),
# 将图片像素值缩小到(0,1)内,并将数据格式从"高*宽*通道"改为"通道*高*宽"
transforms.ToTensor(),
# 对图片的每个通道做标准化
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# 去掉随机裁剪/翻转,保留确定性的图像预处理结果
transform_test = transforms.Compose([
transforms.Resize(256),
# 将图片中央的224x224正方形区域裁剪出来
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
input_str = data_dir + '/' + input_dir + '/'
# 读取原始图像文件。flag=1说明输入图像有三个通道(彩色)。
train_ds = vision.ImageFolderDataset(input_str + 'train', flag=1)
valid_ds = vision.ImageFolderDataset(input_str + 'valid', flag=1)
train_valid_ds = vision.ImageFolderDataset(input_str + 'train_valid', flag=1)
test_ds = vision.ImageFolderDataset(input_str + 'test', flag=1)
loader = gluon.data.DataLoader
train_data = loader(train_ds.transform_first(transform_train),
batch_size, shuffle=True, last_batch='keep')
valid_data = loader(valid_ds.transform_first(transform_test),
batch_size, shuffle=True, last_batch='keep')
train_valid_data = loader(train_valid_ds.transform_first(transform_train),
batch_size, shuffle=True, last_batch='keep')
test_data = loader(test_ds.transform_first(transform_test),
batch_size, shuffle=False, last_batch='keep')
# 交叉熵损失函数。
softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss()
def get_net(ctx):
# 设置 pretrained=True 就能拿到预训练模型的权重,第一次使用需要联网下载
finetune_net = models.resnet34_v2(pretrained=True)
# 定义新的输出网络
finetune_net.output_new = nn.HybridSequential(prefix='')
# 定义256个神经元的全连接层
finetune_net.output_new.add(nn.Dense(256, activation='relu'))
# 定义120个神经元的全连接层,输出分类预测
finetune_net.output_new.add(nn.Dense(120))
# 初始化这个输出网络
finetune_net.output_new.initialize(init.Xavier(), ctx=ctx)
# 把网络参数分配到即将用于计算的CPU/GPU上
finetune_net.collect_params().reset_ctx(ctx)
return finetune_net
def get_loss(data, net, ctx):
loss = 0.0
for feas, label in data:
label = label.as_in_context(ctx)
# 计算特征层的结果
output_features = net.features(feas.as_in_context(ctx))
# 将特征层的结果作为输入,计算全连接网络的结果
output = net.output_new(output_features)
cross_entropy = softmax_cross_entropy(output, label)
loss += nd.mean(cross_entropy).asscalar()
return loss / len(data)
def train(net, train_data, valid_data, num_epochs, lr, wd, ctx, lr_period,
lr_decay):
# 只在新的全连接网络的参数上进行训练
trainer = gluon.Trainer(net.output_new.collect_params(),
'sgd', {'learning_rate': lr, 'momentum': 0.9, 'wd': wd})
prev_time = datetime.datetime.now()
for epoch in range(num_epochs):
train_loss = 0.0
if epoch > 0 and epoch % lr_period == 0:
trainer.set_learning_rate(trainer.learning_rate * lr_decay)
for data, label in train_data:
label = label.astype('float32').as_in_context(ctx)
# 正向传播计算特征层的结果
output_features = net.features(data.as_in_context(ctx))
with autograd.record():
# 将特征层的结果作为输入,计算全连接网络的结果
output = net.output_new(output_features)
loss = softmax_cross_entropy(output, label)
# 反向传播与权重更新只发生在全连接网络上
loss.backward()
trainer.step(batch_size)
train_loss += nd.mean(loss).asscalar()
cur_time = datetime.datetime.now()
h, remainder = divmod((cur_time - prev_time).seconds, 3600)
m, s = divmod(remainder, 60)
time_str = "Time %02d:%02d:%02d" % (h, m, s)
if valid_data is not None:
valid_loss = get_loss(valid_data, net, ctx)
epoch_str = ("Epoch %d. Train loss: %f, Valid loss %f, "
% (epoch, train_loss / len(train_data), valid_loss))
else:
epoch_str = ("Epoch %d. Train loss: %f, "
% (epoch, train_loss / len(train_data)))
prev_time = cur_time
print(epoch_str + time_str + ', lr ' + str(trainer.learning_rate))
ctx = gb.try_gpu()
num_epochs = 1
learning_rate = 0.01
weight_decay = 1e-4
lr_period = 10
lr_decay = 0.1
net = get_net(ctx)
net.hybridize()
train(net, train_data, valid_data, num_epochs, learning_rate,
weight_decay, ctx, lr_period, lr_decay)
| 01a6576400c435113608eb49ace654de0acb63ad | [
"Python"
] | 18 | Python | baiboat/mxnet | 6c2248f13631b3810f1c776da6690726e74a9031 | 711beec541ff5fb65bc7b4943183fb6138e20eac |
refs/heads/main | <file_sep>import React from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import './App.css';
import Search from './components/Search';
import AllocateFund from './components/AllocateFund';
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/" exact component={Search} />
<Route path="/allocateFund" exact component={AllocateFund} />
</Switch>
</Router>
</div>
);
}
export default App
<file_sep>import React, {useState, useEffect} from "react";
import '../App.css';
import { Link } from 'react-router-dom';
function Search() {
const [searchTerm, setSearchTerm] = useState("");
const [searchResults, setSearchResults] = useState([]);
const [checkedResults, setCheckedResults] = useState([]);
const handleChange = event => {
setSearchTerm(event.target.value);
};
const handleChecked = event => {
if(event.target.checked === true){
setCheckedResults([...checkedResults, event.target.value]);
}
if(event.target.checked === false){
var index = checkedResults.indexOf(event.target.value);
if(index !== -1) setCheckedResults([...checkedResults.slice(0,index), ...checkedResults.slice(index+1)]);
}
};
useEffect(() => {
fetch('http://www.mocky.io/v2/5e3415ce3000008900d962b1/')
.then(results => results.json())
.then(data => {
// console.log(data.content[0].fund_name);
const funds = data.content.filter(fund =>
fund.fund_name.toLowerCase().includes(searchTerm)
);
setSearchResults(funds);
});
}, [searchTerm]);
return (
<div className="App">
<input
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleChange}
/>
<ul style={{display : 'flex', flexWrap:'wrap'}}>
{searchResults.map((fund, index) => (
<li key={index}><div className="Card">
<span>{fund.fund_name}</span><br/>
<span>{fund.category}</span><br/>
<span>{fund.return1y}</span><br/>
<input type="checkbox" onChange={handleChecked} value={fund.fund_name}/>
</div></li>
))}
</ul>
<Link id="fixedbutton" to={{ pathname: "/allocateFund",state: { funds: checkedResults }}}>Next</Link>
</div>
);
}
export default Search
<file_sep>import React, {useState} from "react";
import '../App.css';
const AllocateFund = (props) => {
const [input, setInput] = useState(0);
const [inputs,setInputs] = useState({});
//console.log(inputs);
return (
<div>
<form>
<label> Total amount to be invested : <input value={input} onInput={e => setInput(e.target.value)}/> </label>
</form>
<table id="allocationTable">
<thead>
<tr>
<th>Funds</th>
<th>Percentage</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{props.location.state.funds.map((fund,index) => (
<tr key={fund}>
<td>{fund}</td>
<td><input name={fund} onInput={({target}) => setInputs(state => ({...state, [target.name] :target.value}))} value={inputs.fund}/></td>
<td>{input*inputs[`${fund}`]/100}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default AllocateFund
| 79a73ff7f7bf6a2a7fdc0eb2b6287da3151c5240 | [
"JavaScript"
] | 3 | JavaScript | chelsi/mutual-fund-portfolio | 4f55fdf82613c785f0117bbe2060971580c60e17 | 88bf54bfa86020439e9fde08ff69f9982ba31bcf |
refs/heads/main | <repo_name>davidev886/lossCorrection<file_sep>/utils/incoherent_channel.py
import numpy as np
import qutip as qu
from utils.p_operators import *
def inc_channel(prob, n_qubit):
Xq = X[n_qubit]
channel = (prob['1a'] * qu.spre(Id) * qu.spost(Id) +
prob['1b'] * qu.spre(Xq) * qu.spost(Xq) +
prob['1c'] * qu.spre(Xq * Xa) * qu.spost(Xq * Xa) +
prob['1d'] * qu.spre(Xa) * qu.spost(Xa)
)
return channel
if __name__ == "__main__":
print("c")
p = 1.00
qutrit_n = 6
vacuum = qu.tensor([qu.basis(3,0)] * L + [qu.basis(2,0)])
state_rho = vacuum*vacuum.dag()
for data_q in range(7):
state_rho = UnitaryQubitQutritQNDDepol(p, state_rho, data_q)
<file_sep>/old_py/start.sh
#!/bin/bash
export OMP_NUM_THREADS=1
eps=0
chi=0
#for overrot1 in 0.00 0.005773502691896258 0.00707107 0.01 0.0141421 # 0.03162277660 #0.01 # 0.01 #0.03162277660
#do
#for overrot2 in 0.00 0.034 0.017 0.0680 0.0785196 0.0961665 0.136 # 0.4300697618 #0 #0.136 0.4300697618
#do
for overrot1 in 0.010000 #$(seq -f "%1.5f" 0.000 0.00400 0.0141421)
do
for overrot2 in 0.000000 #$(seq -f "%1.5f" 0.000 0.0400 0.16) 0.136
do
folder=$(printf "case_1_analytical/chi_%.01e_eps_%1.3f_p2_%1.5f_p1_%1.5f" $chi $eps ${overrot2} ${overrot1})
echo ${overrot1}, ${overrot2}, ${folder}
mkdir -p $folder
i=0
c=0.
for state in 0
do
echo $overrot1 $overrot2 $state
python simulation_all_over_stabilizers_overrotation.py \
--logical_state ${state} \
--phi_tilde ${c} \
--epsilon_choi ${eps} \
--chi_threshold ${chi} \
--p_overrot_1 ${overrot1} \
--p_overrot_2 ${overrot2} \
--dir_name $folder \
--num_trials 0 \
--verbose
# 2>&1 >& 0_log_${c}_${eps}_${state}_${overrot2}_${overrot1}.log &
pids[${i}]=$!
i=$((i+1))
done
done #for overrot2
done
<file_sep>/old_py/monte_carlo_fp_and_stab_error.py
import qutip as qu
import numpy as np
import os
from utils.p_operators_qutrit import *
from utils.binary_conf import create_random_event
import datetime
import argparse
np.set_printoptions(precision=4, suppress=True)
# python process_matrix_simulation_all.py --phi_tilde --epsilon_choi
parser = argparse.ArgumentParser(description="Simulate qubit losses"
"with QND measurement qubit+7qutrit system")
parser.add_argument('--phi_tilde',
type=float,
default=0.05,
help="Rotation angle"
)
parser.add_argument('--epsilon_choi',
type=float,
default=0.0,
help="epsilon_choi"
)
parser.add_argument('--logical_state',
type=int,
default=0,
help="logical state corresponding"
"to: 0, 1, +, -, +i, -i"
)
parser.add_argument('--chi_threshold',
type=float,
default=0.0,
help="threshold for discarding Kraus"
"operators in the chi matrix"
)
parser.add_argument('--dir_name',
type=str,
default="./",
help="directory for saving data"
)
parser.add_argument('--p_overrot_2',
type=float,
default=0.136,
help="over rotation MS gate"
)
parser.add_argument('--p_overrot_1',
type=float,
default=0.010,
help="over rotation single-qubit gates"
)
parser.add_argument('--num_trials',
type=int,
default=4000,
help="Number of Monte Carlo samples"
)
parser.add_argument('--p_err_stab',
type=float,
default=0.05,
help="error in stab measurements"
)
args = parser.parse_args()
phi_tilde = args.phi_tilde
phi = phi_tilde * np.pi
epsilon_choi = args.epsilon_choi
jLog = args.logical_state
chi_threshold = args.chi_threshold
eta = args.p_overrot_2 * np.pi
eps = args.p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
p_err_stab = args.p_err_stab
p1MS = (args.p_overrot_2 * np.pi / 2 / 2)**2
p_err_stab = 4 * p1MS
print(p_err_stab)
choi_ideal = np.loadtxt("choi_op/choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("choi_op/qubitqutrit_choi_noloss.csv",
dtype=complex,
delimiter=','
)
if not os.path.exists(folder_name):
os.makedirs(folder_name)
choi = choi_ideal
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi, T_matrix)
final_p_loss = []
rotation_ops = Rloss_all(phi_tilde * np.pi)
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
basis_events = ([[0, _] for _ in range(4)] +
[[1, _] for _ in range(2)]
)
basic_event_str = {'0': (0, 0),
'1': (0, 1),
'2': (0, 2),
'3': (0, 3),
'4': (1, 0),
'5': (1, 1)
}
basic_event_probs = {'0': (1 - eps**2 / 2 - eta**2 / 4),
'1': eta**2 / 4,
'2': eps**2 / 4,
'3': eps**2 / 4,
'4': (1 - eps**2 / 4),
'5': eps**2 / 4
}
prob_loss = np.sin(phi / 2)**2 / 2
all_events = product(basis_events, repeat=L)
all_probabilities = []
for event in all_events:
outcomes_ancilla = [el[0] for el in event]
sub_case_ancilla = [el[1] for el in event]
p_0 = prob_loss**np.array(outcomes_ancilla)
p_1 = (1 - prob_loss)**(1 - np.array(outcomes_ancilla))
prob_loss_event = np.prod(p_0) * np.prod(p_1)
prob_inchoerent = np.prod([basic_event_probs[str(_)]
for _ in sub_case_ancilla
])
all_probabilities.append(prob_loss_event * prob_inchoerent)
sorted_index = np.argsort(all_probabilities)[::-1][:num_trials]
trial_list = []
for x in sorted_index:
str_event = np.base_repr(x, base=6).zfill(L)
trial_list.append([basic_event_str[el_event] for el_event in str_event])
now = datetime.datetime.now()
final_data_name = (now.strftime("%Y%m%d%H%M") +
f"_state_{LogicalStates_str[jLog]}_" +
f"phi_{phi_tilde:1.2f}_eps_{epsilon_choi}.dat"
)
file_data_name = os.path.join(folder_name,
final_data_name
)
print(f"logical state |{LogicalStates_str[jLog]}_L>")
index_conf = 0
cumulative_probability = 0
index_conf = 0
cumulative_probability = 0
for event in trial_list:
outcomes_ancilla = [el[0] for el in event]
sub_case_ancilla = [el[1] for el in event]
print(event)
print(outcomes_ancilla)
prob_correction_logical_state = []
psiL = LogicalStates[jLog]
null_state = False
rho_L = psiL * psiL.dag()
do_nothing = []
replace_qubits = []
false_negative = []
probs_outcome = []
probs_incoherent_process = []
for data_q in range(L):
# apply Rloss with an angle phi
rho_L = rotation_ops[data_q] * rho_L * rotation_ops[data_q].dag()
# apply the QND detection unit
rho_L = apply_qnd_process_unit(chi_matrix,
rho_L,
data_q,
chi_threshold
)
# rho_L.tidyup(atol = 1e-8)
# apply the effective incoherent noise model
if outcomes_ancilla[data_q] == 0: # ancilla in 0 state
prob_outcome = (rho_L * Pp_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected
# in the +1 eigenstate of the ancilla
null_state = True
print("check null state")
exit()
if sub_case_ancilla[data_q] == 0: # 1 - eps**2/2 - eta**2/4
rho_L = (Pp_ancilla * rho_L * Pp_ancilla.dag() /
abs(prob_outcome))
do_nothing.append(data_q)
probs_incoherent_process.append(1 - eps**2 / 2 - eta**2 / 4)
elif sub_case_ancilla[data_q] == 1: # eta**2 / 4
rho_L = (Pm_ancilla * rho_L * Pm_ancilla.dag() /
(1 - abs(prob_outcome)))
rho_L = X[data_q] * rho_L * X[data_q].dag()
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
replace_qubits.append(data_q)
probs_incoherent_process.append(eta**2 / 4)
elif sub_case_ancilla[data_q] == 2: # epsilon**2/4
rho_L = (Pm_ancilla * rho_L * Pm_ancilla.dag() /
(1 - abs(prob_outcome)))
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
replace_qubits.append(data_q)
probs_incoherent_process.append(eps**2 / 4)
elif sub_case_ancilla[data_q] == 3: # epsilon**2/4
rho_L = (Pp_ancilla * rho_L * Pp_ancilla.dag()
/ abs(prob_outcome))
rho_L = X[data_q] * rho_L * X[data_q].dag()
do_nothing.append(data_q)
probs_incoherent_process.append(eps**2 / 4)
elif outcomes_ancilla[data_q] == 1: # ancilla in 1 state
prob_outcome = (rho_L * Pm_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
null_state = True
print("check null state")
exit()
if sub_case_ancilla[data_q] == 0: # 1 - eps**2 / 4
rho_L = (Pm_ancilla * rho_L * Pm_ancilla.dag()
/ abs(prob_outcome))
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
replace_qubits.append(data_q)
probs_incoherent_process.append(1 - eps**2 / 4)
elif sub_case_ancilla[data_q] == 1: # eps**2 / 4 false negative
rho_L = (Pp_ancilla * rho_L * Pp_ancilla.dag()
/ (1-abs(prob_outcome)))
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
do_nothing.append(data_q)
probs_incoherent_process.append(eps**2 / 4)
probs_outcome.append(prob_outcome)
prob_total_event = np.prod(probs_outcome) * np.prod(probs_incoherent_process)
cumulative_probability += prob_total_event
print("probs_outcome", np.array(probs_outcome))
print("probs_incoherent_process", np.array(probs_incoherent_process))
print(index_conf, outcomes_ancilla, sub_case_ancilla,
do_nothing,
replace_qubits,
false_negative,
# np.array(probs_outcome),
# np.array(probs_incoherent_process),
# np.prod(probs_outcome),
# f"{np.prod(probs_incoherent_process):4}",
f"{np.prod(probs_outcome)*np.prod(probs_incoherent_process):.4}",
f"{cumulative_probability:.4}"
)
losses = replace_qubits
if sum(outcomes_ancilla) >= 7 or null_state or len(do_nothing) == 0:
print(prob_total_event)
correction_successful = 0.0
prob_correction_logical_state.append(correction_successful)
else:
w_0 = rho_L.ptrace(do_nothing)
rho_L = qu.tensor([qu.fock_dm(3,0)] * len(replace_qubits)
+ [qu.fock_dm(3,2)] * len(false_negative)
+ [w_0]
+ [qu.fock_dm(2,0)])
print(replace_qubits,
false_negative,
do_nothing
)
permutation_order_q = {}
# the order in the for is important because redefine the state as
# ket(0) detected_losses , ket(2) false negative, kept_qubits
for j, el in enumerate(replace_qubits + false_negative + do_nothing):
permutation_order_q[el] = j
# print("permutation_order_q", permutation_order_q)
stab_qubits_new_order = []
for stab in stab_qubits:
stab_qubits_new_order.append([permutation_order_q[q] for q in stab])
Sx = [X[j1] * X[j2] * X[j3] * X[j4] for j1,j2,j3,j4 in stab_qubits_new_order]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4] for j1,j2,j3,j4 in stab_qubits_new_order]
PPx = [[(Id + el) / 2, (Id - el) / 2] for el in Sx]
PPz = [[(Id + el) / 2, (Id - el) / 2] for el in Sz]
average_value_each_stab_meas = []
correction_each_measurement = []
index_stab_measurement = 0
cumulative_probability_stabilizers = 0.0
index_stab = 0
for meas_binary_X, meas_binary_Z in product(range(8), range(8)):
if abs(1 - cumulative_probability_stabilizers) < 1e-4:
# exit if the cumulative probability
# during the stabilizer measurement
# is already close to 1
break
state_after_measure = qu.Qobj(rho_L[:], dims = rho_L.dims)
conf_str_X = bin(meas_binary_X)[2:].zfill(3)
conf_int_X = [int(_) for _ in conf_str_X]
conf_str_Z = bin(meas_binary_Z)[2:].zfill(3)
conf_int_Z = [int(_) for _ in conf_str_Z]
probability_each_measurement = []
for stab_num, outcome_stab in enumerate(conf_int_X):
prob = (PPx[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPx[stab_num][outcome_stab] *
state_after_measure *
PPx[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
for stab_num, outcome_stab in enumerate(conf_int_Z):
prob = (PPz[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPz[stab_num][outcome_stab] *
state_after_measure *
PPz[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
# place where we can apply corrections but we don't
print(f"{index_stab_measurement: 4d}",
conf_int_X,
conf_int_Z,
f"{np.prod(probability_each_measurement):1.4f}",
f"{qu.expect(XL, state_after_measure):+1.4f}",
f"{ qu.expect(ZL, state_after_measure):+1.4f}",
f"{qu.expect(1j * XL * ZL, state_after_measure):+1.4f}"
)
prob_stabilizers = np.prod(probability_each_measurement)
cumulative_probability_stabilizers += prob_stabilizers
successful_correction_total = []
for error_in_stab_X, error_in_stab_Z in product(range(8), range(8)):
conf_str_error_X = bin(error_in_stab_X)[2:].zfill(3)
conf_int_error_X = [int(_) for _ in conf_str_error_X]
conf_str_error_Z = bin(error_in_stab_Z)[2:].zfill(3)
conf_int_error_Z = [int(_) for _ in conf_str_error_Z]
stabX_errors = np.array(conf_int_error_X)
stabZ_errors = np.array(conf_int_error_Z)
# check if a loss happens on a faulty stabilizer
# if so, the state is not correctable
# (as measuring a stabilizer on a lost qubit is impossible)
faulty_stabX_qubits = [el for j,el in enumerate(stab_qubits)
if stabX_errors[j]
]
faulty_stabZ_qubits = [el for j,el in enumerate(stab_qubits)
if stabZ_errors[j]
]
# print("stab_errors", stabX_errors, stabZ_errors)
# print(faulty_stabX_qubits, faulty_stabZ_qubits)
loss_on_faulty_stabX = any([any([(loss in stab)
for loss in losses])
for stab in faulty_stabX_qubits]
)
loss_on_faulty_stabZ = any([any([(loss in stab)
for loss in losses])
for stab in faulty_stabZ_qubits]
)
prob_stab_event_X = np.prod(p_err_stab**stabX_errors *
(1 - p_err_stab)**(1 - stabX_errors)
)
prob_stab_event_Z = np.prod(p_err_stab**stabZ_errors *
(1 - p_err_stab)**(1 - stabZ_errors)
)
prob_stab_error_event = prob_stab_event_X * prob_stab_event_Z
if loss_on_faulty_stabX or loss_on_faulty_stabZ:
# print(faulty_stabX_qubits, [([(loss in stab) for loss in losses]) for stab in faulty_stabX_qubits])
# print(faulty_stabZ_qubits, [([(loss in stab) for loss in losses]) for stab in faulty_stabZ_qubits])
correction_successful = 0.0
else:
if jLog in (0, 1):
correction_successful = (1 + abs(qu.expect(ZL, state_after_measure))) / 2
elif jLog in (2, 3):
correction_successful = (1 + abs(qu.expect(XL, state_after_measure))) / 2
elif jLog in (4, 5):
correction_successful = (1 + abs(qu.expect(1j * XL * ZL, state_after_measure))) / 2
conf_stab_errors = int("".join(str(_) for _ in conf_int_error_X + conf_int_error_Z))
conf_stab_meas = int("".join(str(_) for _ in conf_int_X + conf_int_Z))
# print("------------------>",
# f"{prob_stabilizers:1.5f}",
# f"{prob_stab_error_event:1.5f}",
# f"{correction_successful:1.5f}",
# f"{conf_stab_errors:06d}" )
average_value_each_stab_meas.append(prob_stabilizers *
prob_stab_error_event *
correction_successful
)
index_stab += 1
print("prob_of_succ_correction", np.sum(average_value_each_stab_meas))
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
conf_case_ancilla = int("".join(str(_) for _ in sub_case_ancilla))
res = ([phi_tilde,
conf_loss,
conf_case_ancilla,
np.real(np.sum(average_value_each_stab_meas)),
np.real(prob_total_event)
])
final_p_loss.append(res)
np.savetxt(file_data_name, final_p_loss, fmt='%1.3f\t' +
'%07d\t' +
'%07d\t' +
'%.10e\t' +
'%1.14f\t')
index_conf += 1
np.savetxt(file_data_name, final_p_loss, fmt='%1.3f\t' +
'%07d\t' +
'%07d\t' +
'%.10e\t' +
'%1.14f\t')
<file_sep>/utils/flip_channel.py
import qutip as qu
import numpy as np
from numpy import linalg as LA
from itertools import product
_sigmas_P = [[[1, 0], [0, 1]],
[[0, 1], [1, 0]],
[[0, -1j], [1j,0]],
[[1,0], [0,-1]]]
def bit_flip_channel(p):
X = sigmax()
I = qeye(2)
return (1-p) * sprepost(I, I) + p * sprepost(X, X)
np.set_printoptions(precision=4,suppress=True)
def choiFlip(p):
Lambda = [[1 - p, 0, 0, 1 - p], [0, p, p, 0], [0, p, p, 0], [1 - p, 0, 0, 1 - p]]
return np.array(Lambda)
def normalize_operators(matrices):
return [np.array(el) / LA.norm(el) for el in matrices]
def give_transformation_matrix():
basis_elements_list = []
for _sigma in _sigmas_P:
# we use the column vectorization. that's why we transpose the basis_operator
basis_operator = qu.Qobj(_sigma).full()
basis_element = np.transpose(basis_operator)
rows, cols = basis_element.shape
dimH = rows * cols
vector_basis = basis_element.reshape(1 , dimH)[0]
# the paper defines the change of basis matrix not in the tandard way:
# In linear algebra, the standard definition for the matrix P(e->v) for going to base e to basis v is
# P(e->v)[x]_v = [x]_e where [x]_v is a vector x written in the basis v
# and the matrix P(e->v) is given by putting by columns the components of the basis v written in the basis e
# By looking at appendix B formula 2.2 they define T(sigma -> w) as
# T(sigma -> w) |A>>_sigma = |A>>_w.
#so we need to put the compoments of the basis w written in the basis sigma by row
normalized_vector = np.conjugate(vector_basis) / LA.norm(vector_basis)
basis_elements_list.append(normalized_vector.tolist())
T_matrix = np.array(basis_elements_list)
return T_matrix
def orthonormal_basis_operator(T_matrix):
on_basis = []
for el in T_matrix:
dimH = int(np.sqrt(len(el)))
# we need to transpose as we were working with col-vec convention
on_basis.append(el.reshape((dimH, dimH)).T)
return on_basis
def get_chi_from_choi(choi, T_matrix):
return np.dot(T_matrix, np.dot(choi, T_matrix.conj().T))
def apply_qnd_process_unit(choi, state_total):
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi, T_matrix)
on_basis_Pauli = normalize_operators(_sigmas_P)
rows, cols = chi_matrix.shape
final_state_list = []
for alpha, beta in product(range(rows), range(cols)):
OP_1 = qu.Qobj(on_basis_Pauli[alpha])
OP_2 = qu.Qobj(on_basis_Pauli[beta]).dag()
final_state_list.append(chi_matrix[alpha, beta] * OP_1 * state_total * OP_2)
final_state = sum(final_state_list)
return final_state
state_t = qu.basis(2,0) * qu.basis(2,0).dag()
choi = choiFlip(0.3)
final_state = apply_qnd_process_unit(choi, state_t)
print(final_state)
#function of qutip
print(to_choi(bit_flip_channel(0.3)))
chi_matrix = to_chi(to_choi(bit_flip_channel(0.3)))
print(chi_matrix.shape)
<file_sep>/utils/depol.py
from qutip import *
import numpy as np
import scipy.linalg
from itertools import product
import matplotlib.pyplot as plt
x = sigmax()
y = sigmay()
z = sigmaz()
p = 1
Eps1 = ((1-3*p/4) * spre(qeye(2)) * spost(qeye(2).dag()) +
0.25 * p* (spre(x) * spost(x.dag()) + spre(y) * spost(y.dag()) + spre(z) * spost(z.dag())) )
Eps2 = Qobj(np.eye(4)/2, dims = Eps1.dims, type = Eps1.type)
state_s = (basis(2,0)+0.45 * basis(2,1)).unit()
print(Eps1)
print(Eps2)
print("to choi")
print(to_choi(Eps1))
print(Eps1(state_s))
choi = Qobj(np.eye(4)/2, dims = Eps1.dims, type = Eps1.type)
print("this", choi_to_super(choi))
<file_sep>/old_py/incoherent_all.py
#
# Case 2: incoherent model for the overrotations
#
import qutip as qu
import numpy as np
from itertools import product
import os
from utils.p_operators_qutrit import *
# from utils.p_operators import *
from utils.binary_conf import get_binary_confs
from utils.incoherent_channel_qutrit import (channel_E_0,
channel_E_1,
new_channel)
from utils.parameters import parse_command_line
import datetime
np.set_printoptions(precision=4, suppress=True)
args = parse_command_line()
phi_tilde = args.phi_tilde
print(phi_tilde)
phi = phi_tilde * np.pi
epsilon_choi = args.epsilon_choi
jLog = args.logical_state
chi_threshold = args.chi_threshold
eta = args.p_overrot_2 * np.pi
eps = args.p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
VERBOSE = args.verbose
choi_ideal = np.loadtxt("choi_op/choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("choi_op/qubitqutrit_choi_noloss.csv",
dtype=complex,
delimiter=','
)
if not os.path.exists(folder_name):
os.makedirs(folder_name)
choi = choi_ideal
# T_matrix = give_transformation_matrix()
# chi_matrix = get_chi_from_choi(choi, T_matrix)
final_p_loss = []
# rotation_ops = Rloss_all(phi_tilde * np.pi)
choi = np.real((1 - epsilon_choi) * choi_ideal +
6 * epsilon_choi * choi_experiment
)
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi, T_matrix)
chi_matrix[np.abs(chi_matrix) < chi_threshold] = 0
final_p_loss = []
rotation_ops = Rloss_all(phi_tilde * np.pi)
result_correction = []
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
now = datetime.datetime.now()
final_data_name = (now.strftime("%Y%m%d%H%M") +
f"_state_{LogicalStates_str[jLog]}_" +
f"phi_{phi_tilde:1.5f}_eps_{epsilon_choi}.dat"
)
channel_probs = {'1a': (3 + np.cos(2*eps) + 4*np.cos(eps)*np.cos(eta))/8., # 1(a)
'1b': np.sin(eps)**2/4., # 1(b)
'1c': (3 + np.cos(2*eps) - 4*np.cos(eps)*np.cos(eta))/8., # 1(c)
'1d': np.sin(eps)**2/4., # 1(d)
'2a': np.cos(eps/2.)**2, # 2(a)
'2b': np.sin(eps/2.)**2, # 2(b)
}
prob_loss = np.sin(phi / 2)**2 / 2
all_ancilla_outcomes = get_binary_confs(L)
all_channel_events = get_binary_confs(L)
all_stabilizer_outcomes = list(product(get_binary_confs(3), get_binary_confs(3)))
file_data_name = os.path.join(folder_name,
final_data_name
)
print(f"logical state |{LogicalStates_str[jLog]}_L>")
print(channel_probs)
index_conf = 0
cumulative_probability = 0
if phi_tilde == 0:
all_channel_events = [[0, 0, 0, 0, 0, 0, 0]]
all_channel_events = [[0, 0, 0, 0, 0, 0, 0]]
for channel_event, outcomes_ancilla in product(all_channel_events, all_ancilla_outcomes):
print(channel_event, outcomes_ancilla)
psiL = LogicalStates[jLog]
null_state = False
rho_L = psiL * psiL.dag()
do_nothing = []
replace_qubits = []
probs_outcome = []
probs_incoherent_process = []
for data_q in range(L):
# apply Rloss with an angle phi
rho_L = rotation_ops[data_q] * rho_L * rotation_ops[data_q].dag()
# applying the QND detection unit
rho_L = apply_qnd_process_unit(chi_matrix,
rho_L,
data_q,
chi_threshold
)
# rho_L.tidyup(atol = 1e-8)
# applying the incoherent channel
prob_outcome_ch_ev = 1.0
probs_incoherent_process.append(1.0)
rho_L = new_channel(rho_L, channel_probs, data_q)
# measuring the ancilla
if outcomes_ancilla[data_q] == 0: # ancilla in 0 state
prob_outcome = (rho_L * Pp_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: in prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected
# in the +1 eigenstate of the ancilla
null_state = True
print("check null state outcome 0", prob_outcome)
probs_outcome.append(prob_outcome)
break # exit()
probs_outcome.append(prob_outcome)
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / prob_outcome
do_nothing.append(data_q)
elif outcomes_ancilla[data_q] == 1: # ancilla in 1 state
prob_outcome = (rho_L * Pm_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: in prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected
# in the +1 eigenstate of the ancilla
null_state = True
print("check null state outcome 1", prob_outcome)
probs_outcome.append(prob_outcome)
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
break # exit()
probs_outcome.append(prob_outcome)
rho_L = Pm_ancilla * rho_L * Pm_ancilla.dag() / prob_outcome
replace_qubits.append(data_q)
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
print(f"{data_q}, {prob_outcome_ch_ev:1.4f}, {prob_outcome:1.4f}")
# renormalize if the trace of rho_L is bigger than 1
# because of accumulated errors
traccia = rho_L.tr()
if traccia > 1:
rho_L = rho_L / traccia
p_tot_ancilla = np.real(np.prod(probs_outcome))
p_tot_channel = np.real(np.prod(probs_incoherent_process))
cumulative_probability += p_tot_ancilla * p_tot_channel
print(index_conf, "---->cumulative", f"{1-cumulative_probability:.5e}")
print(index_conf, "---->tr(rho)", f"{rho_L.tr():.6f}")
conf_channel = int("".join(str(_) for _ in channel_event))
conf_ancilla = int("".join(str(_) for _ in outcomes_ancilla))
if sum(outcomes_ancilla) >= 7 or null_state or len(do_nothing) == 0:
p_log_success = 0.0
res = ([phi_tilde,
conf_channel,
conf_ancilla,
p_tot_channel,
p_tot_ancilla,
p_log_success
])
print(index_conf,
channel_event,
outcomes_ancilla,
"null_state"
)
else:
print(index_conf,
channel_event,
outcomes_ancilla,
do_nothing,
replace_qubits,
f"{p_tot_channel:.4}",
f"{p_tot_ancilla:.4}",
f"{1-cumulative_probability:.4e}"
)
w_0 = rho_L.ptrace(do_nothing)
rho_L = qu.tensor([qu.fock_dm(dimQ, 0)] * len(replace_qubits)
+ [w_0]
+ [qu.fock_dm(dimA, 0)])
permutation_order_q = {}
# the order in the for is important because redefine the state as
# ket(0) detected_losses , ket(2), kept_qubits
for j, el in enumerate(replace_qubits + do_nothing):
permutation_order_q[el] = j
# print("permutation_order_q", permutation_order_q)
stab_qubits_new_order = []
for stab in stab_qubits:
stab_qubits_new_order.append([permutation_order_q[q] for q in stab])
Sx = [X[j1] * X[j2] * X[j3] * X[j4] for j1, j2, j3, j4 in stab_qubits_new_order]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4] for j1, j2, j3, j4 in stab_qubits_new_order]
PPx = [[(Id + el) / 2, (Id - el) / 2] for el in Sx]
PPz = [[(Id + el) / 2, (Id - el) / 2] for el in Sz]
average_value_each_stab_meas = []
correction_each_measurement = []
index_stab_measurement = 0
cumulative_probability_stabilizers = 0.0
for configuration_int_X, configuration_int_Z in all_stabilizer_outcomes:
# if abs(1 - cumulative_probability_stabilizers) < 1e-4:
# exit if the cumulative probability
# during the stabilizer measurement
# is already close to 1
# break
state_after_measure = qu.Qobj(rho_L[:], dims=rho_L.dims)
probability_each_measurement = []
for stab_num, outcome_stab in enumerate(configuration_int_X):
prob = (PPx[stab_num][outcome_stab] *
state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPx[stab_num][outcome_stab] *
state_after_measure *
PPx[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
for stab_num, outcome_stab in enumerate(configuration_int_Z):
prob = (PPz[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPz[stab_num][outcome_stab] *
state_after_measure *
PPz[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
# place where we can apply corrections but we don't
prob_stabilizers = np.prod(probability_each_measurement)
cumulative_probability_stabilizers += prob_stabilizers
if jLog in (0, 1):
correction_successful = (1 + abs(qu.expect(ZL, state_after_measure))) / 2
elif jLog in (2, 3):
correction_successful = (1 + abs(qu.expect(XL, state_after_measure))) / 2
elif jLog in (4, 5):
correction_successful = (1 + abs(qu.expect(1j * XL * ZL, state_after_measure))) / 2
if VERBOSE:
print(f"{index_stab_measurement: 4d}",
configuration_int_X,
configuration_int_Z,
f"{np.prod(probability_each_measurement):1.3f}",
f"{qu.expect(XL, state_after_measure):+1.3f}",
f"{qu.expect(ZL, state_after_measure):+1.3f}",
f"{qu.expect(1j * XL * ZL, state_after_measure):+1.3f}",
f"{cumulative_probability_stabilizers:.5f}",
f"{1-cumulative_probability_stabilizers:.4e}",
f"{1-correction_successful:.4e}",
)
average_value_each_stab_meas.append(prob_stabilizers *
correction_successful
)
# conf_stab_meas = int("".join(str(_) for _ in configuration_int_X + configuration_int_Z))
index_stab_measurement += 1
p_log_success = np.sum(average_value_each_stab_meas)
print("cumulative_probability_stabilizers: ",
f"{cumulative_probability_stabilizers:.4f}")
print("1-cumulative_probability_stabilizers: ",
f"{1-cumulative_probability_stabilizers:.4e}")
print(f"prob_of_succ_correction {p_log_success:1.5f}")
res = ([phi_tilde,
conf_channel,
conf_ancilla,
p_tot_channel,
p_tot_ancilla,
p_log_success
])
index_conf += 1
final_p_loss.append(res)
np.savetxt(file_data_name, final_p_loss, fmt='%1.5f\t' +
'%07d\t' +
'%07d\t' +
'%.18e\t' +
'%.18e\t' +
'%.18e\t')
# A = np.array(final_p_loss)
# prob_success = A[:, 2]
# prob_event = A[:, 3]
# print("sum(prob_event)", sum(prob_event))
# p_success = np.sum(prob_success * prob_event)
# print("p_success ", f"{p_success:.4f}")
# print("log_err_rate", f"{1-p_success:.4e}")
#
<file_sep>/old_py/QND_unitary_trace_qubit.py
#
# Case 2: incoherent model for the overrotations
# with no loss rotations
# run on the first most probable events
#
import qutip as qu
import numpy as np
from itertools import product
import os
from utils.p_operators_qutrit import *
# from utils.p_operators import *
from utils.binary_conf import create_random_event
from utils.parameters import parse_command_line
from utils.incoherent_channel_qutrit import inc_channel
import datetime
import glob
np.set_printoptions(precision=4, suppress=True)
args = parse_command_line()
phi_tilde = args.phi_tilde
print(phi_tilde)
phi = phi_tilde * np.pi
epsilon_choi = args.epsilon_choi
jLog = args.logical_state
chi_threshold = args.chi_threshold
eta = args.p_overrot_2 * np.pi
eps = args.p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
VERBOSE = args.verbose
choi_ideal = np.loadtxt("choi_op/choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("choi_op/qubitqutrit_choi_noloss.csv",
dtype=complex,
delimiter=','
)
if not os.path.exists(folder_name):
os.makedirs(folder_name)
choi = choi_ideal
# T_matrix = give_transformation_matrix()
# chi_matrix = get_chi_from_choi(choi, T_matrix)
final_p_loss = []
# rotation_ops = Rloss_all(phi_tilde * np.pi)
choi = np.real((1 - epsilon_choi) * choi_ideal +
6 * epsilon_choi * choi_experiment
)
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi, T_matrix)
chi_matrix[np.abs(chi_matrix) < chi_threshold] = 0
final_p_loss = []
rotation_ops = Rloss_all(phi_tilde * np.pi)
result_correction = []
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
now = datetime.datetime.now()
final_data_name = (now.strftime("%Y%m%d%H%M") +
f"_state_{LogicalStates_str[jLog]}_" +
f"phi_{phi_tilde:1.5f}_eps_{epsilon_choi}.dat"
)
basic_event_probs = {'1a': (3 + np.cos(2*eps) + 4*np.cos(eps)*np.cos(eta))/8., # 1(a)
'1b': np.sin(eps)**2/4., # 1(b)
'1c': (3 + np.cos(2*eps) - 4*np.cos(eps)*np.cos(eta))/8., # 1(c)
'1d': np.sin(eps)**2/4., # 1(d)
'2a': np.cos(eps/2.)**2, # 2(a)
'2b': np.sin(eps/2.)**2, # 2(b)
}
# try with these probability inverted as from Mathematica notebook
# original definition
# If the ancilla is found in 1 (loss detected) we
# (a) leave the qutrit state (ρ = |2⟩ ⟨2|) as it is with probability np.cos(eps/2.)**2
# (b) flip the ancilla to the no-loss detection state with probability np.sin(eps/2.)**2 (false negative).
# '2a': np.cos(eps/2.)**2, # 2(a)
# '2b': np.sin(eps/2.)**2, # 2(b)
prob_loss = np.sin(phi / 2)**2 / 2
all_events = product([0, 1], repeat=L)
file_data_name = os.path.join(folder_name,
final_data_name
)
# get the incoherent channels once
channels_0 = []
channels_1 = []
# for data_q in range(L):
# print(data_q)
# ch_0, ch_1 = inc_channel(basic_event_probs,
# data_q,
# noloss=False
# )
# channels_0.append(ch_0)
# channels_1.append(ch_1)
print(f"logical state |{LogicalStates_str[jLog]}_L>")
print(basic_event_probs)
index_conf = 0
cumulative_probability = 0
for outcomes_ancilla in all_events:
psiL = LogicalStates[jLog]
null_state = False
rho_L = psiL * psiL.dag()
do_nothing = []
replace_qubits = []
probs_outcome = []
probs_incoherent_process = []
print(outcomes_ancilla)
ancilla_after_channel = []
for data_q in range(L):
# print(data_q)
# apply Rloss with an angle phi
rho_L = rotation_ops[data_q] * rho_L * rotation_ops[data_q].dag()
# apply the QND detection unit
rho_L = apply_qnd_process_unit(chi_matrix,
rho_L,
data_q,
chi_threshold
)
# rho_L.tidyup(atol = 1e-8)
# apply the effective incoherent noise model
Xq = X[data_q]
# rho_Lp = rho_L #Pp_ancilla * rho_L * Pp_ancilla.dag()
# rho_Lm = rho_L #Pm_ancilla * rho_L * Pm_ancilla.dag()
# channel_0 = (basic_event_probs['1a'] * Id * rho_Lp * Id +
# basic_event_probs['1b'] * Xq * rho_Lp * Xq +
# basic_event_probs['1c'] * Xq * Xa * rho_Lp * Xq * Xa +
# basic_event_probs['1d'] * Xa * rho_Lp * Xa
# )
#
# channel_1 = (basic_event_probs['2a'] * Id * rho_Lm * Id +
# basic_event_probs['2b'] * Xa * rho_Lm * Xa
# )
# print("prob 0 on channel 0", data_q, (channel_0 * Pp_ancilla).tr())
# print("prob 1 on channel 1", data_q, (channel_1 * Pp_ancilla).tr())
if outcomes_ancilla[data_q] == 0: # ancilla in 0 state before the channel
prob_outcome = (rho_L * Pp_ancilla).tr()
probs_outcome.append(prob_outcome)
if abs(prob_outcome.imag) > 1e-5:
print("warning: in prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected
# in the +1 eigenstate of the ancilla
null_state = True
print("check null state")
ancilla_after_channel = [2] * L
break # exit()
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / prob_outcome
print("prob_outcome 0" , prob_outcome)
# rho_Lp = Pp_ancilla * rho_L * Pp_ancilla.dag()
rho_L = (basic_event_probs['1a'] * Id * rho_L * Id +
basic_event_probs['1b'] * Xq * rho_L * Xq +
basic_event_probs['1c'] * Xq * Xa * rho_L * Xq * Xa +
basic_event_probs['1d'] * Xa * rho_L * Xa
)
print("prob 0 on channel 0 rho", data_q, (rho_L * Pp_ancilla).tr())
print("prob 1 on channel 0 rho", data_q, (rho_L * Pm_ancilla).tr())
prob_coin_toss = 1 - (rho_L * Pp_ancilla).tr()
if prob_coin_toss > 1:
prob_coin_toss = 1
if prob_coin_toss < 0:
prob_coin_toss = 0
ancilla_final = np.random.binomial(1, prob_coin_toss)
ancilla_after_channel.append(ancilla_final)
# if ancilla_final == 0:
# do_nothing.append(data_q)
# elif ancilla_final == 1:
# replace_qubits.append(data_q)
elif outcomes_ancilla[data_q] == 1: # ancilla in 1 state
prob_outcome = (rho_L * Pm_ancilla).tr()
# rho_Lm = Pm_ancilla * rho_L * Pm_ancilla.dag()
probs_outcome.append(prob_outcome)
if abs(prob_outcome.imag) > 1e-5:
print("warning: in prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected
# in the +1 eigenstate of the ancilla
null_state = True
print("check null state outcome 1", prob_outcome)
ancilla_after_channel = [2] * L
break # exit()
rho_L = Pm_ancilla * rho_L * Pm_ancilla.dag() / prob_outcome
print("prob_outcome 1" , prob_outcome)
replace_qubits.append(data_q)
rho_L = (basic_event_probs['2a'] * Id * rho_L * Id +
basic_event_probs['2b'] * Xa * rho_L * Xa
)
print("prob 0 on channel 1 rho", data_q, (rho_L * Pp_ancilla).tr())
print("prob 1 on channel 1 rho", data_q, (rho_L * Pm_ancilla).tr())
prob_coin_toss = 1 - (rho_L * Pp_ancilla).tr()
if prob_coin_toss > 1:
prob_coin_toss = 1
if prob_coin_toss < 0:
prob_coin_toss = 0
ancilla_final = np.random.binomial(1, prob_coin_toss)
ancilla_after_channel.append(ancilla_final)
# if ancilla_final == 0:
# do_nothing.append(data_q)
# elif ancilla_final == 1:
# replace_qubits.append(data_q)
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
# renormalize if the trace of rho_L is bigger than 1
# because of accumulated errorr
traccia = rho_L.tr()
if traccia > 1:
rho_L = rho_L / traccia
print("ancilla_final", ancilla_after_channel)
ancilla_after_channel_arr = np.array(ancilla_after_channel)
replace_qubits = np.where(ancilla_after_channel_arr == 1)[0].tolist()
do_nothing = np.where(ancilla_after_channel_arr == 0)[0].tolist()
print("replace_qubits", replace_qubits)
print("do_nothing", do_nothing)
prob_total_event = np.prod(probs_outcome)
cumulative_probability += prob_total_event
print("probs_outcome", np.array(probs_outcome))
if sum(outcomes_ancilla) >= 7 or null_state or len(do_nothing) == 0:
correction_successful = 0.0
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
conf_ancilla = int("".join(str(_) for _ in ancilla_after_channel))
res = ([phi_tilde,
conf_loss,
correction_successful,
np.real(prob_total_event),
conf_ancilla
])
print(index_conf, outcomes_ancilla,
"null_state"
)
else:
print(index_conf, outcomes_ancilla,
do_nothing,
replace_qubits,
f"{prob_total_event:.4}",
f"{1-cumulative_probability:.4e}"
)
w_0 = rho_L.ptrace(do_nothing)
rho_L = qu.tensor([qu.fock_dm(dimQ, 0)] * len(replace_qubits)
+ [w_0]
+ [qu.fock_dm(dimA, 0)])
print(replace_qubits,
do_nothing
)
permutation_order_q = {}
# the order in the for is important because redefine the state as
# ket(0) detected_losses , ket(2), kept_qubits
for j, el in enumerate(replace_qubits + do_nothing):
permutation_order_q[el] = j
# print("permutation_order_q", permutation_order_q)
stab_qubits_new_order = []
for stab in stab_qubits:
stab_qubits_new_order.append([permutation_order_q[q] for q in stab])
Sx = [X[j1] * X[j2] * X[j3] * X[j4] for j1, j2, j3, j4 in stab_qubits_new_order]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4] for j1, j2, j3, j4 in stab_qubits_new_order]
PPx = [[(Id + el) / 2, (Id - el) / 2] for el in Sx]
PPz = [[(Id + el) / 2, (Id - el) / 2] for el in Sz]
average_value_each_stab_meas = []
correction_each_measurement = []
index_stab_measurement = 0
cumulative_probability_stabilizers = 0.0
for meas_binary_X, meas_binary_Z in product(range(8), range(8)):
# if abs(1 - cumulative_probability_stabilizers) < 1e-4:
# exit if the cumulative probability
# during the stabilizer measurement
# is already close to 1
# break
state_after_measure = qu.Qobj(rho_L[:], dims=rho_L.dims)
configuration_str_X = bin(meas_binary_X)[2:].zfill(3)
configuration_int_X = [int(_) for _ in configuration_str_X]
configuration_str_Z = bin(meas_binary_Z)[2:].zfill(3)
configuration_int_Z = [int(_) for _ in configuration_str_Z]
probability_each_measurement = []
for stab_num, outcome_stab in enumerate(configuration_int_X):
prob = (PPx[stab_num][outcome_stab] *
state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPx[stab_num][outcome_stab] *
state_after_measure *
PPx[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
for stab_num, outcome_stab in enumerate(configuration_int_Z):
prob = (PPz[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPz[stab_num][outcome_stab] *
state_after_measure *
PPz[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
# place where we can apply corrections but we don't
if VERBOSE:
print(f"{index_stab_measurement: 4d}",
configuration_int_X,
configuration_int_Z,
f"{np.prod(probability_each_measurement):1.4f}",
f"{qu.expect(XL, state_after_measure):+1.4f}",
f"{qu.expect(ZL, state_after_measure):+1.4f}",
f"{qu.expect(1j * XL * ZL, state_after_measure):+1.4f}"
)
prob_stabilizers = np.prod(probability_each_measurement)
cumulative_probability_stabilizers += prob_stabilizers
if jLog in (0, 1):
correction_successful = (1 + abs(qu.expect(ZL, state_after_measure))) / 2
elif jLog in (2, 3):
correction_successful = (1 + abs(qu.expect(XL, state_after_measure))) / 2
elif jLog in (4, 5):
correction_successful = (1 + abs(qu.expect(1j * XL * ZL, state_after_measure))) / 2
average_value_each_stab_meas.append(prob_stabilizers *
correction_successful
)
# conf_stab_meas = int("".join(str(_) for _ in configuration_int_X + configuration_int_Z))
index_stab_measurement += 1
print("cumulative_probability_stabilizers: ",
f"{cumulative_probability_stabilizers:.4f}")
print("1-cumulative_probability_stabilizers: ",
f"{1-cumulative_probability_stabilizers:.4e}")
print("prob_of_succ_correction", np.sum(average_value_each_stab_meas))
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
conf_ancilla = int("".join(str(_) for _ in ancilla_after_channel))
res = ([phi_tilde,
conf_loss,
np.real(np.sum(average_value_each_stab_meas)),
np.real(prob_total_event),
conf_ancilla
])
index_conf += 1
final_p_loss.append(res)
np.savetxt(file_data_name, final_p_loss, fmt='%1.5f\t' +
'%07d\t' +
'%.18e\t' +
'%.18e\t' +
'%07d\t')
# A = np.array(final_p_loss)
# prob_success = A[:, 2]
# prob_event = A[:, 3]
# print("sum(prob_event)", sum(prob_event))
# p_success = np.sum(prob_success * prob_event)
# print("p_success ", f"{p_success:.4f}")
# print("log_err_rate", f"{1-p_success:.4e}")
#
<file_sep>/utils/incoherent_channel_qutrit.py
import numpy as np
import qutip as qu
from utils.p_operators_qutrit import *
def channel_E_0(rho_L, prob, n_qubit):
Xq = X[n_qubit]
rhof = (prob['1a'] * Id * rho_L * Id +
prob['1b'] * Xq * rho_L * Xq +
prob['1c'] * Xq * Xa * rho_L * Xq * Xa +
prob['1d'] * Xa * rho_L * Xa
)
return rhof
def channel_E_1(rho_L, prob, n_qubit):
Xq = X[n_qubit]
rhof = (prob['2a'] * Id * rho_L * Id +
prob['2b'] * Xa * rho_L * Xa
)
return rhof
def new_channel(rho_L, prob, n_qubit):
dimHa = 2
dimHq = 3
proj_2 = qu.tensor([qu.qeye(dimHq)] * n_qubit
+ [proj(2, 2, dimH = 3)]
+ [qu.qeye(dimHq)] * (L - n_qubit - 1)
+ [qu.qeye(dimHa)])
P01 = qu.tensor([qu.qeye(dimHq)] * n_qubit
+ [qu.qeye(dimHq) - proj(2, 2, dimH = 3)]
+ [qu.qeye(dimHq)] * (L - n_qubit - 1)
+ [qu.qeye(dimHa)])
Xq = X[n_qubit]
# print(proj_2)
# print()
# print(rho_L)
rhof = (prob['1a'] * Id * P01 * rho_L * P01.dag() * Id +
prob['1b'] * Xq * P01 * rho_L * P01.dag() * Xq +
prob['1c'] * Xq * Xa * P01 * rho_L * P01.dag() * Xq * Xa +
prob['1d'] * Xa * P01 * rho_L * P01.dag() * Xa +
prob['2a'] * Xa * proj_2 * rho_L * proj_2 * Xa +
prob['2b'] * Xa * proj_2 * rho_L * proj_2 * Xa
)
return rhof
def new_channel_only_qutrit(rho_L, prob, n_qubit):
dimHa = 2
dimHq = 3
proj_2 = qu.tensor([qu.qeye(dimHq)] * n_qubit
+ [proj(2, 2, dimH = 3)]
+ [qu.qeye(dimHq)] * (L - n_qubit - 1)
+ [qu.qeye(dimHa)])
P01 = qu.tensor([qu.qeye(dimHq)] * n_qubit
+ [qu.qeye(dimHq) - proj(2, 2, dimH = 3)]
+ [qu.qeye(dimHq)] * (L - n_qubit - 1)
+ [qu.qeye(dimHa)])
Xq = X[n_qubit]
# print(proj_2)
# print()
# print(rho_L)
rhof = (prob['1a'] * Id * P01 * rho_L * P01.dag() * Id +
prob['1b'] * Xq * P01 * rho_L * P01.dag() * Xq +
prob['1c'] * Xq * P01 * rho_L * P01.dag() * Xq +
prob['1d'] * P01 * rho_L * P01.dag() +
prob['2a'] * Xa * proj_2 * rho_L * proj_2 * Xa +
prob['2b'] * Xa * proj_2 * rho_L * proj_2 * Xa
)
return rhof
<file_sep>/start_coherent_model.sh
#!/bin/bash
export OMP_NUM_THREADS=1
eps=0
chi=0
for overrot1 in $(seq -f "%1.5f" 0.000 0.00100 0.0141421)
do
for overrot2 in $(seq -f "%1.5f" 0.000 0.0100 0.16) 0.136
do
folder=$(printf "case_1_zero_loss_final/chi_%.01e_eps_%1.3f_p2_%1.5f_p1_%1.5f" $chi $eps ${overrot2} ${overrot1})
echo ${overrot1}, ${overrot2}, ${folder}
mkdir -p $folder
i=0
c=0.00
for state in 4 2 0
do
echo $overrot1 $overrot2 $state
python simulation_all_over_stabilizers_overrotation.py \
--logical_state ${state} \
--phi_tilde ${c} \
--epsilon_choi ${eps} \
--chi_threshold ${chi} \
--p_overrot_1 ${overrot1} \
--p_overrot_2 ${overrot2} \
--dir_name $folder \
--num_trials 0 \
2>&1 >& 0_log_${c}_${eps}_${state}_${overrot2}_${overrot1}.log &
pids[${i}]=$!
i=$((i+1))
done
done #for overrot2
for pid in ${pids[*]}; do
wait $pid
done
done
<file_sep>/old_py/simulation_all_over_stabilizers_overrotation.py
#
# Case 1: Coherent errors (single and two qubit overrotation)
# with no stabilizers measurement errors
#
import numpy as np
import qutip as qu
import os
from itertools import product
from utils.binary_conf import binary_configurations
from utils.p_operators_qutrit import *
from utils.overrotation_channel import (CorrelatedOverRotQubitAll,
SingleOverRotQubitAll
)
import datetime
from utils.parameters import parse_command_line
import argparse
np.set_printoptions(precision=4, suppress=True)
np.set_printoptions(precision=4, suppress=True)
args = parse_command_line()
phi_tilde = args.phi_tilde
print(phi_tilde)
phi = phi_tilde * np.pi
epsilon_choi = args.epsilon_choi
jLog = args.logical_state
chi_threshold = args.chi_threshold
eta = args.p_overrot_2 * np.pi
eps = args.p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
VERBOSE = args.verbose
p_overrot_2 = args.p_overrot_2
p_overrot_1 = args.p_overrot_1
eta = p_overrot_2 * np.pi
eps = p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
choi_ideal = np.loadtxt("choi_op/choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("choi_op/qubitqutrit_choi_noloss.csv",
dtype=complex,
delimiter=',')
if not os.path.exists(folder_name):
os.makedirs(folder_name)
choi = np.real((1 - epsilon_choi) * choi_ideal +
6 * epsilon_choi * choi_experiment
)
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi, T_matrix)
chi_matrix[np.abs(chi_matrix) < chi_threshold] = 0
final_p_loss = []
rotation_ops = Rloss_all(phi_tilde * np.pi)
result_correction = []
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
OverRotationOperators = CorrelatedOverRotQubitAll(p_overrot_2 * np.pi)
SingleOverRotations = SingleOverRotQubitAll(p_overrot_1 * np.pi)
#SingleOverRotations = SingleOverRotQutritAll(p_overrot_1 * np.pi)
now = datetime.datetime.now()
final_data_name = (now.strftime("%Y%m%d%H%M") +
f"_state_{LogicalStates_str[jLog]}_" +
f"phi_{phi_tilde:1.5f}_eps_{epsilon_choi}.dat"
)
file_data_name = os.path.join(folder_name,
final_data_name
)
print(f"logical state |{LogicalStates_str[jLog]}_L>")
index_confs = 0
final_prob = []
result_correction = []
num_losses = []
all_loss_events = binary_configurations().configurations_list
for outcomes_ancilla in all_loss_events:
index_confs += 1
prob_total_event = []
prob_correction_logical_state = []
psiL = LogicalStates[jLog]
list_qubits = list(range(L))
null_state = False
rho_L = psiL * psiL.dag()
for data_q in list_qubits:
# apply Rloss with an angle phi
rho_L = rotation_ops[data_q] * rho_L * rotation_ops[data_q].dag()
# apply the QND detection unit
rho_L = apply_qnd_process_unit(chi_matrix,
rho_L,
data_q,
chi_threshold
)
# apply the overrotations
if p_overrot_2 or p_overrot_1:
rho_L = (OverRotationOperators[data_q] *
rho_L *
OverRotationOperators[data_q].dag()
)
rho_L = (SingleOverRotations[data_q] *
rho_L *
SingleOverRotations[data_q].dag()
)
if outcomes_ancilla[data_q] == 0:
prob_outcome = (rho_L * Pp_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected in the
# +1 eigenstate of the ancilla
null_state = True
print("check null state outcome 0", prob_outcome)
prob_total_event.append(prob_outcome)
break
else:
prob_total_event.append(prob_outcome)
rho_L = (Pp_ancilla *
rho_L *
Pp_ancilla.dag() / prob_outcome
)
elif outcomes_ancilla[data_q] == 1:
prob_outcome = (rho_L * Pm_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
null_state = True
print("check null state outcome 1", prob_outcome)
prob_total_event.append(prob_outcome)
break
else:
prob_total_event.append(prob_outcome)
rho_L = (Pm_ancilla *
rho_L *
Pm_ancilla.dag() / prob_outcome
)
# reset ancilla
rho_L = Xa * rho_L * Xa.dag()
print(data_q,
outcomes_ancilla[data_q],
prob_outcome)
prob_loss_event = np.abs(np.prod(prob_total_event))
losses = np.where(outcomes_ancilla)[0].tolist()
kept_qubits = list(set(range(L)) - set(losses))
if sum(outcomes_ancilla) >= 7 or null_state:
print(prob_loss_event)
correction_successful = 0.0
prob_correction_logical_state.append(correction_successful)
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
final_p_loss.append([phi_tilde,
conf_loss,
correction_successful,
prob_loss_event
])
else:
w_0 = rho_L.ptrace(kept_qubits)
rho_L = (qu.tensor([qu.fock_dm(3, 0)] * len(losses) +
[w_0] +
[qu.fock_dm(2, 0)])
)
permutation_order_q = {}
for j, el in enumerate(losses + kept_qubits):
permutation_order_q[el] = j
# print("permutation_order_q", permutation_order_q)
stab_qubits_new_order = []
for stab in stab_qubits:
stab_qubits_new_order.append([permutation_order_q[q]
for q in stab]
)
Sx = [X[j1] * X[j2] * X[j3] * X[j4]
for j1, j2, j3, j4 in stab_qubits_new_order
]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4]
for j1, j2, j3, j4 in stab_qubits_new_order
]
PPx = [[(Id + el) / 2, (Id - el) / 2] for el in Sx]
PPz = [[(Id + el) / 2, (Id - el) / 2] for el in Sz]
index_stab_measurement = 0
cumulative_probability_stabilizers = 0.0
for meas_binary_X, meas_binary_Z in product(range(8), range(8)):
# if abs(1 - cumulative_probability_stabilizers) < 1e-4:
# exit if the cumulative probability
# during the stabilizer measurement
# is already close to 1
# break
state_after_measure = qu.Qobj(rho_L[:], dims=rho_L.dims)
conf_str_X = bin(meas_binary_X)[2:].zfill(3)
conf_int_X = [int(_) for _ in conf_str_X]
conf_str_Z = bin(meas_binary_Z)[2:].zfill(3)
conf_int_Z = [int(_) for _ in conf_str_Z]
probability_each_measurement = []
for stab_num, outcome_stab in enumerate(conf_int_X):
prob = (PPx[stab_num][outcome_stab] *
state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPx[stab_num][outcome_stab] *
state_after_measure *
PPx[stab_num][outcome_stab].dag() /
prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
for stab_num, outcome_stab in enumerate(conf_int_Z):
prob = (PPz[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPz[stab_num][outcome_stab] *
state_after_measure *
PPz[stab_num][outcome_stab].dag() /
prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
prob_stabilizers = np.prod(probability_each_measurement)
cumulative_probability_stabilizers += prob_stabilizers
exp_x = np.real(qu.expect(XL, state_after_measure))
exp_z = np.real(qu.expect(ZL, state_after_measure))
exp_y = np.real(qu.expect(1j * XL * ZL, state_after_measure))
if jLog in (0, 1):
correction_successful = (1 + abs(exp_z)) / 2
elif jLog in (2, 3):
correction_successful = (1 + abs(exp_x)) / 2
elif jLog in (4, 5):
correction_successful = (1 + abs(exp_y)) / 2
if VERBOSE:
print(conf_int_X,
conf_int_Z,
f"{prob_stabilizers:1.8f}",
f"{correction_successful:1.8f}",
f"{exp_z:+1.8}",
f"{exp_x:+1.8}",
f"{exp_y:+1.8}"
)
prob_correction_logical_state.append(prob_stabilizers *
correction_successful
)
conf_stab_meas = int("".join(str(_)
for _ in conf_int_X + conf_int_Z)
)
prob_correction = np.real(np.sum(prob_correction_logical_state))
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
final_p_loss.append([phi_tilde,
conf_loss,
prob_correction,
prob_loss_event
])
np.savetxt(file_data_name,
final_p_loss,
fmt='%1.5f\t' +
'%07d\t' +
'%.18e\t' +
'%.18e\t')
np.savetxt(file_data_name,
final_p_loss,
fmt='%1.5f\t%07d\t%.18e\t%.18e\t')<file_sep>/utils/correct_state.py
import numpy as np
import qutip as qu
from itertools import product
from p_operators_qutrit import *
def deterministic_correct(losses, stab_qubit_list, stab_outcome):
if len(losses) == 1:
print(losses[0])
elif len(losses) == 2:
for j_outcome, outcome in enumerate(stab_outcome):
if outcome == -1:
affected_stabilizer = stab_qubit_list[j_outcome]
causing_qubits = list(set(affected_stabilizer) & set(losses))
print("affected_stabilizer", affected_stabilizer)
print("causing_qubits", causing_qubits)
stab_qubits = [[0,1,2,3], [1,2,4,5], [2,3,5,6]]
losses = [0,1, 6]
for x, y, z in product([1,-1],[1,-1],[1,-1]):
print(x, y, z)
deterministic_correct(losses, stab_qubits, [x,y,z])
print()<file_sep>/old_py/zero_loss_simulation_all_over_stabilizers_overrotation.py
#
# Case 1: Coherent errors (single and two qubit overrotation)
# with no stabilizers measurement errors
#
import numpy as np
import qutip as qu
import os
from itertools import product
from utils.binary_conf import binary_configurations
from utils.p_operators import *
# from utils.overrotation_channel import (CorrelatedOverRotQubitAll,
# SingleOverRotQubitAll)
import datetime
import argparse
np.set_printoptions(precision=4, suppress=True)
# python process_matrix_simulation_all.py --phi_tilde --epsilon_choi
parser = argparse.ArgumentParser(description="Simulate qubit losses"
"with QND measurement qubit+7qutrit system")
parser.add_argument('--phi_tilde',
type=float,
default=0.00,
help="Rotation angle"
)
parser.add_argument('--epsilon_choi',
type=float,
default=0.0,
help="epsilon_choi"
)
parser.add_argument('--logical_state',
type=int,
default=0,
help="logical state corresponding"
"to: 0, 1, +, -, +i, -i"
)
parser.add_argument('--chi_threshold',
type=float,
default=0.0,
help="threshold for discarding Kraus"
"operators in the chi matrix"
)
parser.add_argument('--dir_name',
type=str,
default="./",
help="directory for saving data"
)
parser.add_argument('--p_overrot_2',
type=float,
default=0.136,
help="over rotation MS gate"
)
parser.add_argument('--p_overrot_1',
type=float,
default=0.010,
help="over rotation single-qubit gates"
)
parser.add_argument('--num_trials',
type=int,
default=5000,
help="Number of Monte Carlo samples"
)
args = parser.parse_args()
phi_tilde = args.phi_tilde
phi = phi_tilde * np.pi
epsilon_choi = args.epsilon_choi
jLog = args.logical_state
chi_threshold = args.chi_threshold
p_overrot_2 = args.p_overrot_2
p_overrot_1 = args.p_overrot_1
eta = p_overrot_2 * np.pi
eps = p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
choi_ideal = np.loadtxt("choi_op/choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("choi_op/qubitqutrit_choi_noloss.csv",
dtype=complex,
delimiter=',')
if not os.path.exists(folder_name):
os.makedirs(folder_name)
choi = np.real((1 - epsilon_choi) * choi_ideal +
6 * epsilon_choi * choi_experiment
)
# T_matrix = give_transformation_matrix()
# chi_matrix = get_chi_from_choi(choi, T_matrix)
# chi_matrix[np.abs(chi_matrix) < chi_threshold] = 0
final_p_loss = []
# rotation_ops = Rloss_all(phi_tilde * np.pi)
result_correction = []
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
OverRotationOperators = CorrelatedOverRotQubitAll(p_overrot_2 * np.pi)
SingleOverRotations = SingleOverRotQubitAll(p_overrot_1 * np.pi)
now = datetime.datetime.now()
final_data_name = (now.strftime("%Y%m%d%H%M") +
f"_state_{LogicalStates_str[jLog]}_" +
f"phi_{phi_tilde:1.5f}_eps_{epsilon_choi}.dat"
)
file_data_name = os.path.join(folder_name,
final_data_name
)
print(f"logical state |{LogicalStates_str[jLog]}_L>")
index_confs = 0
final_prob = []
result_correction = []
num_losses = []
all_loss_events = binary_configurations().configurations_list
for outcomes_ancilla in all_loss_events:
index_confs += 1
prob_total_event = []
prob_correction_logical_state = []
psiL = LogicalStates[jLog]
list_qubits = list(range(L))
null_state = False
rho_L = psiL * psiL.dag()
for data_q in list_qubits:
# apply Rloss with an angle phi
# rho_L = rotation_ops[data_q] * rho_L * rotation_ops[data_q].dag()
# apply the QND detection unit
# rho_L = apply_qnd_process_unit(chi_matrix,
# rho_L,
# data_q,
# chi_threshold
# )
# apply the overrotations
if p_overrot_2 or p_overrot_1:
rho_L = (OverRotationOperators[data_q] *
rho_L *
OverRotationOperators[data_q].dag()
)
rho_L = (SingleOverRotations[data_q] *
rho_L *
SingleOverRotations[data_q].dag()
)
if outcomes_ancilla[data_q] == 0:
prob_outcome = (rho_L * Pp_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected in the
# +1 eigenstate of the ancilla
null_state = True
else:
rho_L = (Pp_ancilla *
rho_L *
Pp_ancilla.dag() / abs(prob_outcome))
elif outcomes_ancilla[data_q] == 1:
prob_outcome = (rho_L * Pm_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
null_state = True
else:
rho_L = (Pm_ancilla *
rho_L *
Pm_ancilla.dag() / abs(prob_outcome)
)
# reset ancilla
rho_L = Xa * rho_L * Xa.dag()
prob_total_event.append(prob_outcome)
print(data_q,
outcomes_ancilla[data_q],
prob_outcome)
prob_loss_event = np.abs(np.prod(prob_total_event))
losses = np.where(outcomes_ancilla)[0].tolist()
kept_qubits = list(set(range(L)) - set(losses))
if sum(outcomes_ancilla) >= 7 or null_state:
print(prob_loss_event)
correction_successful = 0.0
prob_correction_logical_state.append(correction_successful)
else:
w_0 = rho_L.ptrace(kept_qubits)
rho_L = (qu.tensor([qu.fock_dm(2, 0)] * len(losses) +
[w_0] +
[qu.fock_dm(2, 0)])
)
permutation_order_q = {}
for j, el in enumerate(losses + kept_qubits):
permutation_order_q[el] = j
# print("permutation_order_q", permutation_order_q)
stab_qubits_new_order = []
for stab in stab_qubits:
stab_qubits_new_order.append([permutation_order_q[q]
for q in stab]
)
Sx = [X[j1] * X[j2] * X[j3] * X[j4]
for j1, j2, j3, j4 in stab_qubits_new_order
]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4]
for j1, j2, j3, j4 in stab_qubits_new_order
]
PPx = [[(Id + el) / 2, (Id - el) / 2] for el in Sx]
PPz = [[(Id + el) / 2, (Id - el) / 2] for el in Sz]
index_stab_measurement = 0
cumulative_probability_stabilizers = 0.0
for meas_binary_X, meas_binary_Z in product(range(8), range(8)):
# if abs(1 - cumulative_probability_stabilizers) < 1e-4:
# exit if the cumulative probability
# during the stabilizer measurement
# is already close to 1
# break
state_after_measure = qu.Qobj(rho_L[:], dims=rho_L.dims)
conf_str_X = bin(meas_binary_X)[2:].zfill(3)
conf_int_X = [int(_) for _ in conf_str_X]
conf_str_Z = bin(meas_binary_Z)[2:].zfill(3)
conf_int_Z = [int(_) for _ in conf_str_Z]
probability_each_measurement = []
for stab_num, outcome_stab in enumerate(conf_int_X):
prob = (PPx[stab_num][outcome_stab] *
state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPx[stab_num][outcome_stab] *
state_after_measure *
PPx[stab_num][outcome_stab].dag() /
prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
for stab_num, outcome_stab in enumerate(conf_int_Z):
prob = (PPz[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPz[stab_num][outcome_stab] *
state_after_measure *
PPz[stab_num][outcome_stab].dag() /
prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
prob_stabilizers = np.prod(probability_each_measurement)
cumulative_probability_stabilizers += prob_stabilizers
exp_x = np.real(qu.expect(XL, state_after_measure))
exp_z = np.real(qu.expect(ZL, state_after_measure))
exp_y = np.real(qu.expect(1j * XL * ZL, state_after_measure))
print(conf_int_X,
conf_int_Z,
f"{prob_stabilizers:1.4f}",
f"{exp_x:+1.4f}",
f"{exp_z:+1.4f}",
f"{exp_y:+1.4f}"
)
if jLog in (0, 1):
correction_successful = (1 + abs(exp_z)) / 2
elif jLog in (2, 3):
correction_successful = (1 + abs(exp_x)) / 2
elif jLog in (4, 5):
correction_successful = (1 + abs(exp_y)) / 2
prob_correction_logical_state.append(prob_stabilizers *
correction_successful
)
conf_stab_meas = int("".join(str(_)
for _ in conf_int_X + conf_int_Z)
)
print("cumulative_probability_stabilizers: ", cumulative_probability_stabilizers)
prob_correction = np.real(np.sum(prob_correction_logical_state))
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
final_p_loss.append([phi_tilde,
conf_loss,
prob_correction,
prob_loss_event
])
np.savetxt(file_data_name,
final_p_loss,
fmt='%1.5f\t' +
'%07d\t' +
'%.18e\t' +
'%.18e\t')
<file_sep>/old_py/overrotation_all_stab.sh
#!/bin/bash
export OMP_NUM_THREADS=1
eps=0
chi=0
for overrot1 in 0.01 # 0.03162277660 #0.01 # 0.01 #0.03162277660
do
for overrot2 in 0.0961665 #0.136 # 0.4300697618 #0 #0.136 0.4300697618
do
folder=$(printf "case_1_new_2/chi_%.01e_eps_%1.3f_p2_%1.3f_p1_%1.3f" $chi $eps ${overrot2} ${overrot1})
echo ${overrot1}, ${overrot2}, ${folder}
mkdir -p $folder
i=0
for state in 2 #2
do
for c in $(seq -f "%1.4f" 0.050 0.050 0.50)
#$(seq -f "%1.4f" 0.050 0.050 0.950) #£$(seq -f "%1.4f" 0.005 0.005 0.045) # $(seq -f "%1.4f" 0.050 0.050 0.950)
do
echo $c $state
python simulation_all_over_stabilizers_overrotation.py \
--logical_state ${state} \
--phi_tilde ${c} \
--epsilon_choi ${eps} \
--chi_threshold ${chi} \
--p_overrot_1 ${overrot1} \
--p_overrot_2 ${overrot2} \
--dir_name $folder \
2>&1 >& 0_log_${c}_${eps}_${state}_${overrot2}_${overrot1}.log &
pids[${i}]=$!
i=$((i+1))
done
done
for pid in ${pids[*]}; do
wait $pid
done
done
done
for overrot1 in 0.01 # 0.03162277660 #0.01 # 0.01 #0.03162277660
do
for overrot2 in 0.0961665 #0.136 # 0.4300697618 #0 #0.136 0.4300697618
do
folder=$(printf "case_1_new_2/chi_%.01e_eps_%1.3f_p2_%1.3f_p1_%1.3f" $chi $eps ${overrot2} ${overrot1})
echo ${overrot1}, ${overrot2}, ${folder}
mkdir -p $folder
i=0
for state in 2 #2
do
for c in $(seq -f "%1.4f" 0.550 0.050 0.950)
#$(seq -f "%1.4f" 0.050 0.050 0.950) #£$(seq -f "%1.4f" 0.005 0.005 0.045) # $(seq -f "%1.4f" 0.050 0.050 0.950)
do
echo $c $state
python simulation_all_over_stabilizers_overrotation.py \
--logical_state ${state} \
--phi_tilde ${c} \
--epsilon_choi ${eps} \
--chi_threshold ${chi} \
--p_overrot_1 ${overrot1} \
--p_overrot_2 ${overrot2} \
--dir_name $folder \
2>&1 >& 0_log_${c}_${eps}_${state}_${overrot2}_${overrot1}.log &
pids[${i}]=$!
i=$((i+1))
done
done
for pid in ${pids[*]}; do
wait $pid
done
done
done
<file_sep>/utils/choi_qi.py
import numpy as np
import qutip as qu
import sys
from itertools import product
import matplotlib.pyplot as plt
from matplotlib import colors
PLOT = True
SAVEFILE = False
def proj(ket, bra, dimH = 2):
if isinstance(ket, str):
states_ket = [int(_) for _ in ket]
ket_s = qu.basis([dimH] * len(states_ket), states_ket)
elif isinstance(ket, int):
states_ket = ket
ket_s = qu.basis(dimH, states_ket)
if isinstance(bra, str):
states_bra = [int(_) for _ in bra]
bra_s = qu.basis([dimH] * len(states_bra), states_bra).dag()
elif isinstance(bra, int):
states_bra = bra
bra_s = qu.basis(dimH, states_bra).dag()
return ket_s * bra_s
dimHa = 2
dimHq = 3
GammaState = sum([qu.tensor(qu.basis(dimHa, ja), qu.basis(dimHq, jq), qu.basis(dimHa, ja), qu.basis(dimHq, jq))
for ja,jq in product(range(dimHa), range(dimHq))])/np.sqrt(dimHa * dimHq)
rhoGamma = GammaState * GammaState.dag()
for phi_tilde in [0.0, 1/2, 3/4]:
phi = phi_tilde * np.pi
rot = [ [np.cos(phi/2), 0, np.sin(phi/2)],
[0, 1, 0],
[-np.sin(phi/2), 0, np.cos(phi/2)]
]
Rloss = qu.tensor(qu.qeye(dimHa), qu.Qobj(rot))
msGate = qu.tensor(qu.sigmax(), qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])) + qu.tensor(qu.qeye(dimHa), proj(2, 2, 3))
RxA = qu.tensor(qu.sigmax(), qu.qeye(dimHq)) # bit flip ancilla
temp_Xq = proj(2, 2, dimHq) + proj(1, 0, dimHq) + proj(0, 1, dimHq) # bit flip qutrit
RxQ = qu.tensor(qu.qeye(dimHa), temp_Xq)
U = RxA * RxQ * msGate * Rloss
choiState = qu.tensor(qu.qeye(dimHa), qu.qeye(dimHq), U) * rhoGamma * qu.tensor(qu.qeye(dimHa), qu.qeye(dimHq), U.dag())
A = choiState.full().real
if PLOT:
base_S = [(x,y) for x,y in product(range(2), range(3))]
label_axis =[ "".join([str(_) for _ in bR])+ "," + "".join([str(_) for _ in bS]) for (bR, bS) in product(base_S, base_S) ]
fig, ax = plt.subplots()
img = ax.matshow(A, cmap='RdGy' ) #, interpolation='nearest', cmap=cmap, norm=norm)#, extent=[36,0,36,0])
# img.set_clim(vmin=-1/np.sqrt(6), vmax=1/np.sqrt(6))
img.set_clim(vmin=-1/6, vmax=1/6)
fig.colorbar(img)
plt.title(f"$\phi={phi_tilde:1.2f}\pi$" + " $p_\mathrm{loss}"+ f"={np.sin(phi_tilde*np.pi/2)**2:1.2f}$")
ax.set_yticks(range(len(label_axis)))#, minor = True)
ax.set_yticklabels(label_axis, fontsize = 8)#), minor = True)
ax.set_xticks(range(len(label_axis)), [])
ax.set_xticklabels([])
ax=plt.gca()
ax.set_xticks([x-0.5 for x in range(1,36)],minor=True )
ax.set_yticks([y-0.5 for y in range(1,36)],minor=True)
plt.grid(which="minor",ls="-",lw=0.2, color='w')
ax.tick_params(which='minor', length=0, color='w')
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('top')
for j in range(6):
ax.axhline(y=6*j - 0.5,color='lightgrey', linewidth=1, linestyle='-')
ax.axvline(x=6*j - 0.5,color='lightgrey', linewidth=1, linestyle='-')
plt.show()
# plt.savefig(f"choiFinal_ideal_{phi_tilde}.pdf", bbox_inches='tight')
if SAVEFILE:
np.savetxt(f"choiFinal_ideal_{phi_tilde:1.2f}.dat", choiState, delimiter=',')
<file_sep>/utils/p_operators.py
import qutip as qu
import numpy as np
# ancilla always the last qubit
L = 7
# Hilbert space dimension data qubit / ancilla
dimQ = 2
dimA = 2
Id = qu.tensor([qu.qeye(dimQ)] * L + [qu.qeye(2)])
temp = [[qu.qeye(dimQ)] * j +
[qu.sigmax()] +
[qu.qeye(dimQ)] * (L - j - 1) +
[qu.qeye(2)]
for j in range(L)
]
X = [qu.tensor(temp[j]) for j in range(L)]
temp = [[qu.qeye(dimQ)] * j +
[qu.sigmay()] +
[qu.qeye(dimQ)] * (L - j - 1) +
[qu.qeye(2)]
for j in range(L)
]
Y = [qu.tensor(temp[j]) for j in range(L)]
temp = [[qu.qeye(dimQ)] * j +
[qu.sigmaz()] +
[qu.qeye(dimQ)] * (L - j - 1) +
[qu.qeye(2)]
for j in range(L)
]
Z = [qu.tensor(temp[j]) for j in range(L)]
# ancilla operators
temp = [qu.qeye(dimQ)] * L + [qu.sigmax()]
Xa = qu.tensor(temp)
temp = [qu.qeye(dimQ)] * L + [qu.sigmaz()]
Za = qu.tensor(temp)
Pp_ancilla = (Id + Za) / 2
Pm_ancilla = (Id - Za) / 2
stab_qubits = [[0, 1, 2, 3],
[1, 2, 4, 5],
[2, 3, 5, 6]
]
Sx = [X[j1] * X[j2] * X[j3] * X[j4]
for j1, j2, j3, j4 in stab_qubits
]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4]
for j1, j2, j3, j4 in stab_qubits
]
ZL = Z[0] * Z[1] * Z[2] * Z[3] * Z[4] * Z[5] * Z[6]
XL = X[0] * X[1] * X[2] * X[3] * X[4] * X[5] * X[6]
Px = [(Id + el) / 2 for el in Sx]
Pz = [(Id + el) / 2 for el in Sz]
Pmx = [(Id - el) / 2 for el in Sx]
Pmz = [(Id - el) / 2 for el in Sz]
vacuum = qu.tensor([qu.basis(2, 0)] * L + [qu.basis(2, 0)])
# logical states
ZeroL = (Px[0] * Px[1] * Px[2] * vacuum).unit()
OneL = (XL * ZeroL).unit()
LogicalStates = [ZeroL,
OneL,
(ZeroL + OneL) / np.sqrt(2),
(ZeroL - OneL) / np.sqrt(2),
(ZeroL + 1j * OneL) / np.sqrt(2),
(ZeroL - 1j * OneL) / np.sqrt(2)
]
# ancilla operators
temp = [qu.qeye(dimQ)] * L + [qu.sigmax()]
Xa = qu.tensor(temp)
temp = [qu.qeye(dimQ)] * L + [qu.sigmaz()]
Za = qu.tensor(temp)
Pp_ancilla = (Id + Za) / 2
Pm_ancilla = (Id - Za) / 2
def CorrelatedOverRotQubit(qutrit_n, alpha):
dimHq = 2
dimHa = 2
# X_qutrit = qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
# ket22bra = qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
X_qutrit = qu.sigmax()
ket22bra = qu.Qobj([[0, 0], [0, 0]])
Id = [qu.qeye(dimHq)] * L + [qu.qeye(dimHa)]
XX_operators_1 = ([qu.qeye(dimHq)] * qutrit_n +
[X_qutrit] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[qu.sigmax()]
)
XX_operators_2 = ([qu.qeye(dimHq)] * qutrit_n +
[ket22bra] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[qu.qeye(dimHa)]
)
corr = (np.cos(alpha / 2) * qu.tensor(Id) +
1j * np.sin(alpha / 2) * (qu.tensor(XX_operators_1) +
qu.tensor(XX_operators_2))
)
return corr
def CorrelatedOverRotQubitAll(alpha):
return [CorrelatedOverRotQubit(qutrit_n, alpha) for qutrit_n in range(L)]
def SingleOverRotQubit(qutrit_n, theta):
dimHq = 2
dimHa = 2
# X_qutrit = qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
# ket22bra = qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
X_qutrit = qu.sigmax()
ket22bra = qu.Qobj([[0, 0], [0, 0]])
R1q = (np.cos(theta / 2) * (qu.qeye(dimHq) - ket22bra) -
1j * np.sin(theta / 2) * X_qutrit +
ket22bra
)
R1a = (np.cos(theta / 2) * qu.qeye(dimHa) -
1j * np.sin(theta / 2) * qu.sigmax()
)
OverRotSingle = ([qu.qeye(dimHq)] * qutrit_n +
[R1q] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[R1a]
)
corr = qu.tensor(OverRotSingle)
return corr
def SingleOverRotQubitAll(theta):
return [SingleOverRotQubit(qutrit_n, theta) for qutrit_n in range(L)]<file_sep>/utils/estimate_depol_channel.py
import qutip as qu
import numpy as np
import scipy.linalg
from scipy.linalg import eigh, svd
from p_operators_qutrit import get_chi_from_choi, give_transformation_matrix, normalize_operators
from itertools import product
import matplotlib.pyplot as plt
_lambdas_GM = [[[ 1, 0, 0], [ 0, 1, 0], [0, 0, 1]],
[[ 0 , 1 , 0], [1 , 0 , 0], [0 , 0 , 0 ]],
[[ 0 , -1j , 0], [1j , 0 , 0], [0 , 0 , 0 ] ],
[[ 1 , 0 , 0], [0 , -1 , 0], [0 , 0 , 0 ] ],
[[ 0 , 0 , 1], [0 , 0 , 0], [1 , 0 , 0 ] ],
[[ 0 , 0 , -1j], [0 , 0 , 0], [1j , 0 , 0 ] ],
[[ 0 , 0 , 0], [0 , 0 , 1], [0 , 1 , 0 ] ],
[[ 0 , 0 , 0], [0 , 0 , -1j], [0 , 1j , 0 ] ],
[[ 1 , 0 , 0], [0 , 1 , 0], [0 , 0 , -2 ]]]
_sigmas_P = [[[1, 0], [0, 1]],
[[0, 1], [1, 0]],
[[0, -1j], [1j,0]],
[[1,0], [0,-1]]]
def proj(ket, bra, dimH = 2):
"""
Define basis projector operators|ket >< bra|
"""
if isinstance(ket, str):
states_ket = [int(_) for _ in ket]
ket_s = qu.basis([dimH] * len(states_ket), states_ket)
elif isinstance(ket, int):
states_ket = ket
ket_s = qu.basis(dimH, states_ket)
if isinstance(bra, str):
states_bra = [int(_) for _ in bra]
bra_s = qu.basis([dimH] * len(states_bra), states_bra).dag()
elif isinstance(bra, int):
states_bra = bra
bra_s = qu.basis(dimH, states_bra).dag()
return ket_s * bra_s
def experimental_qnd_channel(chi_matrix):
on_basis_lambda = normalize_operators(_lambdas_GM)
on_basis_Pauli = normalize_operators(_sigmas_P)
rows, cols = chi_matrix.shape
final_state_list = []
for alpha, beta in product(range(rows), range(cols)):
if chi_matrix[alpha, beta]:
a_GM = alpha % 9
a_Pauli = (alpha - a_GM) // 9
OP_temp = [on_basis_Pauli[a_Pauli], on_basis_lambda[a_GM]]
OP_1 = qu.tensor(OP_temp)
b_GM = beta % 9
b_Pauli = (beta - b_GM) // 9
OP_temp = [on_basis_Pauli[b_Pauli], on_basis_lambda[b_GM]]
OP_2 = qu.tensor(OP_temp)
action = chi_matrix[alpha, beta] * qu.spre(OP_1) * qu.spost(OP_2.dag())
final_state_list.append(action)
QND_exp_channel = sum(final_state_list)
return QND_exp_channel
def depolarization_channel(p_dep):
# Define Omega state for computing Choi matrix
# omega = [00,01,02,10,11,12] * [00,01,02,10,11,12] ancilla first
omega = sum([qu.tensor(qu.basis(2, i), qu.basis(3, j),
qu.basis(2, i), qu.basis(3, j))
for i, j in product(range(2), range(3))])
omega_state = omega * omega.dag()
dimHtot = 2 * 3
choi_depolarizing = (p_dep * qu.tensor(qu.qeye(2), qu.qeye(3), qu.qeye(2) , qu.qeye(3))/dimHtot
+ (1 - p_dep) * omega_state)
vals, vecs = eigh(choi_depolarizing.data.todense())
kraus_matrix = [np.sqrt(vals[j]) * vecs[:, j].reshape((dimHtot, dimHtot)).T for j in range(len(vecs))]
system_length = len(choi_depolarizing.dims[0])//2
dim_kraus = [choi_depolarizing.dims[0][-system_length:], choi_depolarizing.dims[0][-system_length:]]
kraus_ops = [qu.Qobj(inpt=op, dims=dim_kraus) for op in kraus_matrix]
channel_dep = sum([qu.spre(op) * qu.spost(op.dag()) for op in kraus_ops])
return channel_dep
if __name__ == "__main__":
np.set_printoptions(precision = 4, suppress = True, linewidth=100000)
omega = sum([qu.tensor(qu.basis(2, i), qu.basis(3, j),
qu.basis(2, i), qu.basis(3, j))
for i, j in product(range(2), range(3))])
omega_state = omega * omega.dag()
dimHtot = 2 * 3
choi_experiment = np.genfromtxt("qubitqutrit_choi_noloss.csv", dtype=complex, delimiter=',')
#Define the ideal channel with A0 and A1 operators:
# A0 = |1><1|+|0><0|
A0 = proj(1, 1, dimH = 3) + proj(0, 0, dimH = 3)
# A1 = |2><2|
A1 = proj(2, 2, dimH = 3)
id_a = qu.qeye(2)
X_a = qu.sigmax()
id_all = qu.tensor(qu.qeye(2), qu.qeye(3))
QND_ideal = qu.tensor(id_a, A0) + qu.tensor(X_a, A1)
# QND_ideal =
# [[1. 0. 0. 0. 0. 0.]
# [0. 1. 0. 0. 0. 0.]
# [0. 0. 0. 0. 0. 1.]
# [0. 0. 0. 1. 0. 0.]
# [0. 0. 0. 0. 1. 0.]
# [0. 0. 1. 0. 0. 0.]]
choi_experiment = np.genfromtxt("qubitqutrit_choi_noloss.csv", dtype=complex, delimiter=',')
distances_list = []
fidelities_list = []
list_prob = np.linspace(0,1) #p of depolarizing noise
for p_dep in list_prob:
channel_dep = depolarization_channel(p_dep)
#construct the choi matrix of the ideal QND followed by the depolarization channel
choi_parts_ideal_depol = []
for i1, j1 in product(range(2), range(3)):
for i2, j2 in product(range(2), range(3)):
state_ket = qu.tensor(qu.basis(2, i1), qu.basis(3, j1))
state_bra = qu.tensor(qu.basis(2, i2), qu.basis(3, j2)).dag()
Qij = QND_ideal * state_ket * state_bra * QND_ideal.dag()
tenso_ij_depol_Qij = qu.tensor(state_ket * state_bra, channel_dep(Qij))
choi_parts_ideal_depol.append(tenso_ij_depol_Qij)
choi_ideal_and_depol = sum(choi_parts_ideal_depol) / 6.
row, cols = choi_ideal_and_depol.shape
u1 = choi_ideal_and_depol.full().reshape((row * cols, 1))
u2 = choi_experiment.reshape((row * cols, 1))
distance_2 = scipy.linalg.norm(u1-u2)
distances_list.append([p_dep, distance_2])
choi_depolarizing = (p_dep * qu.tensor(qu.qeye(2), qu.qeye(3), qu.qeye(2) , qu.qeye(3))/dimHtot
+ (1 - p_dep) * omega_state)
choi_experiment_op = qu.Qobj(inpt=choi_experiment, dims=choi_depolarizing.dims, type=choi_depolarizing.type)
print(qu.process_fidelity(choi_depolarizing, choi_experiment_op))
fidelities_list.append([p_dep, qu.process_fidelity(choi_depolarizing, choi_experiment_op)])
distances_array = np.array(distances_list)
fidelities_array = np.array(fidelities_list)
arg_min = np.argmin(distances_array[:,1])
print(distances_array[arg_min])
print("-----", distances_array[arg_min][0])
choi_experiment = 6 * np.real(np.genfromtxt("qubitqutrit_choi_noloss.csv", dtype=complex, delimiter=','))
T_matrix = give_transformation_matrix()
chi_matrix = np.real(get_chi_from_choi(choi_experiment, T_matrix))
exp_QND = experimental_qnd_channel(chi_matrix)
channel_dep_close = depolarization_channel(distances_array[arg_min][0])
p_dep_min = distances_array[arg_min][0]
plt.plot(distances_array[:,0],distances_array[:,1], '-', label="Cost function $C(p)$")
plt.plot(distances_array[:,0],fidelities_array[:,1], '-', label="Process fidelity")
plt.xlabel("depolarizing error p")
# plt.ylabel("cost function")
plt.title(f"depolarizing error p min = {distances_array[arg_min][0]:.3}")
ax = plt.gca()
from matplotlib.ticker import AutoMinorLocator
ax.xaxis.set_minor_locator(AutoMinorLocator())
ax.yaxis.set_minor_locator(AutoMinorLocator())
# ax.tick_params(axis='x', which='minor', bottom=False)
plt.plot([distances_array[arg_min][0]], [distances_array[arg_min][1]], 'o')
plt.legend()
plt.savefig("distances_p_depol.pdf")
plt.show()
<file_sep>/case_2_zero_loss_commented/plot_all.py
import numpy as np
import pandas as pd
import os
import matplotlib
matplotlib.rcParams.update({'font.size': 14})
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
marker_list = list(Line2D.markers.keys())
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
files = []
directory = './'
list_dirs = []
for filename in os.listdir(directory):
if os.path.isdir(filename) and filename.startswith("chi"):
list_dirs.append(filename)
figura = plt.figure()
ax = figura.add_subplot(111)
#ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
x = np.arange(0, 0.5, 0.01)
plt.plot(x, 1 - x, '-')
x_data = np.arange(0, 0.5, 0.01)
y_data = 1 - 7*x_data**3 + 21*x_data**5 - 21*x_data**6 + 6*x_data**7
# plt.plot(x, y_data, '-')
print(list_dirs)
final_prob_list = []
for folder in sorted(list_dirs):
split_folder_name = folder.split("_")
err_stab = 0.0 #float(split_folder_name[-1])
p1 = float(split_folder_name[-1])
p2 = float(split_folder_name[-3])
epsilon = float(split_folder_name[-5])
number_of_files = len([filename for filename in os.listdir(folder) if filename.startswith("2")])
# if number_of_files == 1: continue
prob_success_state = {}
for filename in os.listdir(folder):
if (filename.startswith("2") and
filename.endswith(".dat") and
(("state_0_" in filename) or ("state_+_" in filename))
):
epsilon = float(filename[:-4].split("_")[-1])
log_state = filename[:-4].split("_")[-5]
A = np.loadtxt(os.path.join(folder, filename))
if len(A.shape) == 1:
A = np.array([A])
phi_tilde = A[0, 0]
phi_tilde_str = f"{phi_tilde:1.6f}"
prob_channel = A[:, 3]
prob_ancilla = A[:, 4]
prob_success = 1#A[:, 4]
print(sum(prob_channel*prob_ancilla))
key = log_state + "_" + phi_tilde_str
final_prob = sum(prob_channel
* prob_ancilla
)
print(filename, final_prob)
if log_state in prob_success_state:
prob_success_state[key].append(final_prob)
else:
prob_success_state[key] = [final_prob]
phis = []
final_prob = {}
for key, val in prob_success_state.items():
print(key, val, "-----------,", epsilon)
exit()
log_operator = key.split("_")[0]
phi_tilde = float(key.split("_")[1])
log_state = key.split("_")[0]
final_prob_list.append(
{'log_operator': log_operator,
'phi_tilde': phi_tilde,
'epsilon': epsilon,
'p2': p2,
'p1': p1,
'err_stab': err_stab,
'prob_success_state': prob_success_state[key][0]
})
results_df = pd.DataFrame(final_prob_list)
print(results_df)
exit()
results_df.sort_values(by=['log_operator', 'phi_tilde'], inplace=True)
B = results_df.groupby(['p2',
'p1',
'err_stab',
'phi_tilde',
'epsilon'
], as_index=False).mean()
C = B.groupby(['p2', 'p1', 'epsilon', 'err_stab'])
marker_idx = 2
out_files = []
for k, gr in C:
p2, p1, epsilon, err_stab = k
print(p2, p1, epsilon)
sorted_data = gr.sort_values(by=['phi_tilde'])
print(sorted_data)
x = np.sin(np.pi * sorted_data['phi_tilde']/2)**2 / 2
y = sorted_data['prob_success_state']
label_plot = ('p_2 =' + f'{p2:1.5f}' +
' p_1 =' + f'{p1:1.5f}'
# ' err_stab =' + f'{err_stab:1.2f}'
)
plt.plot(x, y,
linestyle='-',
marker=marker_list[marker_idx],
label=label_plot
)
marker_idx += 1
name_csv = (f"eps_{epsilon:1.5f}_p2_{p2:1.5f}_" +
f"p1_{p1:1.5f}_errorstab_{err_stab:1.5f}")
out_files.append(name_csv + '.csv')
print(name_csv)
sorted_data.to_csv(name_csv + '.csv', index=False)
print(sorted_data.values)
# print(type(sorted_data.values))
plt.title("Incoherent over-rotations")
plt.xlabel("$p_{loss}$")
plt.ylabel("$p_{success}$")
plt.legend(fontsize=10)
plt.savefig("incoherent_errors_inverted.pdf",
bbox_inches="tight"
)
# plt.savefig("../notes/false_pos_neg_success_probability_choi.pdf", bbox_inches="tight")
for namef in out_files:
print(f'"{namef:s}",')
dfs = [f"{namef:s}" for namef in out_files]
frames = [pd.read_csv(x) for x in dfs]
result = pd.concat(frames)
result.to_csv("raw_data_merged_case_2_zero_loss_qutrit.csv", index=False)
for namef in out_files:
os.remove(namef)
# folder=("/Users/vodola/Dropbox/ColorCodeLattice/"
# "losses_steane_code/choi_operators/notes/case_1/")
#
#
# plt.savefig(folder + "coherent_errors.pdf",
# bbox_inches="tight"
# )
<file_sep>/utils/choi_repr.py
"""
`choi_repr` contains several functions for computing and managing the
the choi operator of a qubit-qutrit system
"""
import numpy as np
import qutip as qu
import sys
from itertools import product
from p_operators_qutrit import proj
def apply_choi(rho, choiState):
dimTot = stateTry.shape[0]
if rho.type == "ket":
rho = (rho * rho.dag()).unit()
finalState = sum([rho[i,j] * choiState[dimTot*i : dimTot*i + dimTot, dimTot*j: dimTot*j + dimTot]
for i,j in product(range(dimTot), range(dimTot))])
finalState = qu.Qobj(inpt=finalState, dims=rho.dims)
return finalState
# for plotting experimental choi operators
if 0: #__name__ == "__main__":
import matplotlib.pyplot as plt
from matplotlib import colors
from itertools import product
base_S = [(x,y) for x,y in product(range(2), range(3))]
label_axis =[ "".join([str(_) for _ in bR])+ "," + "".join([str(_) for _ in bS]) for (bR, bS) in product(base_S, base_S) ]
choi_experiment = np.genfromtxt("qubitqutrit_choi_noloss.csv", dtype=complex, delimiter=',')
np.set_printoptions(precision=4, suppress=True, threshold=sys.maxsize)
ratio = np.abs(choi_experiment.imag)/np.abs(choi_experiment.real)
#compute and print ratio imaginary / real part
for i,j in product(range(ratio.shape[0]), range(ratio.shape[1])) :
print(f"{i: 3d},{j: 3d}, {abs(choi_experiment.real[i,j]):1.2e}, {abs(choi_experiment.imag[i,j]):1.2e}, {ratio[i,j]:6.2f}")
for index, A in enumerate([choi_experiment.real, choi_experiment.imag, np.abs(choi_experiment.imag)/np.abs(choi_experiment.real) ]):
str_img = ["real", "imag", "ratio"][index]
fig, ax = plt.subplots()
img = ax.matshow(A, cmap='RdGy' ) #, interpolation='nearest', cmap=cmap, norm=norm)#, extent=[36,0,36,0])
if index < 2:
img.set_clim(vmin=-0.15, vmax=0.15)
fig.colorbar(img)
plt.title(f"choi experiment no loss {str_img}")
ax.set_yticks(range(len(label_axis)))#, minor = True)
ax.set_yticklabels(label_axis, fontsize = 8)#), minor = True)
ax.set_xticks(range(len(label_axis)), [])
ax.set_xticklabels([])
ax=plt.gca()
ax.set_xticks([x-0.5 for x in range(1,36)],minor=True )
ax.set_yticks([y-0.5 for y in range(1,36)],minor=True)
plt.grid(which="minor",ls="-",lw=0.2, color='w')
ax.tick_params(which='minor', length=0, color='w')
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('top')
for j in range(6):
ax.axhline(y=6*j - 0.5,color='lightgrey', linewidth=1, linestyle='-')
ax.axvline(x=6*j - 0.5,color='lightgrey', linewidth=1, linestyle='-')
#ax.yaxis.grid(True, which='major')
# plt.show()
plt.savefig(f"choi_exp_noloss_{str_img}.pdf", bbox_inches='tight')
# for plotting ideal choi operators
if __name__ == "__main__":
dimHa = 2
dimHq = 3
dimTot = dimHa * dimHq
GammaState = sum([qu.tensor(qu.basis(dimHa, ja), qu.basis(dimHq, jq), qu.basis(dimHa, ja), qu.basis(dimHq, jq))
for ja,jq in product(range(dimHa), range(dimHq))])
rhoGamma = GammaState * GammaState.dag()
phi_tilde = 1 / 2 ## loss 50%
# phi_tilde = 3 / 4. ## loss 85%
for phi_tilde in [0.0, 1/2, 3/4]:
phi = phi_tilde * np.pi
A0 = proj(1, 1, dimHq) + np.cos(phi/2) * proj(0, 0, dimHq) + np.sin(phi/2) * proj(0, 2, dimHq)
A1 = - np.sin(phi/2) * proj(2, 0, dimHq) + np.cos(phi/2) * proj(2, 2, dimHq)
# U = qu.tensor(qu.qeye(dimHa), A0) + qu.tensor(qu.sigmax(), A1)
rot = [ [np.cos(phi/2), 0, np.sin(phi/2)],
[0, 1, 0],
[-np.sin(phi/2), 0, np.cos(phi/2)]
]
Rloss = qu.tensor(qu.qeye(dimHa), qu.Qobj(rot))
msGate = qu.tensor(qu.qeye(dimHa), proj(2, 2, 3)) + qu.tensor(qu.sigmax(), qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]]))
RxA = qu.tensor(qu.sigmax(), qu.qeye(dimHq)) # bit flip ancilla
RxQ = qu.tensor(qu.qeye(dimHa), qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]]) + qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 0, 1]])) # bit flip qutrit
print(RxA.dims)
print(RxQ.dims)
print(msGate.dims)
print(Rloss.dims)
print(RxQ)
U = RxA * RxQ * msGate * Rloss
choiState = qu.tensor(qu.qeye(dimHa), qu.qeye(dimHq), U) * rhoGamma * qu.tensor(qu.qeye(dimHa), qu.qeye(dimHq), U.dag())
import matplotlib.pyplot as plt
from matplotlib import colors
from itertools import product
base_S = [(x,y) for x,y in product(range(2), range(3))]
label_axis =[ "".join([str(_) for _ in bR])+ "," + "".join([str(_) for _ in bS]) for (bR, bS) in product(base_S, base_S) ]
CC = choiState.full() / 6
for A in [choiState.full().real / 6]: #, choiState.full().imag / 6] :
fig, ax = plt.subplots()
img = ax.matshow(A, cmap='RdGy' ) #, interpolation='nearest', cmap=cmap, norm=norm)#, extent=[36,0,36,0])
img.set_clim(vmin=-0.15, vmax=0.15)
fig.colorbar(img)
plt.title(f"$\phi={phi_tilde:1.2f}\pi$" + " $p_\mathrm{loss}"+ f"={np.sin(phi_tilde*np.pi/2)**2:1.2f}$")
ax.set_yticks(range(len(label_axis)))#, minor = True)
ax.set_yticklabels(label_axis, fontsize = 8)#), minor = True)
ax.set_xticks(range(len(label_axis)), [])
ax.set_xticklabels([])
ax=plt.gca()
ax.set_xticks([x-0.5 for x in range(1,36)],minor=True )
ax.set_yticks([y-0.5 for y in range(1,36)],minor=True)
plt.grid(which="minor",ls="-",lw=0.2, color='w')
ax.tick_params(which='minor', length=0, color='w')
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('top')
for j in range(6):
ax.axhline(y=6*j - 0.5,color='lightgrey', linewidth=1, linestyle='-')
ax.axvline(x=6*j - 0.5,color='lightgrey', linewidth=1, linestyle='-')
#ax.yaxis.grid(True, which='major')
plt.show()
# np.savetxt(f"choiFinal_ideal_{phi_tilde:1.2f}.dat", CC, delimiter=',')
# plt.savefig(f"choiFinal_ideal_{phi_tilde}.pdf", bbox_inches='tight')
<file_sep>/utils/depolarizing_channel.py
import numpy as np
import qutip as qu
L = 7
def DepolQubit(i, p): # Qubit Kraus-operators for depolarizing channel
dimHq = 3
index = [
np.sqrt(1 - 3 * p / 4) * qu.qeye(2),
np.sqrt(p / 4) * qu.sigmax(),
np.sqrt(p / 4) * qu.sigmay(),
np.sqrt(p / 4) * qu.sigmaz()
]
return qu.tensor([qu.qeye(dimHq)] * 7 + [index[i]])
def DepolQutrit(qutrit_n, i, p): # Qutrit Kraus-operators for depolarizing channel
dimHq = 3
dimHa = 2
index = [
np.sqrt(3 - 8 * p / 3) / np.sqrt(3) * qu.Qobj([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dims=[[3], [3]]),
np.sqrt(p / 3) / np.sqrt(2) * qu.Qobj([[1, 0, 0], [0, 0, 0], [0, 0, -1]], dims=[[3], [3]]),
np.sqrt(p / 3) * qu.Qobj([[0, 0, 0], [0, 0, 1], [0, 0, 0]], dims=[[3], [3]]),
np.sqrt(p / 3) * qu.Qobj([[0, 0, 1], [0, 0, 0], [0, 0, 0]], dims=[[3], [3]]),
np.sqrt(p / 3) * qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 1, 0]], dims=[[3], [3]]),
np.sqrt(p / 3) / np.sqrt(6) * qu.Qobj([[1, 0, 0], [0, -2, 0], [0, 0, 1]], dims=[[3], [3]]),
np.sqrt(p / 3) * qu.Qobj([[0, 1, 0], [0, 0, 0], [0, 0, 0]], dims=[[3], [3]]),
np.sqrt(p / 3) * qu.Qobj([[0, 0, 0], [0, 0, 0], [1, 0, 0]], dims=[[3], [3]]),
np.sqrt(p / 3) * qu.Qobj([[0, 0, 0], [1, 0, 0], [0, 0, 0]], dims=[[3], [3]])
]
temp = [qu.qeye(dimHq)] * qutrit_n + [index[i]] + [qu.qeye(dimHq)] * (L - qutrit_n - 1) + [qu.qeye(dimHa)]
return qu.tensor(temp)
def UnitaryQubitQutritQNDDepol(p, state_rho, qutrit_n): # depolarizing channel on ancilla qubit & system qutrit
Depol = 0
for i in range(4):
for j in range(9):
Depol = (Depol +
DepolQubit(i,p) * DepolQutrit(qutrit_n, j,p) * state_rho
* DepolQutrit(qutrit_n, j,p).dag() * DepolQubit(i,p).dag() )
return Depol / np.trace(Depol.data.toarray())
if __name__ == "__main__":
print("c")
p = 1.00
qutrit_n = 6
vacuum = qu.tensor([qu.basis(3,0)] * L + [qu.basis(2,0)])
state_rho = vacuum*vacuum.dag()
for data_q in range(7):
state_rho = UnitaryQubitQutritQNDDepol(p, state_rho, data_q)
<file_sep>/utils/binary_conf.py
import numpy as np
from itertools import product
class binary_raw_configurations(object):
def __init__(self, n=6):
self.n = n
configurations = []
for i in range(2**n):
configuration_str = bin(i)[2:].zfill(n)
configuration_int = [int(_) for _ in configuration_str]
configurations.append(configuration_int)
self.configurations = configurations
def get_binary_confs(n):
configurations = {}
for i in range(2**n):
configuration_str = bin(i)[2:].zfill(n)
configuration_int = [int(_) for _ in configuration_str]
num_particles = sum(configuration_int)
if num_particles in configurations:
configurations[num_particles].append(configuration_int)
else:
configurations[num_particles] = [configuration_int]
configurations_list = []
for j in range(n + 1):
configurations_list.extend(configurations[j])
return configurations_list
class binary_configurations(object):
def __init__(self, n=7):
self.n = n
configurations = {}
for i in range(2**n):
configuration_str = bin(i)[2:].zfill(n)
configuration_int = [int(_) for _ in configuration_str]
num_particles = sum(configuration_int)
if num_particles in configurations:
configurations[num_particles].append(configuration_int)
else:
configurations[num_particles] = [configuration_int]
self.configurations = configurations
conf_temp = []
for j in range(n + 1):
conf_temp.extend(configurations[j])
self.configurations_list = conf_temp
def generate_configuration_loss_qnderror(self, num_l, num_q):
configuration_loss = []
configuration_qnd = []
configuration_loss = self.configurations[num_l]
configuration_qnd = self.configurations[num_q]
return product(configuration_loss, configuration_qnd)
class binary_configurations_loss_qnd_stab(object):
def __init__(self, n=7, stab=3):
self.n = n
configurations = {}
for i in range(2**n):
configuration_str = bin(i)[2:].zfill(n)
configuration_int = [int(_) for _ in configuration_str]
num_particles = sum(configuration_int)
if num_particles in configurations:
configurations[num_particles].append(configuration_int)
else:
configurations[num_particles] = [configuration_int]
self.configurations = configurations
configurations_stab = {}
for i in range(2**stab):
configuration_str = bin(i)[2:].zfill(stab)
configuration_int = [int(_) for _ in configuration_str]
num_particles = sum(configuration_int)
if num_particles in configurations_stab:
configurations_stab[num_particles].append(configuration_int)
else:
configurations_stab[num_particles] = [configuration_int]
self.configurations_stab = configurations_stab
def generate_configuration_loss_qnderror(self, num_l, num_q, num_stab):
configuration_loss = []
configuration_qnd = []
configuration_loss = self.configurations[num_l]
configuration_qnd = self.configurations[num_q]
configurations_stab = self.configurations_stab[num_stab]
return product(configuration_loss,
configuration_qnd,
configurations_stab)
class binary_configurations_false_pn(object):
def __init__(self, n=7, stab=3):
self.n = n
configurations = {}
for i in range(2**n):
configuration_str = bin(i)[2:].zfill(n)
configuration_int = [int(_) for _ in configuration_str]
num_particles = sum(configuration_int)
if num_particles in configurations:
configurations[num_particles].append(configuration_int)
else:
configurations[num_particles] = [configuration_int]
self.configurations = configurations
configurations_stab = {}
for i in range(2**stab):
configuration_str = bin(i)[2:].zfill(stab)
configuration_int = [int(_) for _ in configuration_str]
num_particles = sum(configuration_int)
if num_particles in configurations_stab:
configurations_stab[num_particles].append(configuration_int)
else:
configurations_stab[num_particles] = [configuration_int]
self.configurations_stab = configurations_stab
def generate_configuration_loss_qnderror(self, num_l, num_q, num_stab):
configuration_loss = []
configuration_qnd = []
configuration_loss = self.configurations[num_l]
configuration_qnd = self.configurations[num_q]
configurations_stab = self.configurations_stab[num_stab]
return product(configuration_loss,
configuration_qnd,
configurations_stab)
def check_correctable_state_analytics(random_losses, qnd_errors):
non_correctable_3_events = [[0, 1, 4], [0, 2, 5], [0, 3, 6],
[1, 2, 6], [2, 3, 4], [4, 5, 6], [1, 3, 5]]
correctable_4_events = [[0, 1, 2, 3], [1, 2, 4, 5],
[2, 3, 5, 6], [0, 3, 4, 5],
[0, 1, 5, 6], [1, 3, 4, 6],
[0, 2, 4, 6]
]
guessed_loss = [(loss + qnd_err) % 2
for loss, qnd_err in zip(random_losses, qnd_errors)]
num_fresh_qubits = sum(guessed_loss)
position_loss = np.where(random_losses)[0].tolist()
position_qnd = np.where(qnd_errors)[0].tolist()
# find if a qnd_error hits a loss
qnderror_hit_loss = any([(_ in position_loss) for _ in position_qnd])
if qnderror_hit_loss:
non_correctable = True
correctable = False
else:
if num_fresh_qubits in (0, 1, 2):
non_correctable = False
correctable = True
elif num_fresh_qubits == 3:
if sorted(position_loss + position_qnd) \
in non_correctable_3_events:
non_correctable = True
correctable = False
else:
non_correctable = False
correctable = True
elif num_fresh_qubits == 4:
if sorted(position_loss + position_qnd) in correctable_4_events:
non_correctable = False
correctable = True
else:
non_correctable = True
correctable = False
elif num_fresh_qubits in (5, 6, 7):
non_correctable = True
correctable = False
return [correctable, non_correctable]
def check_correctable_state(random_losses, qnd_errors):
"""
Check whether a loss + qnd error event is correctable.
The cases that are correctable with no doubts are the ones where
a. no loss happens and 0,1,2 qnd error happen
or
b. no qnd errors happens and 0,1,2 losses happen
or
c. no qnd errors happens on the losses and the number
of replaced qubits is 0,1,2
The cases that are NOT correctable with no doubts are the ones where
d. one qnd error happens on the position of a loss
or
e. five, six or seven fresh qubits are introduced for replacing
the actual losses or the guessed ones
In all the other cases, one should check
"""
guessed_loss = [(loss + qnd_err) % 2 for
loss, qnd_err in zip(random_losses, qnd_errors)]
num_fresh_qubits = sum(guessed_loss)
position_loss = np.where(random_losses)[0].tolist()
position_qnd = np.where(qnd_errors)[0].tolist()
# find if a qnd_error hits a loss
qnderror_hit_loss = any([(_ in position_loss) for _ in position_qnd])
if qnderror_hit_loss:
non_correctable = True
correctable = False
to_check = False
else:
if num_fresh_qubits in (0, 1, 2):
non_correctable = False
correctable = True
to_check = False
elif num_fresh_qubits in (3, 4):
non_correctable = False
correctable = False
to_check = True
elif num_fresh_qubits in (5, 6, 7):
non_correctable = True
correctable = False
to_check = False
return [correctable, non_correctable, to_check]
def get_ancilla_outcomes_false_negatives(L):
all_binary_ordered_confs = []
for num_loss, loss_confs in binary_configurations().configurations.items():
all_binary_ordered_confs.extend(loss_confs)
all_configurations = []
index_outcomes_ancilla = 0
for outcomes_ancilla in all_binary_ordered_confs:
false_negative_confs = []
for false_neg_events_all in all_binary_ordered_confs:
# print("outcomes_ancilla", outcomes_ancilla, false_neg_events_all)
false_neg_events = [0] * L
for _ in range(L):
if outcomes_ancilla[_] == 0:
false_neg_events[_] = false_neg_events_all[_]
else:
false_neg_events[_] = 0
losses = np.where(outcomes_ancilla)[0].tolist()
false_negative_qubits = np.where(false_neg_events)[0].tolist()
kept_qubits = [_ for _ in range(L)
if (_ not in false_negative_qubits)
and (_ not in losses)]
if false_neg_events not in false_negative_confs \
and \
len(kept_qubits):
false_negative_confs.append(false_neg_events)
all_configurations.append([outcomes_ancilla, false_negative_confs])
index_outcomes_ancilla += 1
return all_configurations
def get_ancilla_outcomes_false_positives(L):
all_binary_ordered_confs = []
for num_loss, loss_confs in binary_configurations().configurations.items():
all_binary_ordered_confs.extend(loss_confs)
all_configurations = []
index_outcomes_ancilla = 0
for outcomes_ancilla in all_binary_ordered_confs:
false_positive_confs = []
for false_pos_events_all in all_binary_ordered_confs:
false_pos_events = [0] * L
for _ in range(L):
if outcomes_ancilla[_] == 1:
false_pos_events[_] = false_pos_events_all[_]
else:
false_pos_events[_] = 0
losses = np.where(outcomes_ancilla)[0].tolist()
false_positive_qubits = np.where(false_pos_events)[0].tolist()
kept_qubits = [_ for _ in range(L)
if (_ not in false_positive_qubits)
and (_ not in losses)]
if false_pos_events not in false_positive_confs \
and sum(false_pos_events) < 7:
false_positive_confs.append(false_pos_events)
all_configurations.append([outcomes_ancilla, false_positive_confs])
index_outcomes_ancilla += 1
return all_configurations
def create_random_event(prob_loss, basic_event_probs):
id_event = []
event = []
for j_qubit in range(7):
ancilla = np.random.binomial(n=1, p=prob_loss, size=1)
ancilla_0 = np.random.multinomial(n=1, size=1,
pvals=[basic_event_probs['0'],
basic_event_probs['1'],
basic_event_probs['2'],
basic_event_probs['3']]
)[0]
ancilla_1 = np.random.multinomial(n=1, size=1,
pvals=[basic_event_probs['4'],
basic_event_probs['5']]
)[0]
if ancilla:
event.append([ancilla[0], np.where(ancilla_1)[0][0]])
id_event.append(str(4 + np.where(ancilla_1)[0][0]))
else:
event.append([ancilla[0], np.where(ancilla_0)[0][0]])
id_event.append(str(np.where(ancilla_0)[0][0]))
event_str = "".join(id_event)
return event, event_str
if __name__ == "__main__":
cc = 0
a = get_ancilla_outcomes_false_negatives(7)
for ifd, [x, y] in enumerate(a):
print(ifd, x, "||")
for el in y:
print(el)
cc += len(y)
print(cc)
<file_sep>/utils/p_operators_qutrit.py
import qutip as qu
import numpy as np
from numpy import linalg as LA
from itertools import product
import matplotlib.pyplot as plt
_lambdas_GM = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
[[0, 1, 0], [1, 0, 0], [0, 0, 0]],
[[0, -1j, 0], [1j, 0, 0], [0, 0, 0]],
[[1, 0, 0], [0, -1, 0], [0, 0, 0]],
[[0, 0, 1], [0, 0, 0], [1, 0, 0]],
[[0, 0, -1j], [0, 0, 0], [1j, 0, 0]],
[[0, 0, 0], [0, 0, 1], [0, 1, 0]],
[[0, 0, 0], [0, 0, -1j], [0, 1j, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, -2]]
]
_sigmas_P = [[[1, 0], [0, 1]],
[[0, 1], [1, 0]],
[[0, -1j], [1j, 0]],
[[1, 0], [0, -1]]
]
# ancilla always the last qubit
L = 7
# Hilbert space dimension data qubit / ancilla
dimQ = 3
dimA = 2
Id = qu.tensor([qu.qeye(3)] * L + [qu.qeye(2)])
x_qutrit = qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
y_qutrit = qu.Qobj([[0, -1j, 0], [1j, 0, 0], [0, 0, 0]])
z_qutrit = qu.Qobj([[1, 0, 0], [0, -1, 0], [0, 0, 0]])
temp = [[qu.qeye(3)] * j +
[x_qutrit] +
[qu.qeye(3)] * (L - j - 1) +
[qu.qeye(2)]
for j in range(L)
]
X = [qu.tensor(temp[j]) for j in range(L)]
temp = [[qu.qeye(3)] * j +
[y_qutrit] +
[qu.qeye(3)] * (L - j - 1) +
[qu.qeye(2)]
for j in range(L)
]
Y = [qu.tensor(temp[j]) for j in range(L)]
temp = [[qu.qeye(3)] * j +
[z_qutrit] +
[qu.qeye(3)] * (L - j - 1) +
[qu.qeye(2)]
for j in range(L)
]
Z = [qu.tensor(temp[j]) for j in range(L)]
# ancilla operators
temp = [qu.qeye(3)] * L + [qu.sigmax()]
Xa = qu.tensor(temp)
temp = [qu.qeye(3)] * L + [qu.sigmaz()]
Za = qu.tensor(temp)
Pp_ancilla = (Id + Za) / 2
Pm_ancilla = (Id - Za) / 2
if L == 7:
stab_qubits = [[0, 1, 2, 3],
[1, 2, 4, 5],
[2, 3, 5, 6]
]
Sx = [X[j1] * X[j2] * X[j3] * X[j4]
for j1, j2, j3, j4 in stab_qubits
]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4]
for j1, j2, j3, j4 in stab_qubits
]
ZL = Z[0] * Z[1] * Z[2] * Z[3] * Z[4] * Z[5] * Z[6]
XL = X[0] * X[1] * X[2] * X[3] * X[4] * X[5] * X[6]
Px = [(Id + el) / 2 for el in Sx]
Pz = [(Id + el) / 2 for el in Sz]
Pmx = [(Id - el) / 2 for el in Sx]
Pmz = [(Id - el) / 2 for el in Sz]
vacuum = qu.tensor([qu.basis(3, 0)] * L + [qu.basis(2, 0)])
# logical states
ZeroL = (Px[0] * Px[1] * Px[2] * vacuum).unit()
OneL = (XL * ZeroL).unit()
LogicalStates = [ZeroL,
OneL,
(ZeroL + OneL) / np.sqrt(2),
(ZeroL - OneL) / np.sqrt(2),
(ZeroL + 1j * OneL) / np.sqrt(2),
(ZeroL - 1j * OneL) / np.sqrt(2)
]
def proj(ket, bra, dimH = 2):
if isinstance(ket, str):
states_ket = [int(_) for _ in ket]
ket_s = qu.basis([dimH] * len(states_ket), states_ket)
elif isinstance(ket, int):
states_ket = ket
ket_s = qu.basis(dimH, states_ket)
if isinstance(bra, str):
states_bra = [int(_) for _ in bra]
bra_s = qu.basis([dimH] * len(states_bra), states_bra).dag()
elif isinstance(bra, int):
states_bra = bra
bra_s = qu.basis(dimH, states_bra).dag()
return ket_s * bra_s
def Rloss(initial_state, phi, qu_data):
if initial_state.type == "ket":
initial_state = initial_state * initial_state.dag()
dimHq = 3 # Hilbert space data qutrit
dimHa = 2 # Hilbert space ancilla qubit
rloss = (proj(1, 1, dimHq) +
np.cos(phi/2) * (proj(0, 0, dimHq) +
proj(2 ,2, dimHq)) +
np.sin(phi/2) * (proj(0, 2, dimHq) - proj(2, 0, dimHq))
)
rot_temp = [qu.qeye(dimHq)] * qu_data + [rloss] + [qu.qeye(dimHq)] * (L - qu_data - 1) + [qu.qeye(dimHa)]
rot = qu.tensor(rot_temp)
return rot * initial_state * rot.dag()
def Rloss_1(initial_state, phi, qu_data):
if initial_state.type == "ket":
initial_state = initial_state * initial_state.dag()
dimHq = 3 # Hilbert space data qutrit
dimHa = 2 # Hilbert space ancilla qubit
rloss = (proj(0, 0, dimHq) + np.cos(phi/2) * (proj(1, 1, dimHq) + proj(2 ,2, dimHq))
+ np.sin(phi/2) * (proj(1, 2, dimHq) - proj(2, 1, dimHq)))
rot_temp = [qu.qeye(dimHq)] * qu_data + [rloss] + [qu.qeye(dimHq)] * (L - qu_data - 1) + [qu.qeye(dimHa)]
rot = qu.tensor(rot_temp)
return rot * initial_state * rot.dag()
def Rloss_all_from_0(phi):
# return a list with 7 Rloss gates one for each data qutrit
dimHq = 3 # Hilbert space data qutrit
dimHa = 2 # Hilbert space ancilla qubit
rloss = (proj(1, 1, dimHq) + np.cos(phi/2) * (proj(0, 0, dimHq) + proj(2 ,2, dimHq))
+ np.sin(phi/2) * (proj(0, 2, dimHq) - proj(2, 0, dimHq)) )
temp = [[qu.qeye(dimHq)] * j + [rloss] + [qu.qeye(dimHq)] * (L - j - 1) + [qu.qeye(dimHa)] for j in range(L)]
R_loss_list = [qu.tensor(temp[j]) for j in range(L)]
return R_loss_list
def Rloss_all_from_1(phi):
# return a list with 7 Rloss gates one for each data qutrit
dimHq = 3 # Hilbert space data qutrit
dimHa = 2 # Hilbert space ancilla qubit
rloss = (proj(0, 0, dimHq) + np.cos(phi/2) * (proj(1, 1, dimHq) + proj(2 ,2, dimHq))
+ np.sin(phi/2) * (proj(1, 2, dimHq) - proj(2, 1, dimHq)) )
temp = [[qu.qeye(dimHq)] * j + [rloss] + [qu.qeye(dimHq)] * (L - j - 1) + [qu.qeye(dimHa)] for j in range(L)]
R_loss_list = [qu.tensor(temp[j]) for j in range(L)]
return R_loss_list
def Rloss_all(phi):
# return a list with 7 Rloss gates one for each data qutrit
dimHq = 3 # Hilbert space data qutrit
dimHa = 2 # Hilbert space ancilla qubit
rloss = (proj(1, 1, dimHq) + np.cos(phi/2) * (proj(0, 0, dimHq) + proj(2 ,2, dimHq))
+ np.sin(phi/2) * (proj(0, 2, dimHq) - proj(2, 0, dimHq)) )
temp = [[qu.qeye(dimHq)] * j + [rloss] + [qu.qeye(dimHq)] * (L - j - 1) + [qu.qeye(dimHa)] for j in range(L)]
R_loss_list = [qu.tensor(temp[j]) for j in range(L)]
return R_loss_list
def normalize_operators(matrices_list):
return [qu.Qobj(np.array(el) / LA.norm(el)) for el in matrices_list]
def give_transformation_matrix():
basis_elements_list = []
# the order of these for loops is important to define the T_matrix because the convention is
# sigma_j x lambda_k in the choi matrix we get from experiments
for j in range(len(_sigmas_P)):
for i in range(len(_lambdas_GM)):
_lambda = _lambdas_GM[i]
_sigma = _sigmas_P[j]
# we use the column vectorization convention. that's why we transpose the basis_element
basis_operator = (qu.tensor(qu.Qobj(_sigma), qu.Qobj(_lambda))).full()
basis_element = np.transpose(basis_operator)
rows, cols = basis_element.shape
dimH = rows * cols
vector_basis = basis_element.reshape(1 , dimH)[0]
# the paper 1111.6950 defines the change of basis matrix not in the standard way:
# In linear algebra, the standard definition for the matrix P(e->v) for going to base e to basis v is
# P(e->v)[x]_v = [x]_e where [x]_v is a vector x written in the basis v
# and the matrix P(e->v) is given by putting the components of the basis v written in the basis e by columns
# By looking at appendix B formula 2.2 they define T(sigma -> w) as
# T(sigma -> w) |A>>_sigma = |A>>_w.
# so we need to put the compoments of the basis w written in the basis sigma by row
normalized_vector = np.conjugate(vector_basis / LA.norm(vector_basis))
basis_elements_list.append(normalized_vector.tolist())
T_matrix = np.array(basis_elements_list)
return T_matrix
def orthonormal_basis_operator(T_matrix):
on_basis = []
for el in T_matrix:
dimH = int(np.sqrt(len(el)))
# we need to transpose as we were working with col-vec convention
on_basis.append(el.reshape((dimH, dimH)).T)
return on_basis
def get_chi_from_choi(choi, T_matrix):
return np.dot(T_matrix, np.dot(choi, T_matrix.conj().T))
def apply_qnd_process_unit(chi_matrix, state_total, qu_data, chi_threshold):
if state_total.type == "ket":
state_total = state_total * state_total.dag()
on_basis_lambda = normalize_operators(_lambdas_GM)
on_basis_Pauli = normalize_operators(_sigmas_P)
rows, cols = chi_matrix.shape
final_state_list = []
for alpha, beta in product(range(rows), range(cols)):
if chi_matrix[alpha, beta]:
a_GM = alpha % 9
a_Pauli = (alpha - a_GM) // 9
OP_temp = [qu.qeye(3)] * qu_data + [on_basis_lambda[a_GM]] + [qu.qeye(3)] * (L - qu_data - 1) + [on_basis_Pauli[a_Pauli]]
OP_1 = qu.tensor(OP_temp)
b_GM = beta % 9
b_Pauli = (beta - b_GM) // 9
OP_temp = [qu.qeye(3)] * qu_data + [on_basis_lambda[b_GM]] + [qu.qeye(3)] * (L - qu_data - 1) + [on_basis_Pauli[b_Pauli]]
OP_2 = qu.tensor(OP_temp)
#partial_state = chi_matrix[alpha, beta] * OP_1 * state_total * OP_2.dag()
#final_state_list.append(partial_state)
if alpha > beta:
action = chi_matrix[alpha, beta] * OP_1 * state_total * OP_2.dag()
final_state_list.append(action + action.dag())
elif alpha == beta:
final_state_list.append(chi_matrix[alpha, beta] * OP_1 * state_total * OP_2.dag())
final_state = sum(final_state_list)
return final_state
def find_false_positive():
phi_tilde = 0
rotation_ops_0 = Rloss_all_from_0(phi_tilde * np.pi)
rotation_ops_1 = Rloss_all_from_1(phi_tilde * np.pi)
on_basis_lambda = normalize_operators(_lambdas_GM)
on_basis_Pauli = normalize_operators(_sigmas_P)
choi_ideal = np.loadtxt("choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("qubitqutrit_choi_noloss.csv", dtype=complex, delimiter=',')
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(6 * choi_experiment, T_matrix) #.round(15)
a = 1/np.sqrt(2)
b = 1/np.sqrt(2)
a = 1
b = 0
c = 0
if 1:
# for a, b in [[1,0], [0,1], [1/np.sqrt(2), 1/np.sqrt(2)]]:
state_qutrit = (a * qu.basis(3,0) + b * qu.basis(3,1) + c * qu.basis(3,2)).unit()
state_0 = (qu.tensor([state_qutrit, qu.basis(2,0)])).unit()
rho_L = state_0 * state_0.dag()
rho_L = rotation_ops_0[0] * rho_L * rotation_ops_0[0].dag()
print(rho_L)
exit()
rho_L = apply_qnd_process_unit(chi_matrix, rho_L, 0, 0)
print(f"prob ancilla 0 {(rho_L * Pp_ancilla).tr()}")
print(f"prob ancilla 1 {(rho_L * Pm_ancilla).tr()}")
p_10 = (rho_L * Pp_ancilla).tr()
p_11 = (rho_L * Pm_ancilla).tr()
print("--------")
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / p_10
print(rho_L)
w_0 = rho_L.ptrace([0])
print(w_0)
# rho_L = apply_qnd_process_unit(chi_matrix, rho_L, 0, 0)
# print(f"prob ancilla 0 {(rho_L * Pm_ancilla).tr()}")
# print(f"prob ancilla 1 {(rho_L * Pp_ancilla).tr()}")
# p_20 = (rho_L * Pp_ancilla).tr()
# p_21 = (rho_L * Pm_ancilla).tr()
# print(p_10*p_20)
# print(p_11*p_21)
# print()
# print(p_10*p_20 + p_11*p_21)
exit()
prob_outcome_1 = (rho_L * Pp_ancilla).tr()
print(prob_outcome_1)
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / abs(prob_outcome_1)
print(rho_L)
print("rotation from 1")
rho_L = rotation_ops_1[0] * rho_L * rotation_ops_1[0].dag()
rho_L = apply_qnd_process_unit(chi_matrix, rho_L, 0, 0)
print("apply second qnd")
print(rho_L)
prob_outcome_2 = (rho_L * Pp_ancilla).tr()
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / abs(prob_outcome_2)
print("project on 0 second time")
print(Pp_ancilla)
print(rho_L)
print(state_0 * state_0.dag())
if __name__ == "__main__":
np.set_printoptions(precision = 5, suppress = True, linewidth=100000)
# find_false_positive()
# exit()
phi_tilde = 1 / 2
rotation_ops_0 = Rloss_all_from_0(phi_tilde * np.pi)
rotation_ops_1 = Rloss_all_from_1(phi_tilde * np.pi)
on_basis_lambda = normalize_operators(_lambdas_GM)
on_basis_Pauli = normalize_operators(_sigmas_P)
choi_ideal = np.loadtxt("choiFinal_ideal.dat")
choi_experiment = 6* np.real(np.genfromtxt("qubitqutrit_choi_noloss.csv", dtype=complex, delimiter=','))
print(choi_experiment.round(3))
exit()
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi_experiment.round(4), T_matrix).round(15)
a = 1/np.sqrt(2)
b = 1/np.sqrt(2)
# a = 1
# b = 0
# state_qutrit = (a * qu.basis(3,0) + b * qu.basis(3,1)).unit()
# state_0 = (qu.tensor([state_qutrit, qu.basis(2,0)])).unit()
# state_0 = (qu.tensor([ZeroL, qu.basis(2,0)])).unit()
state_0 = OneL
rho_L = state_0 * state_0.dag()
print(rho_L)
rho_L = rotation_ops_0[0] * rho_L * rotation_ops_0[0].dag()
rho_L = apply_qnd_process_unit(chi_matrix, rho_L, 0, 0)
print("----")
print(rho_L)
print("----")
prob_outcome_1 = (rho_L * Pp_ancilla).tr()
print(prob_outcome_1)
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / abs(prob_outcome_1)
print(rho_L)
print("rotation from 1")
rho_L = rotation_ops_1[0] * rho_L * rotation_ops_1[0].dag()
rho_L = apply_qnd_process_unit(chi_matrix, rho_L, 0, 0)
print("apply second qnd")
print(rho_L)
prob_outcome_2 = (rho_L * Pp_ancilla).tr()
rho_L = Pp_ancilla * rho_L * Pp_ancilla.dag() / abs(prob_outcome_2)
print("project on 0 second time")
print(rho_L)
print(rho_L == OneL * OneL.dag())
<file_sep>/utils/qnd_error_gen.py
import numpy as np
from itertools import product
def generate_qnd_error_fpn(random_losses, fp_prob, fn_prob, num_qubits = 7):
"""
generate a pattern for qnd error detection with false positive and false negative
"""
false_positive = np.random.binomial(1, fp_prob, num_qubits)
false_negative = np.random.binomial(1, fn_prob, num_qubits)
qnd_error = [0] * num_qubits
for j,x in enumerate(random_losses):
if x == 0:
if false_positive[j] == 1:
#make a qnd error by detecting a loss even if it has not happened (false positive)
qnd_error[j] = 1
elif x == 1:
if false_negative[j] == 1:
#make a qnd error by discarding this loss even if it has happened (false negative)
qnd_error[j] = 1
return qnd_error
def pick_qnd_error(p_qnd):
"""
generate a depolarizing channel with probability p_qnd
returns a string with "Eq Ea" with a Pauli operator on the data qubit and the ancilla
representing the error
"""
random_toss_qnd = np.random.binomial(1, p_qnd, 1)
if not (sum(random_toss_qnd)):
#no qnd_error
return "II"
else:
depol_errors = [e1 + e2 for e1, e2 in product("IXYZ", "IXYZ")]
depol_errors.remove("II")
rng = np.random.default_rng()
return rng.choice(depol_errors)<file_sep>/utils/BasisToSpin1.py
import numpy as np
from qutip import *
import itertools
def BasisToSpin1(process):
pauli_ops = [qeye(2).data.toarray(), # Qubit basis: Commonly known Pauli Basis
sigmax().data.toarray(),
sigmay().data.toarray(),
sigmaz().data.toarray()]
gell_mann_ops = [qeye(3).data.toarray(), # Qutrit basis: https://en.wikipedia.org/wiki/Gell-Mann_matrices
get_qudit_from_qubit_operation(sigmax(), 3, (0, 1), True).data.toarray(),
get_qudit_from_qubit_operation(sigmay(), 3, (0, 1), True).data.toarray(),
get_qudit_from_qubit_operation(sigmaz(), 3, (0, 1), True).data.toarray(),
get_qudit_from_qubit_operation(sigmax(), 3, (0, 2), True).data.toarray(),
get_qudit_from_qubit_operation(sigmay(), 3, (0, 2), True).data.toarray(),
get_qudit_from_qubit_operation(sigmax(), 3, (1, 2), True).data.toarray(),
get_qudit_from_qubit_operation(sigmay(), 3, (1, 2), True).data.toarray(),
(get_qudit_from_qubit_operation(sigmaz(), 3, (0, 1), True).data.toarray()+
2*get_qudit_from_qubit_operation(sigmaz(), 3, (1, 2), True).data.toarray()) / np.sqrt(3)]
TOp = []
for i in pauli_ops:
for j in gell_mann_ops:
TOp.append(np.kron(i, j))
dim = 2*3 # Dimension for qubit-qutrit
print(TOp)
exit()
TOp = np.reshape(TOp, (dim**2, dim**2))
TOp = np.conjugate(TOp)
return dim**(-1)*(np.dot(TOp, np.dot(process, np.conjugate(np.transpose(TOp)))))
def get_qudit_from_qubit_operation(operation, dim = 4, transition = (0,2), is_hamiltonian = True):
"""
Return a higher dimensional operation for a given qubit operation.
Parameters
----------
dim : int
Dimension of the returned operation (dim=2 is qubit).
operation : Qobj
Qubit operation that is expanded to higher dimension.
transition : tuple
Tuple of states that defines on which transition of the qudit the operation acts.
is_hamiltonian : bool
Indicates if the input operation is a Hamiltonian (gets exponentiated later) or or time evolution operator.
Returns
-------
qudit_operation : Qobj
Higher dimensional operation object.
"""
if is_hamiltonian:
qudit_operation = np.zeros((dim, dim), dtype=complex)
else:
qudit_operation = np.identity(dim, dtype=complex)
mask = np.zeros((dim, dim))
mask[tuple(np.array(list(itertools.product(transition, repeat=2))).T)] = 1
np.place(qudit_operation, mask, operation)
qudit_operation = Qobj(qudit_operation)
return qudit_operation
A = np.loadtxt("choiFinal_ideal.dat")/6
for _ in BasisToSpin1(A):
print(_)
print( get_qudit_from_qubit_operation(sigmay(), 3, (1, 2), True).data.toarray(),)<file_sep>/utils/parameters.py
import argparse
# python process_matrix_simulation_all.py --phi_tilde --epsilon_choi
def parse_command_line():
parser = argparse.ArgumentParser(description="Simulate qubit losses"
"with QND measurement qubit+7qutrit system")
parser.add_argument('--phi_tilde',
type=float,
default=0.00,
help="Rotation angle"
)
parser.add_argument('--epsilon_choi',
type=float,
default=0.0,
help="epsilon_choi"
)
parser.add_argument('--logical_state',
type=int,
default=0,
help="logical state corresponding"
"to: 0, 1, +, -, +i, -i"
)
parser.add_argument('--chi_threshold',
type=float,
default=0.0,
help="threshold for discarding Kraus"
"operators in the chi matrix"
)
parser.add_argument('--dir_name',
type=str,
default="./",
help="directory for saving data"
)
parser.add_argument('--p_overrot_2',
type=float,
default=0.136,
help="over rotation MS gate"
)
parser.add_argument('--p_overrot_1',
type=float,
default=0.010,
help="over rotation single-qubit gates"
)
parser.add_argument('--num_trials',
type=int,
default=4000,
help="Number of Monte Carlo samples"
)
parser.add_argument('--verbose',
action="store_true",
help="verbose"
)
args = parser.parse_args()
return parser.parse_args()<file_sep>/utils/corrections.py
import numpy as np
from utils.p_operators import *
def check_correctable_state_analytics(random_losses, qnd_errors):
non_correctable_3_events = [[0, 1, 4], [0, 2, 5], [0, 3, 6], [1, 2, 6], [2, 3, 4], [4, 5, 6], [1, 3, 5]]
correctable_4_events = [[0, 1, 2, 3], [1, 2, 4, 5], [2, 3, 5, 6], [0, 3, 4, 5], [0, 1, 5, 6], [1, 3, 4, 6], [0, 2, 4, 6]]
num_loss = sum(random_losses)
num_qnd = sum(qnd_errors)
guessed_loss = [(loss + qnd_err) % 2 for loss, qnd_err in zip(random_losses, qnd_errors)]
num_fresh_qubits = sum(guessed_loss)
position_loss = np.where(random_losses)[0].tolist()
position_qnd = np.where(qnd_errors)[0].tolist()
#find if a qnd_error hits a loss
qnderror_hit_loss = any([(_ in position_loss) for _ in position_qnd])
if qnderror_hit_loss:
non_correctable = True
correctable = False
else:
if num_fresh_qubits in (0,1,2):
non_correctable = False
correctable = True
elif num_fresh_qubits == 3:
if sorted(position_loss + position_qnd) in non_correctable_3_events:
non_correctable = True
correctable = False
else:
non_correctable = False
correctable = True
elif num_fresh_qubits == 4:
if sorted(position_loss + position_qnd) in correctable_4_events:
non_correctable = False
correctable = True
else:
non_correctable = True
correctable = False
elif num_fresh_qubits in (5,6,7):
non_correctable = True
correctable = False
return [correctable, non_correctable]
def check_stabilizers_measurement(random_losses, qnd_errors, stab_errors_binary):
[correctable_0, non_correctable_0] = check_correctable_state_analytics(random_losses, qnd_errors)
if non_correctable_0:
return [correctable_0, non_correctable_0]
else:
#Stabilizer that are affected by a measurement error
faulty_stab_qubits = [el for j,el in enumerate(stab_qubits) if stab_errors_binary[j]]
position_loss = np.where(random_losses)[0].tolist()
position_qnd = np.where(qnd_errors)[0].tolist()
guessed_loss = [(loss + qnd_err) % 2 for loss, qnd_err in zip(random_losses, qnd_errors)]
position_guessed_loss = np.where(guessed_loss)[0].tolist()
correctable = not (any([any([(loss in stab) for loss in position_guessed_loss]) for stab in faulty_stab_qubits]))
return [correctable, not correctable]
def check_correctable_state(random_losses, qnd_errors):
"""
Check whether a loss + qnd error event is correctable.
The cases that are correctable with no doubts are the ones where
a. no loss happens and 0,1,2 qnd error happen
or
b. no qnd errors happens and 0,1,2 losses happen
or
c. no qnd errors happens on the losses and the number of replaced qubits is 0,1,2
The cases that are NOT correctable with no doubts are the ones where
d. one qnd error happens on the position of a loss
or
e. five, six or seven fresh qubits are introduced for replacing the actual losses or the guessed ones
In all the other cases, one should check
"""
num_loss = sum(random_losses)
num_qnd = sum(qnd_errors)
guessed_loss = [(loss + qnd_err) % 2 for loss, qnd_err in zip(random_losses, qnd_errors)]
num_fresh_qubits = sum(guessed_loss)
position_loss = np.where(random_losses)[0].tolist()
position_qnd = np.where(qnd_errors)[0].tolist()
#find if a qnd_error hits a loss
qnderror_hit_loss = any([(_ in position_loss) for _ in position_qnd])
if qnderror_hit_loss:
non_correctable = True
correctable = False
to_check = False
else:
if num_fresh_qubits in (0,1,2):
non_correctable = False
correctable = True
to_check = False
elif num_fresh_qubits in (3,4):
non_correctable = False
correctable = False
to_check = True
elif num_fresh_qubits in (5,6,7):
non_correctable = True
correctable = False
to_check = False
return [correctable, non_correctable, to_check]<file_sep>/utils/flip_qutip.py
import numpy as np
from qutip import *
from numpy import linalg as LA
def bit_flip_channel(p):
X = sigmax()
I = qeye(2)
return (1-p) * sprepost(I, I) + p * sprepost(X, X)
print(to_choi(bit_flip_channel(0.3)))
chi_matrix = to_chi(to_choi(bit_flip_channel(0.3)))
print(chi_matrix.shape)
<file_sep>/utils/overrotation_channel.py
import numpy as np
import qutip as qu
from itertools import product
L = 7
def DepolQubit(i, p): # Qubit Kraus-operators for depolarizing channel
dimHq = 3
index = [
np.sqrt(1 - 3 * p / 4) * qu.qeye(2),
np.sqrt(p / 4) * qu.sigmax(),
np.sqrt(p / 4) * qu.sigmay(),
np.sqrt(p / 4) * qu.sigmaz()
]
return qu.tensor([qu.qeye(dimHq)] * 7 + [index[i]])
def DepolQutrit(qutrit_n, i, p):
# Qutrit Kraus-operators for depolarizing channel
dimHq = 3
dimHa = 2
dimTot = [[3], [3]]
index = [
np.sqrt(3 - 8 * p / 3) / np.sqrt(3) *
qu.Qobj([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dims=dimTot),
np.sqrt(p / 3) / np.sqrt(2) *
qu.Qobj([[1, 0, 0], [0, 0, 0], [0, 0, -1]], dims=dimTot),
np.sqrt(p / 3) *
qu.Qobj([[0, 0, 0], [0, 0, 1], [0, 0, 0]], dims=dimTot),
np.sqrt(p / 3) *
qu.Qobj([[0, 0, 1], [0, 0, 0], [0, 0, 0]], dims=dimTot),
np.sqrt(p / 3) *
qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 1, 0]], dims=dimTot),
np.sqrt(p / 3) / np.sqrt(6) *
qu.Qobj([[1, 0, 0], [0, -2, 0], [0, 0, 1]], dims=dimTot),
np.sqrt(p / 3) *
qu.Qobj([[0, 1, 0], [0, 0, 0], [0, 0, 0]], dims=dimTot),
np.sqrt(p / 3) *
qu.Qobj([[0, 0, 0], [0, 0, 0], [1, 0, 0]], dims=dimTot),
np.sqrt(p / 3) *
qu.Qobj([[0, 0, 0], [1, 0, 0], [0, 0, 0]], dims=dimTot)
]
temp = ([qu.qeye(dimHq)] * qutrit_n +
[index[i]] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[qu.qeye(dimHa)]
)
return qu.tensor(temp)
def UnitaryQubitQutritQNDDepol(p, state_rho, qutrit_n):
# depolarizing channel on ancilla qubit & system qutrit
Depol = 0
for i, j in product(range(4), range(9)):
Depol = (Depol +
DepolQubit(i, p) *
DepolQutrit(qutrit_n, j, p) *
state_rho *
DepolQutrit(qutrit_n, j, p).dag() *
DepolQubit(i, p).dag()
)
return Depol / np.trace(Depol.data.toarray())
def CorrelatedOverRotQubit(qutrit_n, alpha):
dimHq = 3
dimHa = 2
X_qutrit = qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
ket22bra = qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
Id = [qu.qeye(dimHq)] * L + [qu.qeye(dimHa)]
XX_operators_1 = ([qu.qeye(dimHq)] * qutrit_n +
[X_qutrit] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[qu.sigmax()]
)
XX_operators_2 = ([qu.qeye(dimHq)] * qutrit_n +
[ket22bra] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[qu.qeye(dimHa)]
)
corr = (np.cos(alpha / 2) * qu.tensor(Id) +
1j * np.sin(alpha / 2) * (qu.tensor(XX_operators_1) +
qu.tensor(XX_operators_2))
)
return corr
def CorrelatedOverRotQubitAll(alpha):
return [CorrelatedOverRotQubit(qutrit_n, alpha) for qutrit_n in range(L)]
def SingleOverRotQubit(qutrit_n, theta):
dimHq = 3
dimHa = 2
X_qutrit = qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
ket22bra = qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
R1q = (np.cos(theta / 2) * (qu.qeye(dimHq) - ket22bra) -
1j * np.sin(theta / 2) * X_qutrit +
ket22bra
)
R1a = (np.cos(theta / 2) * qu.qeye(dimHa) -
1j * np.sin(theta / 2) * qu.sigmax()
)
OverRotSingle = ([qu.qeye(dimHq)] * qutrit_n +
[R1q] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[R1a]
)
corr = qu.tensor(OverRotSingle)
return corr
def SingleOverRotQubitAll(theta):
return [SingleOverRotQubit(qutrit_n, theta) for qutrit_n in range(L)]
def SingleOverRotQutrit(qutrit_n, theta):
dimHq = 3
dimHa = 2
X_qutrit = qu.Qobj([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
ket22bra = qu.Qobj([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
R1q = (np.cos(theta / 2) * (qu.qeye(dimHq) - ket22bra) -
1j * np.sin(theta / 2) * X_qutrit +
ket22bra
)
R1a = qu.qeye(dimHa)
OverRotSingle = ([qu.qeye(dimHq)] * qutrit_n +
[R1q] +
[qu.qeye(dimHq)] * (L - qutrit_n - 1) +
[R1a]
)
corr = qu.tensor(OverRotSingle)
return corr
def SingleOverRotQutritAll(theta):
return [SingleOverRotQutrit(qutrit_n, theta) for qutrit_n in range(L)]
<file_sep>/old_py/incoherent_error_model_wrong_case2b.py
#
# Case 2: Incoherent error model for overrotation
# with false negative case 2b (in notes_qi_qec) wrong.
# Keep for testing role of false negative
#
import qutip as qu
import numpy as np
import os
from utils.p_operators_qutrit import *
from utils.binary_conf import create_random_event
import datetime
import argparse
np.set_printoptions(precision=4, suppress=True)
# python process_matrix_simulation_all.py --phi_tilde --epsilon_choi
parser = argparse.ArgumentParser(description="Simulate qubit losses"
"with QND measurement qubit+7qutrit system")
parser.add_argument('--phi_tilde',
type=float,
default=0.05,
help="Rotation angle"
)
parser.add_argument('--epsilon_choi',
type=float,
default=0.0,
help="epsilon_choi"
)
parser.add_argument('--logical_state',
type=int,
default=0,
help="logical state corresponding"
"to: 0, 1, +, -, +i, -i"
)
parser.add_argument('--chi_threshold',
type=float,
default=0.0,
help="threshold for discarding Kraus"
"operators in the chi matrix"
)
parser.add_argument('--dir_name',
type=str,
default="./",
help="directory for saving data"
)
parser.add_argument('--p_overrot_2',
type=float,
default=0.136,
help="over rotation MS gate"
)
parser.add_argument('--p_overrot_1',
type=float,
default=0.010,
help="over rotation single-qubit gates"
)
parser.add_argument('--num_trials',
type=int,
default=5000,
help="Number of Monte Carlo samples"
)
args = parser.parse_args()
phi_tilde = args.phi_tilde
phi = phi_tilde * np.pi
epsilon_choi = args.epsilon_choi
jLog = args.logical_state
chi_threshold = args.chi_threshold
eta = args.p_overrot_2 * np.pi
eps = args.p_overrot_1 * np.pi
folder_name = args.dir_name
num_trials = args.num_trials
choi_ideal = np.loadtxt("choi_op/choiFinal_ideal.dat")
choi_experiment = np.genfromtxt("choi_op/qubitqutrit_choi_noloss.csv",
dtype=complex,
delimiter=','
)
if not os.path.exists(folder_name):
os.makedirs(folder_name)
choi = choi_ideal
T_matrix = give_transformation_matrix()
chi_matrix = get_chi_from_choi(choi, T_matrix)
final_p_loss = []
rotation_ops = Rloss_all(phi_tilde * np.pi)
LogicalStates_str = ["0", "1", "+", "-", "+i", "-i"]
basis_events = ([[0, _] for _ in range(4)] +
[[1, _] for _ in range(2)]
)
basic_event_str = {'0': (0, 0),
'1': (0, 1),
'2': (0, 2),
'3': (0, 3),
'4': (1, 0),
'5': (1, 1)
}
basic_event_probs = {'0': (1 - eps**2 / 2 - eta**2 / 4),
'1': eta**2 / 4,
'2': eps**2 / 4,
'3': eps**2 / 4,
'4': (1 - eps**2 / 4),
'5': eps**2 / 4
}
prob_loss = np.sin(phi / 2)**2 / 2
# all_events = product(basis_events, repeat=L)
# trial_list = [randrange(6**7) for _ in range(num_trials)]
# print(trial_list)
now = datetime.datetime.now()
final_data_name = (now.strftime("%Y%m%d%H%M") +
f"_state_{LogicalStates_str[jLog]}_" +
f"phi_{phi_tilde:1.2f}_eps_{epsilon_choi}.dat"
)
file_data_name = os.path.join(folder_name,
final_data_name
)
print(f"logical state |{LogicalStates_str[jLog]}_L>")
index_conf = 0
cumulative_probability = 0
done_events = []
while len(done_events) <= num_trials:
event, event_str = create_random_event(prob_loss, basic_event_probs)
if event_str in done_events:
continue
done_events.append(event_str)
print(index_conf, event_str)
index_conf += 1
if (index_conf == num_trials or
(1 - cumulative_probability) < 1e-4):
break
outcomes_ancilla = [el[0] for el in event]
sub_case_ancilla = [el[1] for el in event]
print(event)
print(outcomes_ancilla)
prob_correction_logical_state = []
psiL = LogicalStates[jLog]
null_state = False
rho_L = psiL * psiL.dag()
do_nothing = []
replace_qubits = []
false_negative = []
probs_outcome = []
probs_incoherent_process = []
for data_q in range(L):
# apply Rloss with an angle phi
rho_L = rotation_ops[data_q] * rho_L * rotation_ops[data_q].dag()
# apply the QND detection unit
rho_L = apply_qnd_process_unit(chi_matrix,
rho_L,
data_q,
chi_threshold
)
# rho_L.tidyup(atol = 1e-8)
# apply the effective incoherent noise model
if outcomes_ancilla[data_q] == 0: # ancilla in 0 state
prob_outcome = (rho_L * Pp_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
# the state cannot be projected
# in the +1 eigenstate of the ancilla
null_state = True
print("check null state")
exit()
if sub_case_ancilla[data_q] == 0: # 1 - eps**2/2 - eta**2/4
rho_L = (Pp_ancilla * rho_L * Pp_ancilla.dag() /
abs(prob_outcome))
do_nothing.append(data_q)
probs_incoherent_process.append(1 - eps**2 / 2 - eta**2 / 4)
elif sub_case_ancilla[data_q] == 1: # eta**2 / 4
rho_L = (Pm_ancilla * rho_L * Pm_ancilla.dag() /
(1 - abs(prob_outcome)))
rho_L = X[data_q] * rho_L * X[data_q].dag()
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
replace_qubits.append(data_q)
probs_incoherent_process.append(eta**2 / 4)
elif sub_case_ancilla[data_q] == 2: # epsilon**2/4
rho_L = (Pm_ancilla * rho_L * Pm_ancilla.dag() /
(1 - abs(prob_outcome)))
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
replace_qubits.append(data_q)
probs_incoherent_process.append(eps**2 / 4)
elif sub_case_ancilla[data_q] == 3: # epsilon**2/4
rho_L = (Pp_ancilla * rho_L * Pp_ancilla.dag()
/ abs(prob_outcome))
rho_L = X[data_q] * rho_L * X[data_q].dag()
do_nothing.append(data_q)
probs_incoherent_process.append(eps**2 / 4)
elif outcomes_ancilla[data_q] == 1: # ancilla in 1 state
prob_outcome = (rho_L * Pm_ancilla).tr()
if abs(prob_outcome.imag) > 1e-5:
print("warning: im prob_outcome = {prob_outcome}")
if prob_outcome == 0:
null_state = True
print("check null state")
exit()
if sub_case_ancilla[data_q] == 0: # 1 - eps**2 / 4
rho_L = (Pm_ancilla * rho_L * Pm_ancilla.dag() /
abs(prob_outcome))
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
replace_qubits.append(data_q)
probs_incoherent_process.append(1 - eps**2 / 4)
elif sub_case_ancilla[data_q] == 1: # eps**2 / 4 false negative
rho_L = (Pp_ancilla * rho_L * Pp_ancilla.dag()
/ (1-abs(prob_outcome)))
rho_L = Xa * rho_L * Xa.dag() # reinitializing ancilla
false_negative.append(data_q)
probs_incoherent_process.append(eps**2 / 4)
probs_outcome.append(prob_outcome)
prob_total_event = np.prod(probs_outcome) * np.prod(probs_incoherent_process)
cumulative_probability += prob_total_event
print("probs_outcome", np.array(probs_outcome))
print("probs_incoherent_process", np.array(probs_incoherent_process))
print(index_conf, outcomes_ancilla, sub_case_ancilla,
do_nothing,
replace_qubits,
false_negative,
# np.array(probs_outcome),
# np.array(probs_incoherent_process),
# np.prod(probs_outcome),
# f"{np.prod(probs_incoherent_process):4}",
f"{np.prod(probs_outcome)*np.prod(probs_incoherent_process):.4}",
f"{cumulative_probability:.4}"
)
if sum(outcomes_ancilla) >= 7 or null_state or len(do_nothing) == 0:
print(prob_total_event)
correction_successful = 0.0
prob_correction_logical_state.append(correction_successful)
else:
w_0 = rho_L.ptrace(do_nothing)
rho_L = qu.tensor([qu.fock_dm(3, 0)] * len(replace_qubits) +
[qu.fock_dm(3, 2)] * len(false_negative) +
[w_0] +
[qu.fock_dm(2, 0)])
print(replace_qubits,
false_negative,
do_nothing
)
permutation_order_q = {}
# the order in the for is important because redefine the state as
# ket(0) detected_losses , ket(2) false negative, kept_qubits
for j, el in enumerate(replace_qubits + false_negative + do_nothing):
permutation_order_q[el] = j
# print("permutation_order_q", permutation_order_q)
stab_qubits_new_order = []
for stab in stab_qubits:
stab_qubits_new_order.append([permutation_order_q[q]
for q in stab]
)
Sx = [X[j1] * X[j2] * X[j3] * X[j4]
for j1, j2, j3, j4 in stab_qubits_new_order
]
Sz = [Z[j1] * Z[j2] * Z[j3] * Z[j4]
for j1, j2, j3, j4 in stab_qubits_new_order
]
PPx = [[(Id + el) / 2, (Id - el) / 2] for el in Sx]
PPz = [[(Id + el) / 2, (Id - el) / 2] for el in Sz]
average_value_each_stab_meas = []
index_stab_measurement = 0
cumulative_probability_stabilizers = 0.0
for meas_binary_X, meas_binary_Z in product(range(8), range(8)):
if abs(1 - cumulative_probability_stabilizers) < 1e-4:
# exit if the cumulative probability
# during the stabilizer measurement
# is already close to 1
break
state_after_measure = qu.Qobj(rho_L[:], dims=rho_L.dims)
configuration_str_X = bin(meas_binary_X)[2:].zfill(3)
configuration_int_X = [int(_) for _ in configuration_str_X]
configuration_str_Z = bin(meas_binary_Z)[2:].zfill(3)
configuration_int_Z = [int(_) for _ in configuration_str_Z]
probability_each_measurement = []
for stab_num, outcome_stab in enumerate(configuration_int_X):
prob = (PPx[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPx[stab_num][outcome_stab] *
state_after_measure *
PPx[stab_num][outcome_stab].dag() / prob
)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
for stab_num, outcome_stab in enumerate(configuration_int_Z):
prob = (PPz[stab_num][outcome_stab] * state_after_measure).tr()
if np.abs(prob) > 0:
state_after_measure = (PPz[stab_num][outcome_stab] *
state_after_measure *
PPz[stab_num][outcome_stab].dag() / prob)
probability_each_measurement.append(np.real(prob))
else:
probability_each_measurement.append(0)
# place where we can apply corrections but we don't
print(f"{index_stab_measurement: 4d}", configuration_int_X, configuration_int_Z,
f"{np.prod(probability_each_measurement):1.4f}",
f"{qu.expect(XL, state_after_measure):+1.4f}",
f"{ qu.expect(ZL, state_after_measure):+1.4f}",
f"{qu.expect(1j * XL * ZL, state_after_measure):+1.4f}"
)
prob_stabilizers = np.prod(probability_each_measurement)
cumulative_probability_stabilizers += prob_stabilizers
if jLog in (0, 1):
correction_successful = (1 + abs(qu.expect(ZL, state_after_measure))) / 2
elif jLog in (2, 3):
correction_successful = (1 + abs(qu.expect(XL, state_after_measure))) / 2
elif jLog in (4, 5):
correction_successful = (1 + abs(qu.expect(1j * XL * ZL, state_after_measure))) / 2
average_value_each_stab_meas.append(prob_stabilizers *
correction_successful
)
# conf_stab_meas = int("".join(str(_) for _ in configuration_int_X + configuration_int_Z))
index_stab_measurement += 1
print("prob_of_succ_correction", np.sum(average_value_each_stab_meas))
conf_loss = int("".join(str(_) for _ in outcomes_ancilla))
conf_case_ancilla = int("".join(str(_) for _ in sub_case_ancilla))
res = ([phi_tilde,
conf_loss,
conf_case_ancilla,
np.real(np.sum(average_value_each_stab_meas)),
np.real(prob_total_event)
])
final_p_loss.append(res)
np.savetxt(file_data_name, final_p_loss, fmt='%1.3f\t' +
'%07d\t' +
'%07d\t' +
'%.10e\t' +
'%1.14f\t')
np.savetxt(file_data_name, final_p_loss, fmt='%1.3f\t' +
'%07d\t' +
'%07d\t' +
'%.10e\t' +
'%1.14f\t')
| 611e8ea52692cd7e965f25fb528b464e3c5129af | [
"Python",
"Shell"
] | 28 | Python | davidev886/lossCorrection | 7ebcae6c236e876ee5afdb95abf3df2c325cd081 | 8661c04dce1d67632ff9acfdeec6e412f7a6dd9f |
refs/heads/master | <repo_name>RaphaelYoshiga/UnitTestingSamples<file_sep>/Outside.Training.AdvancedTddSample/PageVisitToBrokeredMessageParser.cs
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Outside.Training.AdvancedTddSample
{
public class PageVisitToBrokeredMessageParser : IPageVisitToBrokeredMessageParser
{
public BrokeredMessage Parse(PageVisit pageVisit)
{
var serializedObject = JsonConvert.SerializeObject(pageVisit);
return new BrokeredMessage(serializedObject);
}
}
}
<file_sep>/Outside.Training.BasicTddSample/Triangle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Outside.Training.BasicTddSample
{
public class Triangle
{
public Triangle(double width, double height)
{
if (width < 0)
throw new ArgumentOutOfRangeException("width");
if (height < 0)
throw new ArgumentOutOfRangeException("height");
Width = width;
Height = height;
}
public double Width { get; private set; }
public double Height { get; private set; }
public double CalculateArea()
{
return Height * Width / 2;
}
}
}
<file_sep>/Outside.Training.AdvancedTddSample/PageVisitForwarder.cs
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Outside.Training.AdvancedTddSample
{
public class PageVisitForwarder
{
private IPageVisitToBrokeredMessageParser _messageParser;
private IServiceBusMessageSender _serviceBusMessageSender;
public PageVisitForwarder(IPageVisitToBrokeredMessageParser messageParser, IServiceBusMessageSender serviceBusMessageSender)
{
_messageParser = messageParser;
_serviceBusMessageSender = serviceBusMessageSender;
}
public void ForwardMessage(PageVisit pageVisit)
{
if (pageVisit == null)
throw new ArgumentNullException("pageVisit");
if (string.IsNullOrEmpty(pageVisit.PageUrl))
throw new ArgumentNullException("pageVisit.PageUrl");
var message = _messageParser.Parse(pageVisit);
_serviceBusMessageSender.SendMessage(message);
}
}
}
<file_sep>/Outside.Training.AdvancedTddSample/ServiceBusMessageSender.cs
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Outside.Training.AdvancedTddSample
{
public class ServiceBusMessageSender : IServiceBusMessageSender
{
public void SendMessage(BrokeredMessage message)
{
var topicClient = TopicClient.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"], "topicName");
topicClient.Send(message);
}
}
}
<file_sep>/Outside.Training.BasicTddSample.Tests/TriangleShould.cs
using NUnit.Framework;
using Shouldly;
using System;
namespace Outside.Training.BasicTddSample.Tests
{
[TestFixture]
public class TriangleShould
{
[TestCase(52, 31)]
[TestCase(401, 501)]
public void Set_Constructor_Arguments(int width, int height)
{
var triangle = new Triangle(width, height);
triangle.Width.ShouldBe(width);
triangle.Height.ShouldBe(height);
}
[TestCase(-1)]
[TestCase(-10)]
public void Throw_When_Negative_Height(int height)
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Triangle(1, height));
}
[TestCase(-1)]
[TestCase(-10)]
public void Throw_When_Negative_Width(int width)
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Triangle(width, 1));
}
[TestCase(2, 1, ExpectedResult = 1)]
[TestCase(1, 1, ExpectedResult = 0.5)]
[TestCase(60, 90, ExpectedResult = 2700)]
public double Have_Area_Based_On_Height_And_Width(int width, int height)
{
var triangle = new Triangle(width, height);
return triangle.CalculateArea();
}
}
}
<file_sep>/README.md
# UnitTestingSamples
Unit test samples
<file_sep>/Outside.Training.AdvancedTddSample.Tests/PageVisitForwarderShould.cs
using Microsoft.ServiceBus.Messaging;
using Moq;
using NUnit.Framework;
using System;
namespace Outside.Training.AdvancedTddSample.Tests
{
[TestFixture]
public class PageVisitForwarderShould
{
private PageVisitForwarder _pageVisitForwarder;
private Mock<IServiceBusMessageSender> _serviceBusMock;
private Mock<IPageVisitToBrokeredMessageParser> _messageParserMock;
[SetUp]
public void BeforeEachTest()
{
_messageParserMock = new Mock<IPageVisitToBrokeredMessageParser>();
_serviceBusMock = new Mock<IServiceBusMessageSender>();
_pageVisitForwarder = new PageVisitForwarder(_messageParserMock.Object, _serviceBusMock.Object);
}
[Test]
public void Throw_When_PageVisit_Is_Null()
{
Assert.Throws<ArgumentNullException>(() => _pageVisitForwarder.ForwardMessage(null));
_serviceBusMock.Verify(p => p.SendMessage(It.IsAny<BrokeredMessage>()), Times.Never);
}
[Test]
public void Throw_When_PageUrl_Is_Null()
{
Assert.Throws<ArgumentNullException>(() => _pageVisitForwarder.ForwardMessage(new PageVisit()));
_serviceBusMock.Verify(p => p.SendMessage(It.IsAny<BrokeredMessage>()), Times.Never);
}
[Test]
public void Call_Message_Parser()
{
PageVisit pageVisit = GetValidPageVisit();
_pageVisitForwarder.ForwardMessage(pageVisit);
_messageParserMock.Verify(p => p.Parse(pageVisit), Times.Once);
}
private static PageVisit GetValidPageVisit()
{
var pageVisit = new PageVisit();
pageVisit.PageUrl = "test";
return pageVisit;
}
[Test]
public void Call_Message_Sender()
{
var expectedBrokeredMessage = new BrokeredMessage();
var pageVisit = GetValidPageVisit();
_messageParserMock.Setup(p => p.Parse(It.IsAny<PageVisit>()))
.Returns(expectedBrokeredMessage);
_pageVisitForwarder.ForwardMessage(pageVisit);
_serviceBusMock.Verify(p => p.SendMessage(expectedBrokeredMessage), Times.Once);
}
}
}
<file_sep>/Outside.Training.AdvancedTddSample/IPageVisitToBrokeredMessageParser.cs
using Microsoft.ServiceBus.Messaging;
namespace Outside.Training.AdvancedTddSample
{
public interface IPageVisitToBrokeredMessageParser
{
BrokeredMessage Parse(PageVisit pageVisit);
}
}<file_sep>/Outside.Training.AdvancedTddSample/IServiceBusMessageSender.cs
using Microsoft.ServiceBus.Messaging;
namespace Outside.Training.AdvancedTddSample
{
public interface IServiceBusMessageSender
{
void SendMessage(BrokeredMessage message);
}
} | e20f49d14a832246966da1780726795680e1f8c4 | [
"Markdown",
"C#"
] | 9 | C# | RaphaelYoshiga/UnitTestingSamples | a7bfbeefa30a5894b44c28725b50df8fb5b01b32 | 315d9268d741ca318cf9ad5100ae0be21bcd85a0 |
refs/heads/master | <file_sep>import React from "react";
import {
View,
Text,
StyleSheet,
ImageBackground,
ScrollView
} from "react-native";
import Comment from "../components/Comment";
class CourseInfoScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
courseInfo: this.props.navigation.state.params.courseInfo
};
}
render() {
return (
<ImageBackground
source={require("../assets/background7.jpg")}
style={styles.container}
>
<ScrollView>
<View style={styles.infoContainer}>
<Text style={styles.itemHeader}>Name:</Text>
<View style={styles.listItem}>
<Text>{this.state.courseInfo.name}</Text>
</View>
<Text style={styles.itemHeader}>Code:</Text>
<View style={styles.listItem}>
<Text>{this.state.courseInfo.code}</Text>
</View>
<Text style={styles.itemHeader}>Teacher:</Text>
<View style={styles.listItem}>
<Text>{this.state.courseInfo.teacher}</Text>
</View>
<Text style={styles.itemHeader}>Scope:</Text>
<View style={styles.listItem}>
<Text>{this.state.courseInfo.scope}</Text>
</View>
<Text style={styles.itemHeader}>Objectives:</Text>
<View style={styles.listItem}>
<Text>{this.state.courseInfo.objectives}</Text>
</View>
</View>
</ScrollView>
<Comment courseId={this.state.courseInfo._id} />
</ImageBackground>
);
}
}
export default CourseInfoScreen;
const styles = StyleSheet.create({
container: {
height: "100%"
},
infoContainer: {
height: "45%"
},
itemHeader: {
paddingLeft: 5
},
listItem: {
padding: 5,
marginBottom: 5,
backgroundColor: "#ccc",
borderColor: "black",
borderWidth: 1,
flexDirection: "row",
justifyContent: "space-between",
textAlignVertical: "center",
opacity: 0.8
}
});
<file_sep>import React from "react";
import {
View,
StyleSheet,
ActivityIndicator,
AsyncStorage
} from "react-native";
class LoadingScreen extends React.Component {
constructor() {
super();
this.checkToken();
}
checkToken = async () => {
const token = await AsyncStorage.getItem("token");
if (token) {
this.props.navigation.navigate("App");
} else {
this.props.navigation.navigate("Auth");
}
};
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
}
}
export default LoadingScreen;
const styles = StyleSheet.create({
container: {
height: "100%",
alignItems: "center",
justifyContent: "center"
}
});
<file_sep># The Great University App
This is the specification document of an application built for course Mobile Application Development (2020) at University of Vaasa
### Usage
Scan [this QR code](https://expo.io/@villeve/react-native-app) with your Expo mobile app to load this project immediately. Create new account or use an admin account with following credentials **(CAUTION: CASE SENSITIVE)**: <EMAIL> | admin2020!
### Basic idea
This App allows users to view the course selection of various universities and comment on them. Currently all data about the universities/courses is manually entered by admin users. Most of the Universities are empty, but there are a couple of courses added under University of Vaasa. You may go a head and add your own course!
## Frontend
The frontend is mostly built out of react native screens and it uses the AppNavigator to navigate between them. The code is quite ugly; a lot of repeatance, promises are handled in varying manner and styling is bad. Coolest things are probably the screen navigation as previously mentioned and the use of AsyncStorage to save tokens and user information even when the app is closed
### How to Run
npm start
### Stack
- React Native (Expo)
- Axios
### Github
>https://github.com/Villeve/mobile-application-development
## Backend
The backend uses token based authentication (passport-jwt, express-jwt) and mongoose for data modeling. The forms of the application do not have very implicit validators so they can be rather easily exploited. That is definitely something to improve. Also, new features such as a rating system for the courses and a search could be implemented later.
### How to Run
npm start
### Stack
- Node
- Express
- MongoDB
### Endpoints
- Every endpoint requires authentication (except for login and register)
- All users can send GET-requests
- All users can send or remove their own comment
- Admin users can remove any comment
- Only admin users can send POST or DELETE requests (Comments are an exception)
### Routes
- /api/users
- /api/universities
- /api/faculties
- /api/courses
- /api/comments
### Database
All of the applications data is stored in five JSON-like collections in a NoSQL database, MongoDB. One collection for each type: universities, faculties, courses, comments and users.
- Universities are at the top of the hierarchy as they have references to their corresponding faculties (array of IDs)
- Faculties have reference to their parent University
- Courses have reference to their parent Faculty
- Comments have reference to their parent Course
Users are stored in following manner (passwords are hashed using [bcrypt](https://www.npmjs.com/package/bcryptjs) and 10 salting rounds):
_id:5e349f0e907d6c56a4466ba7
role:"0"
name:"ville"
email:"<EMAIL>"
password:"<PASSWORD>"
date:2020-01-31T21:41:34.796+00:00
__v:0
### Hosting
The backend is hosted on Heroku
>https://mobile-app-backend-uva.herokuapp.com/
### Github
>https://github.com/Villeve/mobile-application-development-backend
----<file_sep>import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import LoginScreen from "./screens/LoginScreen";
import DashboardScreen from "./screens/DashboardScreen";
import LoadingScreen from "./screens/LoadingScreen";
import RegisterScreen from "./screens/RegisterScreen";
import FacultyScreen from "./screens/FacultyScreen";
import CourseScreen from "./screens/CourseScreen";
import NewCourseScreen from "./screens/NewCourseScreen";
import CourseInfoScreen from "./screens/CourseInfoScreen";
const BeforeSignin = createStackNavigator(
{
Login: {
screen: LoginScreen
}
},
{
headerMode: "none",
initialRouteName: "Login"
}
);
const OnRegister = createStackNavigator({
Register: {
screen: RegisterScreen
}
});
const AfterSignin = createStackNavigator(
{
Universities: {
screen: DashboardScreen
}
},
{
initialRouteName: "Universities"
}
);
const OnPressUniversity = createStackNavigator(
{
Faculties: {
screen: FacultyScreen
}
},
{
initialRouteName: "Faculties"
}
);
const OnPressFaculty = createStackNavigator(
{
Courses: {
screen: CourseScreen
}
},
{
initialRouteName: "Courses"
}
);
const OnCreateNewCourse = createStackNavigator(
{
NewCourse: {
screen: NewCourseScreen
}
},
{
headerMode: "none",
initialRouteName: "NewCourse"
}
);
const OnPressCourse = createStackNavigator(
{
CourseInfo: {
screen: CourseInfoScreen
}
},
{
initialRouteName: "CourseInfo"
}
);
const AppNavigator = createStackNavigator(
{
Auth: BeforeSignin,
Register: OnRegister,
App: AfterSignin,
LoadingScreen: LoadingScreen,
Faculties: OnPressUniversity,
Courses: OnPressFaculty,
NewCourse: OnCreateNewCourse,
CourseInfo: OnPressCourse
},
{
headerMode: "",
initialRouteName: "LoadingScreen"
}
);
export default createAppContainer(AppNavigator);
<file_sep>import React, { useState, useEffect } from "react";
import {
View,
Button,
TextInput,
StyleSheet,
Text,
FlatList,
TouchableOpacity,
AsyncStorage
} from "react-native";
import axios from "axios";
import Spinner from 'react-native-loading-spinner-overlay';
const Comment = props => {
const [enteredComment, setEnteredComment] = useState("");
const [role, setRole] = useState("0");
const [username, setUsername] = useState("");
const [comments, setComments] = useState([]);
const [loading, setLoading] = useState(true);
const textAdded = text => setEnteredComment(text);
useEffect(() => {
setUserNameAndType();
fetchComments();
}, []);
const setUserNameAndType = async () => {
const role = await AsyncStorage.getItem("role");
const username = await AsyncStorage.getItem("name");
setUsername(username);
setRole(role);
};
const fetchComments = async () => {
try {
const token = await AsyncStorage.getItem("token");
const headers = {
Authorization: "Bearer " + token
};
const res = await axios({
method: "GET",
url:
"https://mobile-app-backend-uva.herokuapp.com/api/comments/" +
props.courseId,
headers: headers
});
setComments(res.data);
setLoading(false);
} catch (error) {
console.warn(error);
setComments([]);
alert("Error While fetching data");
}
};
const addComment = async () => {
setLoading(true);
const username = await AsyncStorage.getItem("name");
const token = await AsyncStorage.getItem("token");
const headers = {
Authorization: "Bearer " + token
};
const req = {
content: enteredComment,
postedBy: username,
courseId: props.courseId
};
axios({
method: "POST",
url: "https://mobile-app-backend-uva.herokuapp.com/api/comments",
data: req,
headers: headers
})
.then(res => {
setEnteredComment("");
fetchComments();
})
.catch(error => {
console.warn(error);
alert("Error while adding new comment");
});
};
const removeComment = async commentId => {
setLoading(true);
const token = await AsyncStorage.getItem("token");
const headers = {
Authorization: "Bearer " + token
};
axios({
method: "DELETE",
url:
"https://mobile-app-backend-uva.herokuapp.com/api/comments/" +
commentId,
headers: headers
})
.then(res => {
fetchComments();
})
.catch(error => {
console.warn(error);
alert("Error While Removing Comment");
});
};
return (
<View style={styles.container}>
<Spinner
visible={loading}
textContent={'Loading...'}
textStyle={styles.spinnerTextStyle}
/>
<View style={styles.inputContainer}>
<TextInput
placeholder="Add comment"
style={styles.input}
onChangeText={textAdded}
value={enteredComment}
/>
</View>
<Button title="Send" onPress={addComment} />
<FlatList
style={styles.newCommentButton}
data={comments}
keyExtractor={item => item._id}
renderItem={itemData => (
<View style={styles.commentItems}>
<Text style={styles.commentHeader}>
{itemData.item.postedBy} ({itemData.item.date.substring(0, 10)}):
</Text>
<Text> {itemData.item.content}</Text>
{(itemData.item.postedBy === username || role === "1") && (
<TouchableOpacity style={styles.removeButton}>
<Text
style={styles.removeButtonText}
onPress={() => removeComment(itemData.item._id)}
>
Remove
</Text>
</TouchableOpacity>
)}
</View>
)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
height: "55%"
},
spinnerTextStyle: {
color: '#FFF'
},
inputContainer: {
flexDirection: "row"
},
input: {
width: "100%",
borderBottomColor: "black",
borderWidth: 1,
padding: 10,
marginBottom: 5,
backgroundColor: "white",
opacity: 0.8
},
newCommentButton: {
marginTop: 5,
backgroundColor: "white",
opacity: 0.9
},
commentItems: {
marginVertical: 5
},
commentHeader: {
paddingLeft: 5,
fontSize: 12,
color: "grey"
},
removeButton: {
backgroundColor: "red",
paddingVertical: 5,
width: 70
},
removeButtonText: {
color: "#fff",
textAlign: "center",
fontWeight: "bold"
}
});
export default Comment;
<file_sep>import React from "react";
import {
View,
Text,
StyleSheet,
TextInput,
TouchableOpacity,
AsyncStorage,
ImageBackground
} from "react-native";
import axios from "axios";
class LoginScreen extends React.Component {
state = {
email: "",
password: "",
loading: false
};
onStateChange(state, value) {
this.setState({
[state]: value
});
}
// Check the credentials are valid and store user information
login() {
const { email, password } = this.state;
if (email && password) {
const req = {
email: email,
password: password
};
this.setState({
loading: true
});
axios
.post(
"https://mobile-app-backend-uva.herokuapp.com/api/users/login",
req
)
.then(
res => {
this.setState({
loading: false,
email: "",
password: ""
});
var role = res.data.role;
AsyncStorage.setItem("token", res.data.token);
AsyncStorage.setItem("name", res.data.name);
AsyncStorage.setItem("role", role).then(res => {
this.props.navigation.navigate("App");
});
},
err => {
console.warn(err);
this.setState({
loading: false,
password: ""
});
alert("Wrong email or password");
}
);
} else {
alert("Enter email and password");
}
}
render() {
const { email, password, loading } = this.state;
return (
<ImageBackground
source={require("../assets/brickwall.jpg")}
style={styles.container}
>
<View style={styles.formWrapper}>
<Text style={styles.title}>Welcome to the great University App</Text>
<View style={styles.formRow}>
<TextInput
style={styles.textInput}
placeholder="Enter Email"
placeholderTextColor="#333"
value={email}
onChangeText={value => this.onStateChange("email", value)}
/>
</View>
<View style={styles.formRow}>
<TextInput
style={styles.textInput}
placeholder="Enter Password"
placeholderTextColor="#333"
secureTextEntry={true}
value={password}
onChangeText={value => this.onStateChange("password", value)}
/>
</View>
<TouchableOpacity
activeOpacity={0.8}
style={{
...styles.button,
backgroundColor: loading ? "#ddd" : "blue"
}}
onPress={() => this.login()}
disabled={loading}
>
<Text style={styles.buttonText}>
{loading ? "Loading..." : "Sign in"}
</Text>
</TouchableOpacity>
<Text
style={styles.registerText}
onPress={() => this.props.navigation.navigate("Register")}
>
Click to Register
</Text>
</View>
</ImageBackground>
);
}
}
export default LoginScreen;
const styles = StyleSheet.create({
container: {
height: "100%",
alignItems: "center",
justifyContent: "center"
},
formWrapper: {
width: "80%"
},
formRow: {
marginBottom: 10
},
textInput: {
backgroundColor: "#ddd",
height: 40,
paddingHorizontal: 10
},
title: {
textAlign: "center",
marginBottom: 20,
fontSize: 38,
fontWeight: "bold",
color: "yellow"
},
button: {
paddingVertical: 10
},
buttonText: {
textAlign: "center",
color: "#fff",
fontSize: 15,
fontWeight: "bold"
},
registerText: {
textAlign: "center",
color: "yellow",
fontSize: 18,
fontWeight: "bold",
paddingVertical: 10
}
}); | 00498ab73cd92be6f43a59005d1290211944e2d3 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | Villeve/mobile-application-development | 04a57ba5f9c6efe0b14c57558f1e55b667a68052 | fe01825fb93e4dcb293943511da2d6ded1533a42 |
refs/heads/master | <file_sep>#!/usr/bin/env python
#
# Copyright under the latest Apache License 2.0
'''
Based on code that Konpaku Kogasa used to create code.google.com/p/oauth-python-twitter2/
Requires:
simplejson
oauth2
'''
__author__ = "<NAME>, <NAME>, <NAME>"
__version__ = "0.1"
# Library modules
import urllib
import urllib2
import urlparse
import time
# Non library modules
import simplejson
import oauth2
# Taken from oauth implementation at: http://github.com/harperreed/twitteroauth-python/tree/master
REQUEST_TOKEN_URL = 'https://www.readability.com/api/rest/v1/oauth/request_token/'
ACCESS_TOKEN_URL = 'https://www.readability.com/api/rest/v1/oauth/access_token/'
AUTHORIZATION_URL = 'https://www.readability.com/api/rest/v1/oauth/authorize/'
class OAuthApi():
def __init__(self, consumer_key, consumer_secret, token=None, token_secret=None):
if token and token_secret:
token = oauth2.Token(token, token_secret)
else:
token = None
self._Consumer = oauth2.Consumer(consumer_key, consumer_secret)
#self._signature_method = oauth2.SignatureMethod_PLAINTEXT()
self._access_token = token
def _FetchUrl(self,url, http_method=None,parameters=None):
client = oauth2.Client(self._Consumer, self._access_token)
if http_method == 'POST':
body = urllib.urlencode(parameters)
return client.request(url, method=http_method, body=body)
else:
return client.request(url, method=http_method)
def getAuthorizationURL(self, token, url=AUTHORIZATION_URL):
'''Create a signed authorization URL
Returns:
A signed OAuthRequest authorization URL
'''
return "%s?oauth_token=%s" % (url, token['oauth_token'])
def getRequestToken(self, url=REQUEST_TOKEN_URL):
'''Get a Request Token from Twitter
Returns:
A OAuthToken object containing a request token
'''
resp, content = oauth2.Client(self._Consumer).request(url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
return dict(urlparse.parse_qsl(content))
def getAccessToken(self, token, verifier, url=ACCESS_TOKEN_URL):
'''Get a Request Token from Twitter
Returns:
A OAuthToken object containing a request token
'''
token = oauth2.Token(token['oauth_token'], token['oauth_token_secret'])
token.set_verifier(verifier)
client = oauth2.Client(self._Consumer, token)
resp, content = client.request(url, "POST")
return dict(urlparse.parse_qsl(content))
def addBookmark(self, url, favorite=0, archive=0, options={}):
'''Add a bookmark. Returns 202 Accepted, meaning that the bookmark has been added
but no guarantees are made as to whether the article proper has yet been parsed.
'''
options['url'] = url
resp, content = self.ApiCall('bookmarks', 'POST', options)
if resp.get('status') == '409':
raise Exception("409 Conflict/Duplicate - %s" % url)
elif resp.get('status') == '202':
return {'x-article-location': resp.get('x-article-location'),
'location': resp.get('location')}
def getBookmarks(self, options={}):
return simplejson.loads(self.ApiCall('bookmarks', 'GET', options)[1])
def getSubresources(self, options={}):
return self.ApiCall('', 'GET', options)
def ApiCall(self, call, type="GET", parameters={}):
'''Calls the twitter API
Args:
call: The name of the api call (ie. account/rate_limit_status)
type: One of "GET" or "POST"
parameters: Parameters to pass to the Readability API call
Returns:
Returns the twitter.User object
'''
response = self._FetchUrl("https://www.readability.com/api/rest/v1/%s/" % call, type, parameters)
return response
<file_sep>from oauthreadability import OAuthApi
consumer_key = ""
consumer_secret = ""
readability = OAuthApi(consumer_key, consumer_secret)
# Get the temporary credentials for our next few calls
temp_credentials = readability.getRequestToken()
# User pastes this into their browser to bring back a pin number
print(readability.getAuthorizationURL(temp_credentials))
# Get the pin # from the user and get our permanent credentials
oauth_verifier = raw_input('What is the PIN? ')
access_token = readability.getAccessToken(temp_credentials, oauth_verifier)
print("oauth_token: " + access_token['oauth_token'])
print("oauth_token_secret: " + access_token['oauth_token_secret'])
# access_token = {'oauth_token': '',
# 'oauth_token_secret': ''}
# # Do a test API call using our new credentials
readability = OAuthApi(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
print readability.getBookmarks()
print readability.addBookmark(url='http://blog.arc90.com/2010/11/30/silence-is-golden/')
| 2c00db0e7c130d2391b906888df00b9a12473603 | [
"Python"
] | 2 | Python | jurecuhalev/oauth-python-readability | f268e4178d9a5680e9a602bc20cc075507f71070 | 1499755a74244bcc98ff4fcee86bd4ea1ad9e383 |
refs/heads/master | <file_sep>tap "dart-lang/dart"
tap "github/gh"
tap "homebrew/bundle"
tap "homebrew/cask"
tap "homebrew/core"
tap "homebrew/services"
tap "mongodb/brew"
tap "sass/sass"
# Search tool like grep, but optimized for programmers
brew "ack"
# Infamous electronic fortune-cookie generator
brew "fortune"
# Command-line fuzzy finder written in Go
brew "fzf"
# GitHub command-line tool
brew "gh"
# Distributed revision control system
brew "git"
# Interpreted, interactive, object-oriented programming language
brew "python@3.8", link: true
# Core application library for C
brew "glib"
# Open source programming language to build simple/reliable/efficient software
brew "go"
# Improved top (interactive process viewer)
brew "htop"
# Configurable static site generator
brew "hugo"
# Tools and libraries to manipulate images in many formats
brew "imagemagick"
# Fast, highly customisable system info script
brew "neofetch"
# Read-write NTFS driver for FUSE
brew "ntfs-3g"
# Manage multiple Node.js versions
brew "nvm"
# Object-relational database system
brew "postgresql"
# Implementation of Telnet and SSH
brew "putty"
# Install various Ruby versions and implementations
brew "ruby-build"
# Ruby version manager
brew "rbenv"
# Powerful, clean, object-oriented scripting language
brew "ruby"
# Terminal multiplexer
brew "tmux"
# Display directories as trees (with optional color/HTML output)
brew "tree"
# Vi 'workalike' with many additional features
brew "vim"
# Internet file retriever
brew "wget"
# UNIX shell (command interpreter)
brew "zsh"
# Fish-like fast/unobtrusive autosuggestions for zsh
brew "zsh-autosuggestions"
# Additional completion definitions for zsh
brew "zsh-completions"
# High-performance, schema-free, document-oriented database
brew "mongodb/brew/mongodb-community"
# A badass zsh theme with more power than a normal earthling
brew "sambadevi/powerlevel9k/powerlevel9k"
# Stylesheet Preprocessor
brew "sass/sass/sass"
cask "godot"
# Terminal emulator as alternative to Apple's Terminal app
cask "iterm2"
# Finder Toolbar app to open the current directory in Terminal or Editor
cask "openinterminal"
# QuickLook plug-in that renders source code with syntax highlighting
cask "qlcolorcode"
# Display image info and preview unsupported formats in QuickLook
cask "qlimagesize"
# QuickLook generator for Markdown files
cask "qlmarkdown"
cask "qlstephen"
cask "quicklook-json"
cask "quicklookase"
# Application for inspecting installer packages
cask "suspicious-package"
<file_sep>DISABLE_MAGIC_FUNCTIONS="true"
export PATH=$HOME/bin:/usr/local/bin:$PATH
export PATH="/usr/local/sbin:$PATH"
# Path to your oh-my-zsh installation.
export ZSH="/Users/az/.oh-my-zsh"
export LC_CTYPE=C
export LANG=C
# fix for vim: https://stackoverflow.com/a/56743150/8080186
export LC_ALL=en_US.UTF-8
ZSH_THEME="agnoster"
# Uncomment the following line to display red dots whilst waiting for completion.
COMPLETION_WAITING_DOTS="true"
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# see 'man strftime' for details.
HIST_STAMPS="yyyy-mm-dd"
# Standard plugins can be found in ~/.oh-my-zsh/plugins/*
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
plugins=(
brew
colored-man-pages
git
npm
osx
)
source $ZSH/oh-my-zsh.sh
# User configuration
# Repo: https://github.com/rupa/z
. ~/.z.sh
fpath=(/usr/local/share/zsh-completions $fpath)
source /usr/local/share/zsh-autosuggestions/zsh-autosuggestions.zsh
export MANPATH="/usr/local/man:$MANPATH"
# You may need to manually set your language environment
export LANG=en_US.UTF-8
# Compilation flags
export ARCHFLAGS="-arch x86_64"
# ssh
export SSH_KEY_PATH="~/.ssh/rsa_id"
alias vrc="vi ~/.vimrc"
alias zrc="vi ~/.zshrc"
alias szrc="source ~/.zshrc"
alias ohmyzsh="vi ~/.oh-my-zsh"
alias cx="code ."
alias cc="cd ~/GitHub"
# Shorthands
alias c="clear"
alias cls="c && ls"
alias l="ls -A"
alias la="ls -lA"
alias ll="ls -l"
alias lst="tree"
# Delete branch locally
alias gbd="git branch -d" # localBranchName
alias gbD="git branch -D" # same, but forced... or something
# Initial git push
alias gpp="git push --set-upstream origin" # master
# Delete branch remotely
alias gbdr="git push origin --delete" # remoteBranchName
# Sass
alias sassw="sass --watch sass/style.sass:style.css"
alias sasswc="sassw --style compressed"
# Python
alias pip="pip3"
alias pyms="python3 -m http.server --bind localhost"
# Jekyll
alias jekyllsw="bundle exec jekyll serve --watch"
# Gatekeeper disable
# Usage: disablegatekeeper /path/
alias disablegatekeeper="sudo xattr -rd com.apple.quarantine "
# Show random emojis in place of username@devicename
prompt_context() {
prompt_segment black default "⚡️"
}
# Show only current directory in agnoster theme
prompt_dir() { prompt_segment blue black '%c' }
# Enter key fix
stty sane
# Reminders
echo "Hi Ajit, try: cc, cx"
# source /usr/local/opt/nvm/nvm.sh
export NVM_DIR=~/.nvm
source ~/.nvm/nvm.sh
#[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion" # This loads nvm bash_completion
| ea15be5b64a0a60b6f6e3a65ff1356f9d241c5c1 | [
"Ruby",
"Shell"
] | 2 | Ruby | AjitZero/dotfiles | b043ec8b7bc82d934f8d8fe3cb18dc6f5d97ea79 | 0e32f50ab715b703d52de55f0d3cb7e7fb6b3fa6 |
refs/heads/master | <file_sep>package com.kodilla.modul74stream.world;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
public class WorldTestSuite {
@Test
public void testGetPeopleQuantity(){
//Given
//new countries
Country poland = new Country("Poland", new BigDecimal("111111"));
Country sweden = new Country("Sweden", new BigDecimal("111111"));
Country holand = new Country("Holand", new BigDecimal("111111"));
Country china = new Country("China", new BigDecimal("111111"));
Country thailand = new Country("Thailand", new BigDecimal("111111"));
Country egypt = new Country("Egypt", new BigDecimal("111111"));
Country ethiopia = new Country("Ethiopia", new BigDecimal("111111"));
Country somalia = new Country("Somalia", new BigDecimal("111111"));
//new continents
Continent europe = new Continent("Europe");
europe.addCountry(poland);
europe.addCountry(sweden);
europe.addCountry(holand);
Continent asia = new Continent("Asia");
asia.addCountry(china);
asia.addCountry(thailand);
Continent africa = new Continent("Africa");
africa.addCountry(egypt);
africa.addCountry(ethiopia);
africa.addCountry(somalia);
//new world
World world = new World();
world.addContinent(europe);
world.addContinent(asia);
world.addContinent(africa);
//When
BigDecimal result = world.getPeopleQuantity();
//Then
Assert.assertEquals(new BigDecimal("888888"), result);
}
}
| 537619a78eedd164bc7f0aafee42213bbb69e514 | [
"Java"
] | 1 | Java | Kaja89/modul-7-4-zadanie | bef922b10ae7623797ddc8ee8c9c852fa5735204 | 1fd6664698cf3b10f860d73d8aa3c29bd4c96f1d |
refs/heads/master | <repo_name>ClassroomCode/NI<file_sep>/FormsAuth/EComm.Web/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EComm.Web.Models;
using EComm.Data;
namespace EComm.Web.Controllers
{
public class HomeController : Controller
{
private readonly IRepository _repository;
private readonly ILogger<HomeController> _logger;
public HomeController(IRepository repository, ILogger<HomeController> logger)
{
_repository = repository;
_logger = logger;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
[HttpGet("privacy")]
public IActionResult Privacy()
{
return View();
}
[HttpGet("error")]
[HttpPost("error")]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpGet("clienterror")]
[HttpPost("clienterror")]
public IActionResult ClientError(int statusCode)
{
ViewBag.Message = statusCode switch
{
400 => "Bad Request (400)",
404 => "Not Found (404)",
418 => "I'm a teapot (418)",
_ => $"Other ({statusCode})"
};
return View();
}
}
}
<file_sep>/FormsAuth/EComm.Web/Models/CartViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EComm.Web.Models
{
public class CartViewModel
{
public ShoppingCart Cart { get; set; }
[Required]
public string CustomerName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[CreditCard]
public string CreditCard { get; set; }
}
}
<file_sep>/FormsAuth/EComm.Web/API/ECommGrpcService.cs
using EComm.Data;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EComm.Web.API.gRPC
{
public class ECommGrpcService : ECommGrpc.ECommGrpcBase
{
private readonly IRepository _repository;
private readonly ILogger<ECommGrpcService> _logger;
public ECommGrpcService(IRepository repository,
ILogger<ECommGrpcService> logger)
{
_repository = repository;
_logger = logger;
}
public override async Task<ProductReply> GetProduct(ProductRequest request, ServerCallContext context)
{
var product = await _repository.GetProduct(request.Id, true);
var reply = new ProductReply {
Id = product.Id,
Name = product.ProductName,
Price = (double)product.UnitPrice.Value,
Supplier = product.Supplier.CompanyName
};
return reply;
}
}
}
<file_sep>/CryptoLab/CryptoWeb/Controllers/HashController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace CryptoWeb.Controllers
{
public class HashController : Controller
{
private readonly IConfiguration _configuration;
private readonly ILogger<HashController> _logger;
public HashController(IConfiguration configuration, ILogger<HashController> logger)
{
_configuration = configuration;
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Hash(string plaintext)
{
var sha = SHA256.Create();
byte[] digestBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(plaintext));
ViewBag.Plaintext = plaintext;
ViewBag.DigestBytes = Encoding.UTF8.GetString(digestBytes);
ViewBag.EncodedDigest = Convert.ToBase64String(digestBytes);
return View("Digest");
}
}
}<file_sep>/FormsAuth/EComm.Data/IRepository.cs
using EComm.Data.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace EComm.Data
{
public interface IRepository
{
Task<IEnumerable<Product>> GetAllProducts(bool includeSuppliers = false);
Task<Product> GetProduct(int id, bool includeSupplier = false);
Task<IEnumerable<Supplier>> GetAllSuppliers();
Task SaveProduct(Product product);
}
}
<file_sep>/CryptoLab/CryptoWeb/Controllers/AsymmetricController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CryptoLib;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Text;
namespace CryptoWeb.Controllers
{
public class AsymmetricController : Controller
{
private readonly IConfiguration _configuration;
private readonly ILogger<AsymmetricController> _logger;
public AsymmetricController(IConfiguration configuration, ILogger<AsymmetricController> logger)
{
_configuration = configuration;
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Encrypt(string plaintext)
{
string publicKey = _configuration["Asymmetric:PublicKey"];
Asymmetric a = new Asymmetric();
byte[] encryptedBytes = a.Encrypt(plaintext, publicKey);
ViewBag.Plaintext = plaintext;
ViewBag.EncryptedBytes = Encoding.UTF8.GetString(encryptedBytes);
ViewBag.Ciphertext = Convert.ToBase64String(encryptedBytes);
return View();
}
[HttpPost]
public IActionResult Decrypt(string ciphertext)
{
string privateKey = _configuration["Asymmetric:PrivateKey"];
Asymmetric a = new Asymmetric();
byte[] decryptedBytes = a.Decrypt(ciphertext, privateKey);
ViewBag.Ciphertext = ciphertext;
ViewBag.Plaintext = Encoding.UTF8.GetString(decryptedBytes);
return View();
}
}
}<file_sep>/FormsAuth/EComm.Web/wwwroot/js/cart.js
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'quantity': $('input[name=quantity]').val()
};
$.ajax({
type: 'POST',
url: $('#addToCartForm').attr('action'),
data: formData
})
.done(function (response) {
$('#message').html(response);
});
event.preventDefault();
});
});
<file_sep>/CryptoLab/CryptoWeb/Controllers/DataProtectionController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CryptoLib;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace CryptoWeb.Controllers
{
public class DataProtectionController : Controller
{
private readonly IDataProtectionProvider _dataProtectionProvider;
private readonly ILogger<DataProtectionController> _logger;
public DataProtectionController(IDataProtectionProvider dataProtectionProvider, ILogger<DataProtectionController> logger)
{
_dataProtectionProvider = dataProtectionProvider;
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Encrypt(string plaintext)
{
IDataProtector dp = _dataProtectionProvider.CreateProtector("SecretStuff");
var ciphertext = dp.Protect(plaintext);
ViewBag.Plaintext = plaintext;
ViewBag.Ciphertext = ciphertext;
return View();
}
[HttpPost]
public IActionResult Decrypt(string ciphertext)
{
IDataProtector dp = _dataProtectionProvider.CreateProtector("SecretStuff");
var plaintext = dp.Unprotect(ciphertext);
ViewBag.Ciphertext = ciphertext;
ViewBag.Plaintext = plaintext;
return View();
}
}
}<file_sep>/CryptoLab/CryptoWeb/Controllers/HmacController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using CryptoLib;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace CryptoWeb.Controllers
{
public class HmacController : Controller
{
private readonly IConfiguration _configuration;
private readonly ILogger<HmacController> _logger;
public HmacController(IConfiguration configuration, ILogger<HmacController> logger)
{
_configuration = configuration;
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Generate(string payload)
{
string key = _configuration["Symmetric:Key"];
var hmac = Hmac.Gen(payload, key);
ViewBag.Payload = payload;
ViewBag.HMAC = hmac;
return View();
}
[HttpPost]
public IActionResult Verify(string payload, string hmac)
{
string key = _configuration["Symmetric:Key"];
var calculatedHMAC = Hmac.Gen(payload, key);
ViewBag.Payload = payload;
ViewBag.IncludedHMAC = hmac;
ViewBag.CalculatedHMAC = calculatedHMAC;
bool isVaild = (hmac == calculatedHMAC);
ViewBag.IsValid = isVaild;
return View();
}
}
}<file_sep>/FormsAuth/EComm.Web/Models/ShoppingCart.cs
using EComm.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Http;
using System.Text.Json;
namespace EComm.Web.Models
{
public class ShoppingCart
{
public ShoppingCart()
{
LineItems = new List<LineItem>();
}
public List<LineItem> LineItems { get; set; }
public string FormattedGrandTotal => $"{LineItems.Sum(i => i.TotalCost):C}";
public class LineItem
{
public Product Product { get; set; }
public int Quantity { get; set; }
public decimal TotalCost => Product.UnitPrice.Value * Quantity;
}
public static ShoppingCart GetFromSession(ISession session)
{
byte[] data;
ShoppingCart cart = null;
bool b = session.TryGetValue("ShoppingCart", out data);
if (b) {
string json = Encoding.UTF8.GetString(data);
cart = JsonSerializer.Deserialize<ShoppingCart>(json);
}
return cart ?? new ShoppingCart();
}
public static void StoreInSession(ShoppingCart cart, ISession session)
{
string json = JsonSerializer.Serialize(cart);
byte[] data = Encoding.UTF8.GetBytes(json);
session.Set("ShoppingCart", data);
}
}
}
<file_sep>/EComm/EComm/Controllers/ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EComm.DataAccess;
using EComm.Models;
using Microsoft.AspNetCore.Mvc;
namespace EComm.Controllers
{
public class ProductController : Controller
{
private readonly IRepository _repository;
public ProductController(IRepository repository)
{
_repository = repository;
}
public IActionResult Search(string q)
{
var results = _repository.GetProductsByName(q);
ViewBag.Q = q;
return View(results);
}
public IActionResult Edit(int id)
{
var product = _repository.GetProduct(id);
return View(product);
}
[HttpPost]
public IActionResult Edit(Product product)
{
// save
return RedirectToAction("Index", "Home");
}
}
}<file_sep>/FormsAuth/EComm.Web/Models/ProductEditViewModel.cs
using EComm.Data.Entities;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace EComm.Web.Models
{
public class ProductEditViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "A product must have a name")]
public string ProductName { get; set; }
[Required(ErrorMessage = "A product must have a price")]
[Range(0.0, 500.0, ErrorMessage = "Price of a product must be between 0 and 500")]
public decimal? UnitPrice { get; set; }
public string Package { get; set; }
public bool IsDiscontinued { get; set; }
public int SupplierId { get; set; }
public Supplier Supplier { get; set; }
public IEnumerable<Supplier> Suppliers { get; set; }
public IEnumerable<SelectListItem> SupplierItems =>
Suppliers?.Select(s => new SelectListItem { Text = s.CompanyName, Value = s.Id.ToString() })
.OrderBy(item => item.Text);
}
}
<file_sep>/FormsAuth/EComm.Web/Controllers/ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EComm.Data;
using EComm.Data.Entities;
using EComm.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EComm.Web.Controllers
{
public class ProductController : Controller
{
private readonly IRepository _repository;
private readonly ILogger<ProductController> _logger;
private readonly ISession _session;
public ProductController(IRepository repository,
ILogger<ProductController> logger,
ISession session)
{
_repository = repository;
_logger = logger;
_session = session;
}
[HttpGet("product/{id}")]
public async Task<IActionResult> Details(int id)
{
var product = await _repository.GetProduct(id, includeSupplier: true);
if (product == null) return NotFound();
return View(product);
}
[HttpGet("product/edit/{id}")]
[Authorize(Policy = "AdminsOnly")]
public async Task<IActionResult> Edit(int id)
{
var product = await _repository.GetProduct(id, includeSupplier: true);
var suppliers = await _repository.GetAllSuppliers();
var pvm = new ProductEditViewModel {
Id = product.Id,
ProductName = product.ProductName,
UnitPrice = product.UnitPrice,
Package = product.Package,
IsDiscontinued = product.IsDiscontinued,
SupplierId = product.SupplierId,
Supplier = product.Supplier,
Suppliers = suppliers
};
return View(pvm);
}
[HttpPost("product/edit/{id}")]
[Authorize(Policy = "AdminsOnly")]
public async Task<IActionResult> Edit(int id, ProductEditViewModel pvm)
{
if (!ModelState.IsValid) {
pvm.Suppliers = await _repository.GetAllSuppliers();
return View(pvm);
}
var product = new Product {
Id = id,
ProductName = pvm.ProductName,
UnitPrice = pvm.UnitPrice,
Package = pvm.Package,
IsDiscontinued = pvm.IsDiscontinued,
SupplierId = pvm.SupplierId
};
await _repository.SaveProduct(product);
return RedirectToAction("Details", new { id = id });
}
[HttpPost("product/addtocart/{id}")]
public async Task<IActionResult> AddToCart(int id, int quantity)
{
var product = await _repository.GetProduct(id);
var totalCost = quantity * product.UnitPrice;
string message = $"You added {product.ProductName} " +
$"(x {quantity}) to your cart " +
$"at a total cost of {totalCost:C}.";
var cart = ShoppingCart.GetFromSession(_session);
var lineItem = cart.LineItems.SingleOrDefault(item => item.Product.Id == id);
if (lineItem != null) {
lineItem.Quantity += quantity;
}
else {
cart.LineItems.Add(new ShoppingCart.LineItem {
Product = product,
Quantity = quantity
});
}
ShoppingCart.StoreInSession(cart, _session);
return PartialView("_AddedToCart", message);
}
[HttpGet("product/cart")]
public IActionResult Cart()
{
var cart = ShoppingCart.GetFromSession(HttpContext.Session);
var cvm = new CartViewModel() { Cart = cart };
return View(cvm);
}
[HttpPost("product/checkout")]
public IActionResult Checkout(CartViewModel cvm)
{
if (!ModelState.IsValid) {
cvm.Cart = ShoppingCart.GetFromSession(HttpContext.Session);
return View("Cart", cvm);
}
// TODO: Charge the customer's card and record the order
HttpContext.Session.Clear();
return RedirectToAction("ThankYou");
}
[HttpGet("thankyou")]
public IActionResult ThankYou()
{
return View();
}
}
}<file_sep>/CryptoLab/CryptoLib/Hmac.cs
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace CryptoLib
{
public static class Hmac
{
public static string Gen(string input, string key)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] digestBytes;
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) {
digestBytes = hmac.ComputeHash(inputBytes);
}
return Convert.ToBase64String(digestBytes);
}
public static bool Verify(string input, string digest, string key)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] digestBytes;
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) {
digestBytes = hmac.ComputeHash(inputBytes);
}
string calculatedDigest = Convert.ToBase64String(digestBytes);
Console.WriteLine();
Console.WriteLine("Calculated HMAC: {0}", calculatedDigest);
return digest.Equals(calculatedDigest, StringComparison.Ordinal);
}
}
}
<file_sep>/CryptoLab/CryptoLib/Symmetric.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace CryptoLib
{
public class Symmetric
{
private readonly RijndaelManaged _provider;
private byte[] _key { get; }
public byte[] _iv { get; }
public Symmetric(string key, string iv)
{
_provider = new RijndaelManaged();
_key = Convert.FromBase64String(key);
_iv = Convert.FromBase64String(iv);
}
public byte[] Encrypt(string plaintext)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] cipherBytes;
using (var buf = new MemoryStream()) {
using (var stream = new CryptoStream(buf, _provider.CreateEncryptor(_key, _iv), CryptoStreamMode.Write)) {
stream.Write(clearBytes, 0, clearBytes.Length);
stream.FlushFinalBlock();
}
cipherBytes = buf.ToArray();
}
return cipherBytes;
}
public byte[] Decrypt(string ciphertext)
{
byte[] cipherBytes = Convert.FromBase64String(ciphertext);
byte[] clearBytes;
using (var buf = new MemoryStream()) {
using (var stream = new CryptoStream(buf, _provider.CreateDecryptor(_key, _iv), CryptoStreamMode.Write)) {
stream.Write(cipherBytes, 0, cipherBytes.Length);
stream.FlushFinalBlock();
}
clearBytes = buf.ToArray();
}
return clearBytes;
}
public string GenerateKey()
{
byte[] keyBytes;
using (var rngProvider = new RNGCryptoServiceProvider()) {
keyBytes = new byte[_provider.KeySize / 8];
rngProvider.GetBytes(keyBytes);
}
return Convert.ToBase64String(keyBytes);
}
public string GenerateIV()
{
byte[] ivBytes;
using (var rngProvider = new RNGCryptoServiceProvider()) {
ivBytes = new byte[_provider.BlockSize / 8];
rngProvider.GetBytes(ivBytes);
}
return Convert.ToBase64String(ivBytes);
}
}
}
<file_sep>/EComm/EComm/DataAccess/EFRepository.cs
using EComm.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EComm.DataAccess
{
public class EFRepository : DbContext
{
public EFRepository(DbContextOptions options)
: base(options) { }
public DbSet<Product> Products { get; set; }
}
}
<file_sep>/FormsAuth/EComm.Web/Controllers/AccountController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using EComm.Web.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
namespace EComm.Web.Controllers
{
public class AccountController : Controller
{
[HttpGet("login")]
public IActionResult Login(string ReturnUrl)
{
return View(new LoginViewModel { ReturnUrl = ReturnUrl });
}
[HttpPost("login")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel lvm)
{
if (!ModelState.IsValid) return View(lvm);
bool auth = (lvm.Username == "test" && lvm.Password == "<PASSWORD>");
if (!auth) {
ModelState.AddModelError(string.Empty, "Invalid Login");
return View(lvm);
}
var principal = new ClaimsPrincipal(
new ClaimsIdentity(new List<Claim> {
new Claim(ClaimTypes.Name, lvm.Username),
new Claim(ClaimTypes.Role, "Admin")
}, CookieAuthenticationDefaults.AuthenticationScheme));
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme, principal);
if (lvm.ReturnUrl != null) return LocalRedirect(lvm.ReturnUrl);
return RedirectToAction("Index", "Home");
}
}
}<file_sep>/FormsAuth/EComm.Tests/UnitTest1.cs
using EComm.Data.Entities;
using EComm.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using System;
using Xunit;
namespace EComm.Tests
{
public class UnitTest1
{
[Fact]
public void PassingTest()
{
Assert.Equal(4, (2 + 2));
}
[Fact]
public void ProductDetails()
{
// Arrange
var repository = new StubRepository();
var pc = new ProductController(repository, null, null);
// Act
var result = pc.Details(1).Result;
// Assert
Assert.IsAssignableFrom<ViewResult>(result);
var vr = result as ViewResult;
Assert.IsAssignableFrom<Product>(vr.Model);
var model = vr.Model as Product;
Assert.Equal("Bread", model.ProductName);
}
}
}
<file_sep>/EComm/EComm/DataAccess/Repository.cs
using EComm.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
namespace EComm.DataAccess
{
public interface IRepository
{
List<Product> GetProductsByName(string name);
Product GetProduct(int id);
}
public class Repository : IRepository
{
private readonly string _connStr;
public Repository(string connStr)
{
_connStr = connStr;
}
public List<Product> GetProductsByName(string q)
{
var retVal = new List<Product>();
var conn = new SqlConnection(_connStr);
var sql = "SELECT * FROM Products WHERE ProductName LIKE '" + q + "%'";
var cmd = new SqlCommand(sql, conn);
conn.Open();
var rdr = cmd.ExecuteReader();
while (rdr.Read()) {
retVal.Add(new Product() {
Id = (int)rdr["Id"],
ProductName = (string)rdr["ProductName"],
Package = (string)rdr["Package"]
});
}
conn.Close();
return retVal;
}
public Product GetProduct(int id)
{
Product product = null;
var conn = new SqlConnection(_connStr);
var sql = "SELECT * FROM Products WHERE Id = @Id";
var cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Id", id);
conn.Open();
var rdr = cmd.ExecuteReader();
while (rdr.Read()) {
product = new Product() {
Id = (int)rdr["Id"],
ProductName = (string)rdr["ProductName"]
};
}
conn.Close();
return product;
}
}
}
<file_sep>/FormsAuth/EComm.Tests/StubRepository.cs
using EComm.Data;
using EComm.Data.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace EComm.Tests
{
public class StubRepository : IRepository
{
public Task<IEnumerable<Product>> GetAllProducts(bool includeSuppliers = false)
{
throw new NotImplementedException();
}
public Task<IEnumerable<Supplier>> GetAllSuppliers()
{
throw new NotImplementedException();
}
public Task<Product> GetProduct(int id, bool includeSuppliers = false)
{
var product = new Product {
Id = 1,
ProductName = "Bread",
UnitPrice = 15.00M,
Package = "Bag",
IsDiscontinued = false,
SupplierId = 1
};
if (includeSuppliers) {
product.Supplier = new Supplier {
Id = 1,
CompanyName = "Acme, Inc."
};
}
return Task.Run(() => product);
}
public Task SaveProduct(Product product)
{
throw new NotImplementedException();
}
}
}
<file_sep>/FormsAuth/EComm.Data.EF/ECommDataContext.cs
using EComm.Data.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace EComm.Data.EF
{
public class ECommDataContext : DbContext, IRepository
{
public ECommDataContext(DbContextOptions options)
: base(options) { }
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public async Task<IEnumerable<Product>> GetAllProducts(bool includeSuppliers = false)
{
return includeSuppliers switch
{
false => await Products.ToListAsync(),
true => await Products.Include(p => p.Supplier).ToListAsync()
};
}
public async Task<Product> GetProduct(int id, bool includeSupplier = false)
{
return includeSupplier switch
{
false => await Products.SingleOrDefaultAsync(p => p.Id == id),
true => await Products.Include(p => p.Supplier)
.SingleOrDefaultAsync(p => p.Id == id)
};
}
public async Task<IEnumerable<Supplier>> GetAllSuppliers()
{
return await Suppliers.ToListAsync();
}
public async Task SaveProduct(Product product)
{
Products.Attach(product);
Entry(product).State = EntityState.Modified;
await SaveChangesAsync();
}
}
}
<file_sep>/CryptoLab/CryptoWeb/Controllers/SymmetricController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CryptoLib;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace CryptoWeb.Controllers
{
public class SymmetricController : Controller
{
private readonly IConfiguration _configuration;
private readonly ILogger<SymmetricController> _logger;
public SymmetricController(IConfiguration configuration, ILogger<SymmetricController> logger)
{
_configuration = configuration;
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Encrypt(string plaintext)
{
string key = _configuration["Symmetric:Key"];
string iv = _configuration["Symmetric:IV"];
Symmetric s = new Symmetric(key, iv);
byte[] encryptedBytes = s.Encrypt(plaintext);
ViewBag.Plaintext = plaintext;
ViewBag.EncryptedBytes = Encoding.UTF8.GetString(encryptedBytes);
ViewBag.Ciphertext = Convert.ToBase64String(encryptedBytes);
return View();
}
[HttpPost]
public IActionResult Decrypt(string ciphertext)
{
string key = _configuration["Symmetric:Key"];
string iv = _configuration["Symmetric:IV"];
Symmetric s = new Symmetric(key, iv);
byte[] decryptedBytes = s.Decrypt(ciphertext);
ViewBag.Ciphertext = ciphertext;
ViewBag.Plaintext = Encoding.UTF8.GetString(decryptedBytes);
return View();
}
}
}<file_sep>/FormsAuth/EComm.Web/ViewComponents/ProductList.cs
using EComm.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EComm.Web.ViewComponents
{
public class ProductList : ViewComponent
{
private readonly IRepository _repository;
private readonly ILogger<ProductList> _logger;
public ProductList(IRepository repository, ILogger<ProductList> logger)
{
_repository = repository;
_logger = logger;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var products = await _repository.GetAllProducts(includeSuppliers: true);
return View(products);
}
}
}
<file_sep>/CryptoLab/CryptoLib/Asymmetric.cs
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace CryptoLib
{
public class Asymmetric
{
private RSACryptoServiceProvider _provider;
public Asymmetric()
{
_provider = new RSACryptoServiceProvider();
}
public byte[] Encrypt(string plaintext, string publicKey)
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);
_provider.FromXmlString(publicKey);
byte[] cipherBytes = _provider.Encrypt(plainBytes, true);
return cipherBytes;
}
public byte[] Decrypt(string ciphertext, string privateKey)
{
byte[] cipherBytes = Convert.FromBase64String(ciphertext);
_provider.FromXmlString(privateKey);
byte[] clearBytes = _provider.Decrypt(cipherBytes, true);
return clearBytes;
}
public string[] GenerateKeyPair()
{
string[] keys = new string[2];
keys[0] = _provider.ToXmlString(false);
keys[1] = _provider.ToXmlString(true);
return keys;
}
}
}
<file_sep>/FormsAuth/EComm.Web/API/ProductApiController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EComm.Data;
using EComm.Data.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace EComm.Web.API
{
[ApiController]
public class ProductApiController : ControllerBase
{
private readonly IRepository _repository;
private readonly ILogger<ProductApiController> _logger;
public ProductApiController(IRepository repository,
ILogger<ProductApiController> logger)
{
_repository = repository;
_logger = logger;
}
[HttpGet("api/products")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<List<Product>>> GetProducts()
{
var products = await _repository.GetAllProducts(includeSuppliers: true);
return products.ToList();
}
[HttpGet("api/product/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _repository.GetProduct(id, true);
if (product == null) return NotFound();
return product;
}
[HttpPut("api/product/{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> PutProduct(int id, Product product)
{
if (id != product.Id) return BadRequest();
await _repository.SaveProduct(product);
return NoContent();
}
}
}<file_sep>/FormsAuth/EComm.ClientApp/Program.cs
using EComm.Web.API.gRPC;
using Grpc.Net.Client;
using System;
using System.Threading.Tasks;
namespace EComm.ClientApp
{
class Program
{
static async Task Main(string[] args)
{
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new ECommGrpc.ECommGrpcClient(channel);
var reply = await client.GetProductAsync(new ProductRequest { Id = 5 });
Console.WriteLine($"{reply.Id}, {reply.Name}, {reply.Price}, " +
$"{reply.Package}, {reply.Supplier}");
}
}
}
| 2e02a64b914830af1085a77c02eb36555b87e1ab | [
"JavaScript",
"C#"
] | 26 | C# | ClassroomCode/NI | 03b1ee7ef04ee499b723713c8e671513f43c5b0b | 13751e6e1d504275f821a2a1cae804ed5da6ef85 |
refs/heads/master | <repo_name>Nightstars/cpp_mem<file_sep>/cpp_mem/cpp_mem.cpp
// cpp_mem.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int *p = new int(20);
if (NULL == p) {
system("pause");
return 0;
}
cout << *p << endl;
delete p;
p = NULL;
int* p1 = new int;
if (NULL == p1) {
system("pause");
return 0;
}
*p1 = 30;
cout << *p1 << endl;
delete p1;
p1 = NULL;
int* p2 = new int[1000];
if (NULL == p2)
{
system("pause");
return 0;
}
p2[0] = 10;
p2[1] = 20;
cout << p2[0] << "\t" << p2[1] << endl;
delete[]p2;
p2 = NULL;
system("pause");
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| 8136378ad513c918b33f904248d5793973fd2993 | [
"C++"
] | 1 | C++ | Nightstars/cpp_mem | 4a77c85f9b2434f56ac52652a8c45fc8ad0d0e23 | c5cf4ac260d786c999f3aaf5b254bfde3f6ef088 |
refs/heads/master | <file_sep># coding:utf-8
'''
@author = super_fazai
@File : demo.py
@Time : 2018/7/3 18:26
@connect : <EMAIL>
'''
"""
UUID 是通用唯一识别码(Universally Unique Identifier)的缩写
"""
import uuid
# make a random UUID
print(uuid.uuid1())
print(uuid.uuid4())
# make a UUID using an MD5 hash of a namespace UUID and a name(这样生成的是唯一的识别码)
print(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')) # '6fa459ea-ee8a-3ca4-894e-db77e160355e'
# make a UUID using a SHA-1 hash of a namespace UUID and a name(这样生成的是唯一的识别码)
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')) # '886313e1-3b8a-5372-9b90-0c9aee199e5d'
# make a UUID from a string of hex digits (braces and hyphens ignored)(这样生成的是唯一的识别码)
x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
print(str(x)) # '00010203-0405-0607-0809-0a0b0c0d0e0f'
# get the raw 16 bytes of the UUID
print(x.bytes)
# make a UUID from a 16-byte string
print(uuid.UUID(bytes=x.bytes)) | 0d2347350daba8add5ebb6383d1d1c69ba4e36d3 | [
"Python"
] | 1 | Python | adminafa/python | 1ed3df87720938f1dc646813ff485a89b8790d3f | 4795fe8a507894543e18547bd24d86ec9c7f3814 |
refs/heads/master | <repo_name>JestW/nora<file_sep>/src/Nora/EventBundle/Controller/DefaultController.php
<?php
namespace Nora\EventBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction($count,$firstName)
{
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('EventBundle:Event');
$event = (array(
'name' => '123456'
// 'location' =>'456'
));
return $this->render('EventBundle:Default:index.html.twig', array('name' => $firstName,'count' => $count, 'event' =>$event));
}
}
| c148b2a89602e75a14b813372ee132e3b33ac972 | [
"PHP"
] | 1 | PHP | JestW/nora | d838b807d620a659140b024ced371978f015056f | 9f2fda37323cf45ecb2c0b7cd7aeef262cd5b1f8 |
refs/heads/main | <repo_name>manish202/fashion-hub<file_sep>/myscript.js
$(function(){
$(window).scroll(function(){
var top = $(window).scrollTop();
if(top >= 500){
$('.go-up').slideDown(500);
}else{
$('.go-up').slideUp(500);
}
});
$('.go-up').click(function(){
$(window).scrollTop(0);
});
$('.bar').click(function(){
$(this).toggleClass('active');
$('#nav').toggleClass('movement');
});
$('#email').keyup(function(){
var email = $('#email').val();
if(isValidEmail(email)){
$('#email').removeClass('is-invalid').addClass('is-valid');
}else{
$('#email').removeClass('is-valid').addClass('is-invalid');
}
});
$('#subject').keyup(function(){
var subject = $('#subject').val();
if(subject.length <= 100){
$('#subject').removeClass('is-invalid').addClass('is-valid');
}else{
$('#subject').removeClass('is-valid').addClass('is-invalid');
}
});
});
function isValidEmail(param){
if(param.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)){
return true;
}else{
return false;
}
}
| 67af880fc0c2baa3768582eca08a8816da07a321 | [
"JavaScript"
] | 1 | JavaScript | manish202/fashion-hub | 8a72d1447c2f4927ceae84fcd597163010ea7ca9 | fab2cff9f78179ac5088841393faf22b42fe3af5 |
refs/heads/main | <file_sep>interface Deployable {
type: string
name: string
options: object
}
interface Deployment {
deployables: Record<string, Deployable>
}
type SerializedDeploymentSpec = string
interface LiveDeployment {
name: string
type: string
current: SerializedDeploymentSpec
}
type MaybePromise<T> = T | Promise<T>
interface DeployableType {
// Future: order deployments by dependencies
// getDependencies?: (name: string, options: object) => string[]
deploy: (name: string, options: object) => MaybePromise<SerializedDeploymentSpec>
// Future: update an existing deployment
// update?: (name: string, options: object, current: SerializedDeploymentSpec) => MaybePromise<SerializedDeploymentSpec>
undeploy?: (name: string, current: SerializedDeploymentSpec) => MaybePromise<void>
getInterface?: (name: string, current: SerializedDeploymentSpec) => MaybePromise<any>
}
type DeployableTypeRecord = Record<string, DeployableType>
// Deployable collector
type MarkFn = (typeName: string, name: string, options: MarkOptions) => string
function collect(types: DeployableTypeRecord, (mark: MarkFn) => void): Deployment
// Deploy/update/undeploy
async function deploy(types: DeployableTypeRecord, new_: Deployment /*, current?: DeploymentSpec*/): Promise<DeploymentSpec>
async function undeploy(types: DeployableTypeRecord, current: DeploymentSpec)
<file_sep>
export const assertJSON = object => {
(function recurse (value, path) {
if (value === null || ['string', 'number', 'boolean'].includes(typeof value)) {
return
}
if (typeof value === 'number' && !Number.isNaN(value) && Number.isFinite(value)) {
return
}
if (typeof value === 'object') {
Object.keys(value).forEach(key => {
recurse(value, path.concat(key))
})
return
}
throw new Error(
`Found a non-JSON value at ${path.join('.')}`
)
})(object, ['<passed object>'])
return object
}
<file_sep>import { strict as assert } from 'assert'
import { _collect as collect, deploy } from '../lib/index.js'
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
describe('collect', () => {
it('provides type creators which create temporary refs', () => {
const theType = {}
const typeRec = { theType }
let theRef
collect(typeRec, ({ theType }) => {
theRef = theType('myTypeName', { params: true })
})
assert.deepEqual(theRef, { __ref: 'myTypeName' })
})
it('collects deployments from a typeRec', () => {
const redis = {}
const lambda = {}
const typeRec = {
redis,
lambda
}
const deployment = collect(typeRec, ({ redis, lambda }) => {
const myRedis = redis('myRedis')
lambda('myLambda', { args: [myRedis]})
})
assert.deepEqual(deployment, {
myRedis: { typeName: 'redis', name: 'myRedis', options: undefined },
myLambda: { typeName: 'lambda', name: 'myLambda', options: { args: [{ __ref: 'myRedis' }] } }
})
})
})
describe('deploy', () => {
const makeMockType = () => ({
deploy: async (_, name, options) =>
({ name, options })
})
const typeRec = {
db: makeMockType(),
backend: makeMockType(),
}
const spec = (({ db, backend, frontend }) => {
const myDb = db('myDb')
const myBackend = backend('myBackend', {
args: [db('myDb')]
})
})
it('deploys a deployment spec', async () => {
const { myDb, myBackend } = await deploy(typeRec, spec)
assert.deepEqual(myDb, {
typeName: 'db',
name: 'myDb',
current: { name: 'myDb', options: undefined }
})
assert.deepEqual(myBackend.current, {
name: 'myBackend',
options: {
args: [{__ref: 'myDb'}]
}
})
})
it('provides depend() function to wait for another deployment', async () => {
const deployedOrder = []
let dependData
const typeRec = {
db: {
async deploy(ctx) {
await sleep(5)
deployedOrder.push('db')
}
},
backend: {
async deploy(ctx, _, { args: [db]}) {
dependData = await ctx.depend(db)
deployedOrder.push('backend')
}
}
}
await deploy(typeRec, spec)
assert.deepEqual(deployedOrder, ['db', 'backend'])
assert.deepEqual(dependData, {
typeName: 'db',
name: 'myDb',
current: undefined
})
})
})
| 9c323ef1450d5e0b3246aba1b5a2399daba0841c | [
"JavaScript",
"TypeScript"
] | 3 | TypeScript | fabiosantoscode/scatterbrain-deployments | 9c890ac3bf8bb958f1a6848ae27c3bd3cda3eb72 | a219a0d124629196bb59d1410c8324cee050f609 |
refs/heads/master | <repo_name>SergeyGolenko/UINavigationViewController<file_sep>/SecondViewController.swift
//
// SecondViewController.swift
// UINavigationViewController
//
// Created by <NAME> on 03/08/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "SecondVC"
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true )
self.perform(#selector(goBack ), with: nil, afterDelay: 2.0)
}
@objc func goBack(){
//self.navigationController?.popViewController(animated: true)
// получаем текущий массив контроллеров
var currentViewControllerArray = self.navigationController?.viewControllers
// удаляем последний контроллер
currentViewControllerArray?.removeLast()
// Присваиваю новый контроллер
if let newController = currentViewControllerArray{
self.navigationController?.viewControllers = newController
}
}
}
<file_sep>/UINavigationViewController/ViewController.swift
//
// ViewController.swift
// UINavigationViewController
//
// Created by <NAME> on 30/07/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var displaySecondButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "FirstVC "
self.displaySecondButton = UIButton(type: .system)
self.displaySecondButton.setTitle("SecondVC", for: .normal)
self.displaySecondButton.sizeToFit()
self.displaySecondButton.center = self.view.center
self.view.addSubview(displaySecondButton)
self.displaySecondButton.addTarget(self, action: #selector(showSecondDisplayVC(parametrSender:)), for: .touchUpInside)
}
@objc func showSecondDisplayVC (parametrSender:Any){
let secondVC = SecondViewController()
self.navigationController?.pushViewController(secondVC, animated: true)
}
}
| 65eff418382d2770adad95906c8610555736b67f | [
"Swift"
] | 2 | Swift | SergeyGolenko/UINavigationViewController | 79fdea9884afcd64837c137b9750be46ef327ca5 | 320a2768c5ae23ba0c7e0517cb3f6bbeb0bd8650 |
refs/heads/master | <file_sep>= Summary
* link:chapters/design-principles.adoc[Design Principles]
* link:chapters/chapters/general-guidelines.adoc[General Guidelines]
* link:chapters/security.adoc[Security]
* link:chapters/compatibility.adoc[Compatibility]
* link:chapters/json-guidelines.adoc[JSON Guidelines]
* link:chapters/naming.adoc[API Naming]
* link:chapters/resources.adoc[Resources]
* link:chapters/http.adoc[HTTP]
* link:chapters/performance.adoc[Performance]
* link:chapters/pagination.adoc[Pagination]
* link:chapters/hyper-media.adoc[Hypermedia]
* link:chapters/data-formats.adoc[Data Formats]
* link:chapters/common-data-types.adoc[Common Data Types]
* link:chapters/common-headers.adoc[Common Headers]
* link:chapters/proprietary-headers.adoc[Proprietary Headers]
* link:chapters/deprecation.adoc[Deprecation]
* link:chapters/api-operation.adoc[API Operation]
* link:chapters/events.adoc[Events]
* link:chapters/references.adoc[References]
* link:chapters/tooling.adoc[Tooling]
* link:chapters/changelog.adoc[Changelogs]
<file_sep>:stylesheet: zalando.css
:toc: left
:toclevels: 2
:leveloffset: +1
:sectlinks:
:creator: Zalando SE
:producer: Asciidoctor
:keywords: Zalando, RESTful, API, Guidelines
:copyright: CC-BY-SA 3.0
:MUST: pass:[<span style="color:#bf0000"><strong>MUST</strong></span>]
:SHOULD: pass:[<span style="color:#bfbf00"><strong>SHOULD</strong></span>]
:MAY: pass:[<span style="color:#006000"><strong>MAY</strong></span>]
= Zalando RESTful API Guidelines
Zalando SE
image::assets/api-zalando-small.jpg[API Guild Logo]
Other formats: link:zalando-restful-guidelines.pdf[PDF], link:zalando-restful-guidelines.epub[EPUB3]
include::chapters/introduction.adoc[]
include::chapters/design-principles.adoc[]
include::chapters/general-guidelines.adoc[]
include::chapters/security.adoc[]
include::chapters/compatibility.adoc[]
include::chapters/json-guidelines.adoc[]
include::chapters/naming.adoc[]
include::chapters/resources.adoc[]
include::chapters/http.adoc[]
include::chapters/performance.adoc[]
include::chapters/pagination.adoc[]
include::chapters/hyper-media.adoc[]
include::chapters/data-formats.adoc[]
include::chapters/common-data-types.adoc[]
include::chapters/common-headers.adoc[]
include::chapters/proprietary-headers.adoc[]
include::chapters/deprecation.adoc[]
include::chapters/api-operation.adoc[]
include::chapters/events.adoc[]
include::chapters/references.adoc[]
include::chapters/tooling.adoc[]
include::chapters/changelog.adoc[]
++++
<script>
var ruleIdRegEx = /(\d)+/;
var h3headers = document.getElementsByTagName("h3");
for (var i = 0; i < h3headers.length; i++) {
var header = h3headers[i];
if (header.id && header.id.match(ruleIdRegEx)) {
var a = header.getElementsByTagName("a")[0]
a.innerHTML = "#" + header.id + " " + a.innerHTML;
}
}
</script>
++++
<file_sep>#!/usr/bin/env bash
# Script to build Zalando RESTful Guidelines (static HTML, PDF)
set -ex #print commands, exit on failure
BUILD_DIR=output
rm -rf ${BUILD_DIR}/* #clean
cp -r assets ${BUILD_DIR}/ #copy assets
asciidoctor -D ${BUILD_DIR} index.adoc #generate HTML
asciidoctor-pdf -D ${BUILD_DIR} index.adoc #generate PDF
asciidoctor-epub3 -D ${BUILD_DIR} index.adoc #generate EPUB3
mv ${BUILD_DIR}/index.pdf ${BUILD_DIR}/zalando-restful-guidelines.pdf
mv ${BUILD_DIR}/index.epub ${BUILD_DIR}/zalando-restful-guidelines.epub<file_sep>= Build
== Requirements
* http://asciidoctor.org/docs/install-toolchain/[Install Asciidoctor toolchain]
* Install gems for PDF and EPUB3 generation
** `gem install --pre asciidoctor-pdf`
** `gem install coderay pygments.rb`
** `gem install --pre asciidoctor-epub3`
== Run `./build.sh` to build HTML site, PDF and EPUB3 locally
== Generate Custom CSS
. http://asciidoctor.org/docs/user-manual/#stylesheet-factory[Clone and install]
dependencies of the `asciidoctor-stylesheet-factory`
.. `git clone <EMAIL>:asciidoctor/asciidoctor-stylesheet-factory.git`
.. `cd ${asciidoctor-stylesheet-factory} && bundle install`
. Copy Zalando SASS files to the stylesheet factory's directory
`cp -r ${guidelines-repository}/sass/* ${asciidoctor-stylesheet-factory}/sass`
. Generate CSS
`cd ${asciidoctor-stylesheet-factory} && compass compile`
. Copy generated CSS file
`cp ${asciidoctor-stylesheet-factory}/stylesheets/zalando.css ${guidelines-repository}/zalando.css`
| 51c575ca3dbe0747ffad756690cf66f952867e8c | [
"AsciiDoc",
"Shell"
] | 4 | AsciiDoc | maxim-tschumak/restful-api-guidelines | 9df116e011f151410a32ad3b3f419b7592a2a31e | 7d9617cdd446fdcaedd0328467a583cfaa577e23 |
refs/heads/main | <file_sep>var gulp = require('gulp');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var concat = require('gulp-concat');
var config = {
fontawesomeDir: './bower_components/font-awesome',
publicDir: './assets',
};
// Task for compile css
gulp.task('css', function() {
return gulp.src('sass/app.scss')
.pipe(sass({
includePaths: [config.fontawesomeDir + '/scss'],
includePaths: [config.datepickerDir + '/src/sass'],
includePaths: [config.hoverDir + '/scss'],
outputStyle: 'compressed'
}))
.pipe(gulp.dest(config.publicDir + '/css'));
});
// Task for compile js
gulp.task('scripts', async function(){
gulp.src([
'./bower_components/jquery/dist/jquery.min.js',
'./assets/js/popper.min.js',
'./assets/js/bootstrap.min.js',
'./bower_components/slick-carousel/slick/slick.min.js',
])
.pipe(concat('main.min.js'))
.pipe(uglify())
.pipe(gulp.dest('./assets/js'))
});
// Task for including boostrap fonts
gulp.task('fontsBootstrap', function() {
return gulp.src(config.bootstrapDir + '/assets/fonts/**/*')
.pipe(gulp.dest(config.publicDir + '/fonts'));
});
// Task for including fontawesome
gulp.task('fontsAwesome', function() {
return gulp.src(config.fontawesomeDir + '/fonts/*')
.pipe(gulp.dest(config.publicDir + '/fonts'));
});
gulp.task('default', gulp.series('css', 'scripts', 'fontsBootstrap', 'fontsAwesome'));<file_sep>+(function($) {
'use strict';
if (typeof window.$ === 'undefined' || !window.$)
throw "This theme need jQuery";
/**
//////////////////////////////// * Doc ready //////////////////////////////
*/
$(function() {
});
})(jQuery);
| abf15658e4df4eced644e0c51f38e40e7ec123a1 | [
"JavaScript"
] | 2 | JavaScript | luthfimunadzar/sass-web | 7d0cce17f6965fc2ab43e965210e711da7225265 | f4f5349812f8d373c767c59f5f5c136840212d00 |
refs/heads/master | <file_sep>SELECT GRUPO,SUM(CANTIDADPENDIENTE)CANTIDADPENDIENTE,
SUM(PENDIENTE)PENDIENTE,
SUM(CANCELADO)CANCELADO,
SUM(TOTAL)TOTAL,
SUM(TOTALCARTERAPROP)TOTALCARTERAPROP,
SUM(PENDIENTE)/SUM(TOTALCARTERAPROP)*100 Eficiencia,
SUM(TOTAL)/SUM(TOTALCARTERAPROP)*100 EficienciaInicial
FROM INICIO
GROUP BY GRUPO
<file_sep>SELECT
SUCURSAL,DESCTIPO,
SUM(CANTIDADPENDIENTE) CANTIDADPENDIENTE,
ROUND(SUM(PENDIENTE)) PENDIENTE,
SUM(CANTIDADCANCELADO),
ROUND(SUM(CANCELADO)) CANCELADO,
ROUND(SUM(TOTAL)) TOTAL,
SUM(TOTALCARTERA) TOTALCARTERA,
SUM(CANCELADO)/SUM(TOTAL)*100 RECUPERO,
SUM(PENDIENTE)/SUM(TOTALCARTERA)*100 Eficiencia,
SUM(TOTAL)/SUM(TOTALCARTERA)*100 EFICIENCIA_INICIAL
FROM HSTREPORTE2 WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()))
GROUP BY SUCURSAL,DESCTIPO;
<file_sep>/*blanqueo las passwords nuevas*/
UPDATE USUARIOS SET PASSWORD=SHA1(UPPER(CODIGO)) WHERE PASSWORD='';
/*crea sucursales en espejo*/
UPDATE USUARIOPERFILES_TMP SET VETRAMOCOMPLETO=1 WHERE TOPE=1;
/*agrego supervisores*/
/*Puede dar cero registros actualizados.*/
INSERT INTO SUPERVISORUSUARIOS SELECT (SELECT IDUSUARIO FROM USUARIOS WHERE codigo='SUPGAR'),IDUSUARIO,1 FROM USUARIOS WHERE CODIGO LIKE 'GAR%' AND IDUSUARIO NOT IN (SELECT IDUSUARIO FROM SUPERVISORUSUARIOS);
INSERT INTO SUPERVISORUSUARIOS SELECT (SELECT IDUSUARIO FROM USUARIOS WHERE codigo='ARGSUP'),IDUSUARIO,1 FROM USUARIOS WHERE CODIGO LIKE 'ARG%' AND IDUSUARIO NOT IN (SELECT IDUSUARIO FROM SUPERVISORUSUARIOS);
INSERT INTO SUPERVISORUSUARIOS SELECT (SELECT IDUSUARIO FROM USUARIOS WHERE codigo='SUPwpc'),IDUSUARIO,1 FROM USUARIOS WHERE CODIGO LIKE 'WPC%' AND IDUSUARIO NOT IN (SELECT IDUSUARIO FROM SUPERVISORUSUARIOS);
<file_sep>varLog=/home/callcenter/interfaz/proceso/logs/legalesLog.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
from="<EMAIL>"
queries=/home/callcenter/interfaz/proceso/queries
legalesProcesar=/home/callcenter/interfaz/legales
procesados=/home/callcenter/interfaz/procesados
proceso=/home/callcenter/interfaz/proceso
legalesProcesados=/home/callcenter/interfaz/procesados/legales
errorMensaje=/home/callcenter/interfaz/proceso/archivos/mensajeErrorDirectorioVacio.txt
archivos=/home/callcenter/interfaz/proceso/archivos/
legales1=/home/callcenter/interfaz/legales/legales1
legales2=/home/callcenter/interfaz/legales/legales2
temporalLegales=/home/callcenter/interfaz/proceso/archivos/temporalLegales.txt
temporalLegales2=/home/callcenter/interfaz/proceso/archivos/temporalLegales2.txt
queryGenericaIn=$queries/genericaLegalesIn.sql
queryGenericaNotIn=$queries/genericaLegalesNotIn.sql
reportes=/home/callcenter/interfaz/proceso/reportes
archivoIn=$archivos/ultimaFechaGuardadaLegalesIn.txt
archivoNotIn=$archivos/ultimaFechaGuardadaLegalesNotIn.txt
eMail=/home/callcenter/interfaz/proceso/eMailReporte.sh
appendearArchivos()
{
echo "$(cat $1)" > $temporalLegales
echo "$(cat $2)" >>$temporalLegales
}
cargarRegistrosEnTabla()
{
#Borro todo el contenido de la tabla
mysql -se "DELETE FROM legales_registros_copy;"
#Cargo la tabla con las cosas del mes
for i in $(cat $temporalLegales)
do
numeroAInsertar=$(echo -e "'$i'")
#mysql -se "INSERT INTO legales_registros_copy VALUES (NULL,$numeroAInsertar, (SELECT CURDATE() FROM DUAL));"
mysql -se "INSERT INTO legales_registros_copy VALUES (NULL,$numeroAInsertar);"
done
}
chequearCantidadDeArchivos()
{
#ambos existen
if [[ -f $legales1 && -f $legales2 ]]
then
appendearArchivos $legales1 $legales2
echo -e "===============================\n$(date +%d/%m/%Y----%H.%M)\nSe generará el reporte, se encontraron los archivos legales1 y legales2.\n===============================">>$varLog
#solo existe el 1
else if [ -f $legales1 ]
then
echo -e "===============================\n$(date +%d/%m/%Y----%H.%M)\nSe generará el reporte pero solo se encontró el archivo legales1.\n===============================">>$varLog
echo "$(cat $legales1 )" > $temporalLegales
#solo existe el 2
else if [ -f $legales2 ]
then
echo -e "===============================\n$(date +%d/%m/%Y----%H.%M)\nSe generará el reporte pero solo se encontró el archivo legales2.\n===============================">>$varLog
echo "$(cat $legales2)" > $temporalLegales
#no hay archivos
else
echo -e "===============================\n$(date +%d/%m/%Y----%H.%M)\nNo se encontraron los archivos legales1 ni legales2, no se generará ningun reporte.\n===============================">>$varLog
exit 1
fi
fi
fi
}
comprobarErrores ()
{
#El parametro 3 es el nombre del script ejecutado y el parametro 2 es la direccion donde se encuentra el log, parametro 1 es $?
if [ $1 -eq 0 ]
then
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nSe ejecuto correctamente $3\n==============================="
echo -e $mensajeLog >> $2
else
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nHubo un error al ejecutar $3\n==============================="
echo -e "$mensajeLog" >> $2
fi
}
generarReporte ()
{
query=$(cat $1)
fecha=$(date +%d-%m-%Y-%H.%M)
echo $fecha > $3
#Esto te pide como primer parametro la query a ejecutar de la carpeta queries, y como segundo parametro el string para generar el reporte
mysql -se "$query" > /home/callcenter/interfaz/proceso/reportes/$2$fecha.xls
error=$?
comprobarErrores $error $varLog $2
# mandarMailLog $error $2 <EMAIL>
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$2" -r "$from" <EMAIL>
# echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$2" -r "$from" <EMAIL>
}
filtrarMovidaDeArchivos()
{
for i in $(ls $procesar)
do
if [ -f $i ]
then
mv $i $procesados
fi
done
}
generarReportes()
{
generarReporte $queryGenericaIn "Reporte_Legales_In" $archivoIn
generarReporte $queryGenericaNotIn "Reporte_Legales_NotIn" $archivoNotIn
}
mandarMail()
{
ultimaFechaIn=$(cat $archivoIn)
ultimaFechaNotIn=$(cat $archivoNotIn)
tar -czvf $reportes/$ultimaFechaNotIn-Reporte_Legales.tar.gz -C $reportes Reporte_Legales_In$ultimaFechaIn.xls Reporte_Legales_NotIn$ultimaFechaNotIn.xls
$eMail 4 <EMAIL> "[CallMora]-Reporte_de_Legales" $reportes/$ultimaFechaNotIn-Reporte_Legales.tar.gz
}
moverYRenombrarArchivosOriginales()
{
fecha=$(date +%d-%m-%Y-%H.%M)
mv $legales1 $legalesProcesados/legales1_$fecha
mv $legales2 $legalesProcesados/legales2_$fecha
}
verificarSiEsFechaDeLegales()
{
dia=$(date +%D | cut -d "/" -f 2)
if [ $dia -lt 5 ]
then
exit 1
fi
}
verificarSiEsFechaDeLegales
chequearCantidadDeArchivos
cargarRegistrosEnTabla
generarReportes
mandarMail
moverYRenombrarArchivosOriginales
<file_sep>insert into USUARIOPERFILES_TMP_Backup select IDUSUARIOPERFILES,IDUSUARIO,IDGRUPO,IDPERFIL,IDSUCURSAL,FACTOR,
TOPEPTF,TOPE,VETRAMOCOMPLETO,FECHAALTA,FECHABAJA,ESTADO,now()
from USUARIOPERFILES_TMP;<file_sep><?php
include('../../htdocs/conndb/conndb.php');
//Inicializa Variables de URL
$serviceName="Pago Facil";
$protocol="https://";
$ipUrl="www.e-pagofacil.com";
$port=443;
$call="/2130/index.php";
$URLsola = $protocol.$ipUrl;
$SELECT= "select * from pago_facil_queue pe where pe.status=0 ";
$result = mysql_query($SELECT, $conn );
while ($row = mysql_fetch_array($result)){
$txtURL = $protocol.$ipUrl.$call;
$txtURL .="?p_id_emec=".$row['p_id_emec'];
$txtURL .="&p_id_operacion=".$row['p_id_operacion'];
$txtURL .="&p_id_mone_ecom=".$row['p_id_mone_ecom'];
$txtURL .="&p_va_monto=".$row['p_va_monto'];
$txtURL .="&p_fe_transaccion=".$row['p_fe_transaccion'];
$txtURL .="&p_fe_hora=".$row['p_fe_hora'];
$txtURL .="&p_dias_vigencia=".$row['p_dias_vigencia'];
$txtURL .="&p_direccion_email_usua=".$row['p_direccion_email_usua'];
$txtURL .="&p_nombre_usuario=".$row['p_nombre_usuario'];
$txtURL .="&p_apellido_usuario=".$row['p_apellido_usuario'];
$txtURL .="&p_domicilio_usuario=".$row['p_domicilio_usuario'];
$txtURL .="&p_localidad_usuario=".$row['p_localidad_usuario'];
$txtURL .="&p_provincia_usuario=".$row['p_provincia_usuario'];
$txtURL .="&p_pais_usuario=".$row['p_pais_usuario'];
$txtURL .="&p_direccion_email_alter=".$row['p_direccion_email_alter'];
echo $txtURL;
exec ('wget -O salida --no-check-certificate "'.$txtURL.'"');
$sql="update pago_facil_queue set status=1 where idPFacil=".$row['idPFacil'];
mysql_query($sql, $conn );
}
?>
<file_sep>SELECT
GRUPO,
SUM(CANTIDADPENDIENTE) CANTIDADPENDIENTE,
ROUND(SUM(PENDIENTE)) PENDIENTE,
SUM(CANTIDADCANCELADO)CANTIDADCANCELADO,
ROUND(SUM(CANCELADO)) CANCELADO,
SUM(CANTIDADTOTAL)CANTIDADTOTAL,
ROUND(SUM(TOTAL)) TOTAL,
SUM(TOTALCARTERAPROP) TOTALCARTERA,
SUM(CANCELADO)/SUM(TOTAL)*100 RECUPERO,
SUM(PENDIENTE)/SUM(TOTALCARTERAPROP)*100 Eficiencia,
SUM(TOTAL)/SUM(TOTALCARTERAPROP)*100 EFICIENCIA_INICIAL
FROM HSTREPORTE1_DIARIA WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()))
GROUP BY GRUPO;<file_sep>archivos=/home/callcenter/interfaz/proceso/archivos
queries=/home/callcenter/interfaz/proceso/queries
reportes=/home/callcenter/interfaz/proceso/reportes
from="<EMAIL>"
varLog=/home/callcenter/interfaz/proceso/logs/reportes_log.txt
paso1=$queries/reporte1_CierrePorUsuario.sql
paso2=$queries/reporte2_CierrePorGrupo.sql
paso3=$queries/reporte3_CierrePorSucursal.sql
eMail=/home/callcenter/interfaz/proceso/eMailReporte.sh
archivo1=$archivos/ultimaFechaGuardadaCierre1.txt
archivo2=$archivos/ultimaFechaGuardadaCierre2.txt
archivo3=$archivos/ultimaFechaGuardadaCierre3.txt
comprobarErrores ()
{
#El parametro 3 es el nombre del script ejecutado y el parametro 2 es la direccion donde se encuentra el log, parametro 1 es $?
if [ $1 -eq 0 ]
then
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nSe ejecuto correctamente $3\n==============================="
echo -e $mensajeLog >> $2
else
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nHubo un error al ejecutar $3\n==============================="
echo -e "$mensajeLog" >> $2
fi
}
mandarMailAResponsablesReporteLog ()
{
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$1" -r "$from" <EMAIL>
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$1" -r "$from" <EMAIL>
}
generarReporte ()
{
query=$(cat $1)
fecha=$(date +%d-%m-%Y-%H.%M)
echo $fecha > $3
#Esto te pide como primer parametro la query a ejecutar de la carpeta queries, y como segundo parametro el string para generar el reporte
mysql -se "$query" > /home/callcenter/interfaz/proceso/reportes/$2$fecha.xls
error=$?
comprobarErrores $error $varLog $2
mandarMailAResponsablesReporteLog $2
}
ejecutarQuery ()
{
query=$(cat $1)
mysql -se "$query"
}
mandarMailAResponsablesReporte ()
{
$eMail 3 <EMAIL> "[CallMora]-Reporte_de_Cierre" $reportes/Reporte_Cierre_Por_Usuario$ultimaFecha1.xls $reportes/Reporte_Cierre_Por_Grupo$ultimaFecha2.xls $reportes/Reporte_Cierre_Por_Sucursal$ultimaFecha3.xls
$eMail 3 <EMAIL> "[CallMora]-Reporte_de_Cierre" $reportes/Reporte_Cierre_Por_Usuario$ultimaFecha1.xls $reportes/Reporte_Cierre_Por_Grupo$ultimaFecha2.xls $reportes/Reporte_Cierre_Por_Sucursal$ultimaFecha3.xls
$eMail 3 <EMAIL> "[CallMora]-Reporte_de_Cierre" $reportes/Reporte_Cierre_Por_Usuario$ultimaFecha1.xls $reportes/Reporte_Cierre_Por_Grupo$ultimaFecha2.xls $reportes/Reporte_Cierre_Por_Sucursal$ultimaFecha3.xls
$eMail 3 <EMAIL> "[CallMora]-Reporte_de_Cierre" $reportes/Reporte_Cierre_Por_Usuario$ultimaFecha1.xls $reportes/Reporte_Cierre_Por_Grupo$ultimaFecha2.xls $reportes/Reporte_Cierre_Por_Sucursal$ultimaFecha3.xls
#$eMail 3 <EMAIL> "[CallMora]-Reporte_de_Cierre" $reportes/Reporte_Cierre_Por_Usuario$ultimaFecha1.xls $reportes/Reporte_Cierre_Por_Grupo$ultimaFecha2.xls $reportes/Reporte_Cierre_Por_Sucursal$ultimaFecha3.xls
}
generarReporte $paso1 Reporte_Cierre_Por_Usuario $archivo1
generarReporte $paso2 Reporte_Cierre_Por_Grupo $archivo2
generarReporte $paso3 Reporte_Cierre_Por_Sucursal $archivo3
ultimaFecha1=$(cat $archivo1)
ultimaFecha2=$(cat $archivo2)
ultimaFecha3=$(cat $archivo3)
mandarMailAResponsablesReporte<file_sep>host="10.88.1.32"
user="callcenter"
pass="<PASSWORD>"
query=$(cat /home/callcenter/interfaz/proceso/queries/$1)
fecha=$(date +%d-%m-%Y-%H.%M)
comprobarErrores=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
varLog=/home/callcenter/interfaz/proceso/logs/reportes_log.txt
mandarMailLog=/home/callcenter/interfaz/proceso/mailingReportes.sh
echo $fecha > $3
#Esto te pide como primer parametro la query a ejecutar de la carpeta queries, y como segundo parametro el string para generar el reporte
mysql -D $host -u $user -p $pass -se "$query" > /home/callcenter/interfaz/proceso/reportes/$2$fecha.xls
error=$?
$comprobarErrores $error $varLog $2
$mandarMailLog $error $2
<file_sep>SELECT COUNT(*) FROM DISTRIBUCION;<file_sep>host=10.88.1.32
user=callcenter
pass=<PASSWORD>
query=$(cat $1)
mysql -D $host -u $user -p $pass -se "$query"<file_sep>comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
varLog=/home/callcenter/interfaz/proceso/logs/php_log.txt
cd /home/callcenter/interfaz/proceso
/usr/bin/php totales.php
comprobar $? $varLog totales.php
cd /home/callcenter/interfaz/procesar
mv a* ../auxiliar/
mv * ../procesados
mv ../auxiliar/* ./
gunzip *.gz
cd ../proceso
/usr/bin/php interfaz.php
comprobar $? $varLog interfaz.php
# /usr/bin/php ccext_gering_out.php
# comprobar $? $varLog ccext_gering_out.php
/usr/bin/php ccext_contactogarantido_in.php
comprobar $? $varLog ccext_contactogarantido_in.php
/usr/bin/php ccext_contactogarantido_out.php
comprobar $? $varLog ccext_contactogarantido_out.php
# /usr/bin/php ccext_contactogarantido_out_send.php
# comprobar $? $varLog ccext_contactogarantido_out_send.php
# cd /home/callcenter/
# /usr/bin/php distribucion.php
# comprobar $? $varLog distribucion.php
#SI SE VA A DESCOMENTAR ccext_gering_out.php o ccext_contactogarantido_out_send.php tambien hacerlo con los echo mas abajo para que quede su corrida en el LOG
<file_sep>SELECT flagNecesarioParaEjecutarCierre FRoM fechas_cierre where fecha=date_add('<file_sep><?
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** CUSTOM DATA ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// EXT: Código de Call Center Externo
$EXT = "1";
// idusuario
$IDUSUARIO = "GAR%";
// local path
$PATH = "/home/callcenter/interfaz/cc_externo/contactogarantido/out/";
$SENTPATH = "/home/callcenter/interfaz/cc_externo/contactogarantido/out/sent/";
// log
$LOG = "/home/callcenter/interfaz/cc_externo/contactogarantido/log/send.log";
// sftp
$SFTP = 1;
$SFTPSERVER = "192.168.3.11";
$SFTPPORT = "18024";
$SFTPUSER = "fvgdatos";
$SFTPPASS = "<PASSWORD>";
$SFTPPATH = "/inbox/";
// ftp
$FTPSERVER = "ftp.contactogarantido.com";
$FTPUSER = "fravega";
$FTPPASS = "<PASSWORD>";
$FTPPATH = "/inbox/";
//zip extension
$ZIPEXT = ".tar.gz";
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** CUSTOM DATA ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// include
include("/home/callcenter/htdocs/conndb/conndb.php");
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/callcenter/htdocs/phplib/phpseclib/');
include('Net/SFTP.php');
// date
$DATE = date("Ymd",time());
// files
$FILE['CARTERA'] = "CARTERA_".$DATE.".txt";
$FILE['MOROSOS'] = "MOROSOS_".$DATE.".txt";
$FILE['TELEFONOS'] = "TELEFONOS_".$DATE.".txt";
$FILE['REFERENCIAS'] = "REFERENCIAS_".$DATE.".txt";
$FILE['DIRECCIONES'] = "DIRECCIONES_".$DATE.".txt";
$FILE['EMPLEOS'] = "EMPLEOS_".$DATE.".txt";
$FILE['CREDITOS'] = "CREDITOS_".$DATE.".txt";
$FILE['PRODUCTOS'] = "PRODUCTOS_".$DATE.".txt";
$FILE['SEGUIMIENTO'] = "SEGUIMIENTO_".$DATE.".txt";
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ LOG ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
function savelog($msg) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - $msg\r\n" );
@fclose($handle);
}
}
function errorlog($type, $info, $file, $row) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - ERR --> $type: $info FILE: $file - Row $row\r\n" );
@fclose($handle);
}
}
set_error_handler(errorlog, E_USER_ERROR);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ LOG ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ atrsucMCV *************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
//$execOut = shell_exec('cp /home/callcenter/interfaz/data/'.$FILE['ATRSUCMCV'].' '.$PATH.'');
//savelog('atrsucMCV: '.$execOut);
$atrsucMCVfile = trim(shell_exec('ls -ABrt1 /home/callcenter/interfaz/data/atrsucMCV*| tail -n1'));
$FILE['ATRSUCMCV'] = trim(shell_exec('basename '.$atrsucMCVfile));
savelog('ATRSUCMCV FILE: '.$FILE['ATRSUCMCV']);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ atrsucMCV ** **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** SEGUIMIENTO ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// if file does not exist, join files into single large file
if (!file_exists($PATH.$FILE['SEGUIMIENTO'])) {
$execOut = exec("cat ".$PATH."tmp/".$FILE['SEGUIMIENTO'].".".str_pad($i,5,"0", STR_PAD_LEFT)." > ".$PATH.$FILE['SEGUIMIENTO'] ,$execOut);
savelog('JOIN: '.$execOut[0]);
}
$execOut = exec("rm -rf ".$PATH."tmp/*".$DATE.".* ");
savelog('DEL tmp: '.$execOut);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** SEGUIMIENTO ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** TAR *************/ // tar --remove-files
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// tar/gzip files
passthru('/bin/tar -cvf '.$PATH.$DATE.'.tar --files-from /dev/null',$execOut);
savelog('TAR CREATE FILE '.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['CARTERA'],$execOut);
savelog('TAR CARTERA (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['CARTERA'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['MOROSOS'],$execOut);
savelog('TAR MOROSOS (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['MOROSOS'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['TELEFONOS'],$execOut);
savelog('TAR TELEFONOS (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['TELEFONOS'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['REFERENCIAS'],$execOut);
savelog('TAR REFERENCIAS (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['REFERENCIAS'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['DIRECCIONES'],$execOut);
savelog('TAR DIRECCIONES (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['DIRECCIONES'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['EMPLEOS'],$execOut);
savelog('TAR EMPLEOS (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['EMPLEOS'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['CREDITOS'],$execOut);
savelog('TAR CREDITOS (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['CREDITOS'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['PRODUCTOS'],$execOut);
savelog('TAR PRODUCTOS (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['PRODUCTOS'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['SEGUIMIENTO'],$execOut);
savelog('TAR SEGUIMIENTO (/bin/tar -rvf '.$PATH.$DATE.'.tar -C'.$PATH.' '.$FILE['SEGUIMIENTO'].'):'.$execOut);
passthru('/bin/tar -rvf '.$PATH.$DATE.'.tar -C/home/callcenter/interfaz/data/ '.$FILE['ATRSUCMCV'],$execOut);
savelog('TAR ATRSUCMCV (/bin/tar -rvf '.$PATH.$DATE.'.tar -C/home/callcenter/interfaz/data/ '.$FILE['ATRSUCMCV'].'): '.$execOut);
exec("/bin/gzip ".$PATH.$DATE.".tar",$execOut);
savelog('GZIP: '.$execOut[0]);
$execOut = exec("rm -rf ".$PATH."*".$DATE.".txt ");
savelog('DEL TXT: '.$execOut);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** tar *************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** SFTP ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// connect to SFTP server (port 22)
if ($SFTP) {
$sftp = new Net_SFTP($SFTPSERVER, $SFTPPORT);
if (!$sftp->login($SFTPUSER, $SFTPPASS)) {
savelog('ERR SFTP CONNECT: '.$SFTPSERVER);
$SFTP = 0;
} else {
savelog('OK SFTP CONNECT: '.$SFTPSERVER);
$sftp->chdir($SFTPPATH);
savelog(((!$sftp->put($DATE.$ZIPEXT, $PATH.$DATE.$ZIPEXT, NET_SFTP_LOCAL_FILE)) ? 'ERR SFTP: ':'OK SFTP:').$DATE.$ZIPEXT);
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** SFTP ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ FTP ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// connect to FTP server (port 21)
if (!$SFTP) {
$conn_id = ftp_connect($FTPSERVER, 21);
savelog(((!$conn_id) ? 'ERR FTP: ':'OK FTP: ').$FTPSERVER);
if ($conn_id) {
// send access parameters
ftp_login($conn_id, $FTPUSER, $FTPPASS);
// turn on passive mode transfers
ftp_pasv ($conn_id, true);
$arr_size=count($FILE);
// perform file upload
$upload = ftp_put($conn_id, $FTPPATH.$DATE.$ZIPEXT, $PATH.$DATE.$ZIPEXT, FTP_BINARY);
// check upload status:
savelog(((!$upload) ? 'ERR FTP: ':'OK FTP: ').$DATE.$ZIPEXT);
// close the FTP stream
ftp_close($conn_id);
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ FTP ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** MOVE ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// move files to sent folder
//savelog(((!rename($PATH.$DATE.$ZIPEXT, $SENTPATH.$DATE.$ZIPEXT)) ? 'ERR MOVE: ':'OK MOVE: ').$DATE.$ZIPEXT);
exec("mv ".$PATH.$DATE.".tar.gz ".$SENTPATH.$DATE.".tar.gz",$execOut);
savelog('MOVE: '.$execOut[0]);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** MOVE ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
?>
<file_sep>generarMensaje ()
{
fecha=$(date +%d-%m-%Y)
hora=$(date +%H.%M)
mensaje=/home/callcenter/interfaz/proceso/archivos/mensajePlantillaReporteCierre.txt
echo -e "Estimados, adjuntamos los reportes correspondientes a la cierre de las cobranzas del mes en curso, generados el dia $fecha a las $hora HS.\n\nSaludos\n\nSistemas-Call Mora" >$mensaje
}
generarMensajeTxt ()
{
plantilla=/home/callcenter/interfaz/proceso/archivos/mensajePlantillaReporteCierre.txt
generarMensaje > $plantilla
mensaje=$(cat $plantilla)
}
mandarReportesEmail ()
{
archivos=/home/callcenter/interfaz/proceso/archivos
plantilla=$archivos/mensajePlantillaReporteCierre.txt
from="<EMAIL>"
# more receiver like <EMAIL> <EMAIL> ...
to="$1"
subject="$2"
#you can also read content from the file just use $(cat yourfile)
j=1
generarMensajeTxt
for i in $(seq 3 $#);
do
files[$j]=$(echo $@ | cut -d " " -f $i)
let j=j+1
done
for att in "${files[@]}"; do
[ ! -f "$att" ] && echo "Warning: attachment $att not found, skipping" >&2 && continue
attargs+=( "-a" "$att" )
done
cat $plantilla | mail -s "$subject" -r "$from" "${attargs[@]}" "$to"
}
mandarReportesEmail $@
<file_sep><?
date_default_timezone_set ('America/Argentina/Buenos_Aires');
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** CUSTOM DATA ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// EXT: Código de Call Center Externo
$EXT = "1";
// local path
$PATH = "/home/callcenter/interfaz/cc_externo/contactogarantido/in/";
$SENTPATH = "/home/callcenter/interfaz/cc_externo/contactogarantido/in/processed/";
$TARFILE = "fvg_";
// log
$LOG = "/home/callcenter/interfaz/cc_externo/contactogarantido/log/in.log";
// sftp
$SFTP = 1;
$SFTPSERVER = "192.168.3.11";
$SFTPPORT = "18024";
$SFTPUSER = "fvgdatos";
$SFTPPASS = "<PASSWORD>";
$SFTPPATH = "/outbox/";
// ftp
$FTPSERVER = "ftp.contactogarantido.com";
$FTPUSER = "fravega";
$FTPPASS = "<PASSWORD>";
$FTPPATH = "/outbox/";
//zip extension
$ZIPEXT = ".tar.gz";
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** CUSTOM DATA ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// include
include("/home/callcenter/htdocs/conndb/conndb.php");
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/callcenter/htdocs/phplib/phpseclib/');
include('Net/SFTP.php');
// date
$DATE = date("Ymd",time());
$DATEINV = $DATE; //date("dmY",time());
// files
$FILE['TELEFONOS'] = "TELEFONOS_".$DATE.".txt";
$FILE['REFERENCIAS'] = "REFERENCIAS_".$DATE.".txt";
$FILE['DIRECCIONES'] = "DIRECCIONES_".$DATE.".txt";
$FILE['EMPLEOS'] = "EMPLEOS_".$DATE.".txt";
$FILE['SEGUIMIENTO'] = "SEGUIMIENTO_".$DATE.".txt";
// line length
$FILELENGTH['TELEFONOS'] = 605;
$FILELENGTH['REFERENCIAS'] = 572;
$FILELENGTH['DIRECCIONES'] = 1348;
$FILELENGTH['EMPLEOS'] = 1891;
$FILELENGTH['SEGUIMIENTO'] = 8324;
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ LOG ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
function savelog($msg) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - $msg\r\n" );
@fclose($handle);
}
}
function errorlog($type, $info, $file, $row) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - ERR --> $type: $info FILE: $file - Row $row\r\n" );
@fclose($handle);
}
}
set_error_handler(errorlog, E_USER_ERROR);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ LOG ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** SFTP ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// connect to SFTP server (port 22)
if ($SFTP) {
$sftp = new Net_SFTP($SFTPSERVER, $SFTPPORT);
if (!$sftp->login($SFTPUSER, $SFTPPASS)) {
savelog('ERR SFTP CONNECT: '.$SFTPSERVER);
//$SFTP = 0;
} else {
savelog('OK SFTP CONNECT: '.$SFTPSERVER);
$sftp->chdir($SFTPPATH);
savelog(((!$sftp->get($TARFILE.$DATEINV.$ZIPEXT, $PATH.$TARFILE.$DATEINV.$ZIPEXT)) ? 'ERR SFTP: ':'OK SFTP:').$TARFILE.$DATEINV.$ZIPEXT);
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** SFTP ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ FTP ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// connect to FTP server (port 21)
if (!$SFTP) {
$conn_id = ftp_connect($FTPSERVER, 21);
savelog(((!$conn_id) ? 'ERR FTP: ':'OK FTP: ').$FTPSERVER);
if ($conn_id) {
// send access parameters
ftp_login($conn_id, $FTPUSER, $FTPPASS);
// turn on passive mode transfers
ftp_pasv ($conn_id, true);
// change ftp dir
ftp_chdir($conn_id,$FTPPATH);
// change local dir
$CURDIR = getcwd();
chdir($PATH);
// perform file download
$upload = ftp_get($conn_id, $TARFILE.$DATEINV.$ZIPEXT, $TARFILE.$DATEINV.$ZIPEXT, FTP_BINARY);
// check upload status:
savelog(((!$upload) ? 'ERR FTP: ':'OK FTP: ').$TARFILE.$DATEINV.$ZIPEXT);
// close the FTP stream
ftp_close($conn_id);
// change local dir
chdir($CURDIR);
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ FTP ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** TAR *************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
shell_exec("rm -fR ".$PATH.$TARFILE.$DATEINV.";");
if (file_exists($PATH.$TARFILE.$DATEINV.$ZIPEXT)) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV.$ZIPEXT);
// tar/gzip files
shell_exec("cd ".$PATH."; mkdir ".$TARFILE.$DATEINV."; tar -xvf ".$TARFILE.$DATEINV.$ZIPEXT." -C ".$TARFILE.$DATEINV);
shell_exec("mv -f ".$PATH.$TARFILE.$DATEINV.$ZIPEXT." ".$PATH."/proc;");
} else {
savelog("ERR FILE NOT EXISTS: ".$PATH.$TARFILE.$DATEINV.$ZIPEXT);
return;
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** TAR *************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******* FILES EXIST *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*
foreach($FILE as $i => $v) {
if (file_exists($PATH.$TARFILE.$DATEINV."/".$FILE[$i])) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE[$i]);
} else {
savelog("ERR FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE[$i]);
return;
}
}
*/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******* FILES EXIST *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/****** LINES LENGTH *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
foreach($FILE as $i => $v) {
$tmpfile = $PATH.$TARFILE.$DATEINV."/".$FILE[$i];
$tmphandle = @fopen($tmpfile, "r");
$tmperror[$i] = 0;
if ($tmphandle) {
$cnt = 0;
while (!feof($tmphandle) && !$tmperror[$i]) {
$cnt++;
$tmpline = str_replace(array("\n","\r\n"), '', fgets($tmphandle));
if ($tmpline) {
if (strlen($tmpline) != $FILELENGTH[$i]) $tmperror[$i] = strlen($tmpline);
}
}
}
fclose($tmphandle);
if (!$tmperror[$i]) {
savelog("OK LINES LENGHT [".$FILELENGTH[$i]."]: ".$PATH.$TARFILE.$DATEINV."/".$FILE[$i]);
} else {
savelog("ERR LINES LENGHT [".$FILELENGTH[$i]."/".$tmperror[$i]." - ".$cnt."]: ".$PATH.$TARFILE.$DATEINV."/".$FILE[$i]);
}
}
foreach($tmperror as $i => $v) {
if ($tmperror[$i]) {
savelog("EXIT");
return;
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/****** LINES LENGTH *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************** TELEFONOS **************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
if (file_exists($PATH.$TARFILE.$DATEINV."/".$FILE['TELEFONOS'])) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['TELEFONOS']);
// create temporary table
$SQL = "CREATE TEMPORARY TABLE IMPORT_CALLEXT_TELEFONOS_".$DATE." (
IDTELEFONO int(11) unsigned NOT NULL,
IDCONTACTO int(11) unsigned NOT NULL DEFAULT '0',
TIPO int(11) unsigned NOT NULL DEFAULT '0',
CODIGOAREA int(11) unsigned DEFAULT NULL,
NUMERO int(11) unsigned DEFAULT NULL,
INTERNO int(11) unsigned DEFAULT NULL,
HORARIO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
COMENTARIOS varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
FECHAALTA datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
FECHABAJA datetime DEFAULT NULL,
ESTADO int(1) unsigned NOT NULL DEFAULT '1',
EXT int(1) unsigned NOT NULL DEFAULT '0',
IDTELEFONOEXT int(11) unsigned NOT NULL DEFAULT '0',
KEY TELEFONOESTADO (IDTELEFONO,ESTADO,EXT),
KEY TELEFONOEXTESTADO (IDTELEFONOEXT,ESTADO,EXT),
KEY CODIGOAREA (IDCONTACTO,CODIGOAREA,NUMERO),
KEY IDCONTACTO (IDCONTACTO,FECHAALTA)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." CREATE TABLE: IMPORT_CALLEXT_TELEFONOS_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
// read file into temporary table
$file = $PATH.$TARFILE.$DATEINV."/".$FILE['TELEFONOS'];
$handle = @fopen($file, "r");
if ($handle) {
$cnt = 0;
$tot = 0;
$imp = 0;
while (!feof($handle)) {
$cnt++;
$line = str_replace("'","´",fgets($handle));
if ($line) {
$tot++;
$TMP = null;
$TMP['IDCONTACTO'] = substr($line,0,11);
$TMP['IDTELEFONO'] = substr($line,11,11);
$TMP['CODIGOAREA'] = substr($line,22,11);
$TMP['NUMERO'] = substr($line,33,11);
$TMP['INTERNO'] = substr($line,44,11);
$TMP['HORARIO'] = substr($line,55,255);
$TMP['COMENTARIOS'] = substr($line,310,255);
$TMP['FECHAALTA'] = substr($line,565,19);
$TMP['FECHABAJA'] = substr($line,584,19);
$TMP['ESTADO'] = substr($line,603,1);
$TMP['EXT'] = substr($line,604,1);
// copy new files into temporary table
if (!$TMP['ESTADO'] || $TMP['EXT'] == $EXT) { // only BAJA or EXT==$EXT
$SQL = "INSERT INTO IMPORT_CALLEXT_TELEFONOS_".$DATE." (IDCONTACTO,IDTELEFONO,CODIGOAREA,NUMERO,INTERNO,HORARIO,COMENTARIOS,FECHAALTA,FECHABAJA,ESTADO,EXT,IDTELEFONOEXT)
values ('".$TMP['IDCONTACTO']."',
'".((!$TMP['EXT']) ? $TMP['IDTELEFONO'] : 0)."',
'".$TMP['CODIGOAREA']."',
'".$TMP['NUMERO']."',
'".$TMP['INTERNO']."',
'".$TMP['HORARIO']."',
'".$TMP['COMENTARIOS']."',
str_to_date('".$TMP['FECHAALTA']."','%Y-%m-%d %H:%i:%s'),
".(($TMP['FECHABAJA']) ? "str_to_date('".$TMP['FECHABAJA']."','%Y-%m-%d %H:%i:%s')" : NULL).",
'".$TMP['ESTADO']."',
'".$TMP['EXT']."',
'".(($TMP['EXT']) ? $TMP['IDTELEFONO'] : 0)."')";
$result = mysql_query($SQL, $conn);
if (!$result) savelog("ERR LOAD RECORDS: IMPORT_CALLEXT_TELEFONOS_".$DATE."\n".mysql_error($conn)."\nLINE: ".$cnt."\n"); else $imp++;
}
}
}
fclose($handle);
savelog("OK LOAD RECORDS: IMPORT_CALLEXT_TELEFONOS_".$DATE." [".$imp."/".$tot."]");
}
// update bajas EXT = 0
$SQL = "UPDATE TELEFONOS t, IMPORT_CALLEXT_TELEFONOS_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = i.ESTADO
WHERE t.IDTELEFONO = i.IDTELEFONO
AND i.ESTADO = 0
AND i.EXT = 0";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: TELEFONOS (UPDATE BAJAS) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// insert where EXT = $EXT
$SQL = "INSERT INTO TELEFONOS (IDCONTACTO,TIPO,CODIGOAREA,NUMERO,INTERNO,HORARIO,COMENTARIOS,FECHAALTA,FECHABAJA,ESTADO,EXT,IDTELEFONOEXT)
SELECT i.IDCONTACTO,i.TIPO,i.CODIGOAREA,i.NUMERO,i.INTERNO,i.HORARIO,i.COMENTARIOS,i.FECHAALTA,i.FECHABAJA,i.ESTADO,i.EXT,i.IDTELEFONOEXT
FROM IMPORT_CALLEXT_TELEFONOS_".$DATE." i
WHERE i.EXT = ".$EXT."
AND NOT EXISTS (SELECT 1 FROM TELEFONOS t WHERE t.EXT = i.EXT AND t.IDTELEFONOEXT = i.IDTELEFONOEXT)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: TELEFONOS (INSERT EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// update bajas EXT = $EXT
$SQL = "UPDATE TELEFONOS t, IMPORT_CALLEXT_TELEFONOS_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = 0
WHERE t.IDTELEFONOEXT = i.IDTELEFONOEXT
AND i.ESTADO = 0
AND i.EXT = ".$EXT;
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: TELEFONOS (UPDATE BAJAS EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
} else {
savelog("ERR FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['TELEFONOS']);
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************** TELEFONOS **************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************* REFERENCIAS *************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
if (file_exists($PATH.$TARFILE.$DATEINV."/".$FILE['REFERENCIAS'])) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['REFERENCIAS']);
// create temporary table
$SQL = "CREATE TEMPORARY TABLE IMPORT_CALLEXT_REFERENCIAS_".$DATE." (
IDREFERENCIA int(11) unsigned NOT NULL,
IDCONTACTO int(11) unsigned NOT NULL DEFAULT '0',
REFERENCIA varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
TELEFONO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
FECHAALTA datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
FECHABAJA datetime DEFAULT NULL,
ESTADO int(1) unsigned NOT NULL DEFAULT '1',
EXT int(1) unsigned NOT NULL DEFAULT '0',
IDREFERENCIAEXT int(11) unsigned NOT NULL DEFAULT '0',
KEY REFERENCIAESTADO (IDREFERENCIA,ESTADO,EXT),
KEY REFERENCIAEXTESTADO (IDREFERENCIAEXT,ESTADO,EXT),
KEY IDCONTACTO (IDCONTACTO,FECHAALTA)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." CREATE TABLE: IMPORT_CALLEXT_REFERENCIAS_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
// read file into temporary table
$file = $PATH.$TARFILE.$DATEINV."/".$FILE['REFERENCIAS'];
$handle = @fopen($file, "r");
if ($handle) {
$cnt = 0;
$tot = 0;
$imp = 0;
while (!feof($handle)) {
$cnt++;
$line = str_replace("'","´",fgets($handle));
if ($line) {
$tot++;
$TMP = null;
$TMP['IDCONTACTO'] = substr($line,0,11);
$TMP['IDREFERENCIA'] = substr($line,11,11);
$TMP['REFERENCIA'] = substr($line,22,255);
$TMP['TELEFONO'] = substr($line,277,255);
$TMP['FECHAALTA'] = substr($line,532,19);
$TMP['FECHABAJA'] = substr($line,551,19);
$TMP['ESTADO'] = substr($line,570,1);
$TMP['EXT'] = substr($line,571,1);
// copy new files into temporary table
if (!$TMP['ESTADO'] || $TMP['EXT'] == $EXT) { // only BAJA or EXT==$EXT
$SQL = "INSERT INTO IMPORT_CALLEXT_REFERENCIAS_".$DATE." (IDCONTACTO,IDREFERENCIA,REFERENCIA,TELEFONO,FECHAALTA,FECHABAJA,ESTADO,EXT,IDREFERENCIAEXT)
values ('".$TMP['IDCONTACTO']."',
'".((!$TMP['EXT']) ? $TMP['IDREFERENCIA'] : 0)."',
'".$TMP['REFERENCIA']."',
'".$TMP['TELEFONO']."',
str_to_date('".$TMP['FECHAALTA']."','%Y-%m-%d %H:%i:%s'),
".(($TMP['FECHABAJA']) ? "str_to_date('".$TMP['FECHABAJA']."','%Y-%m-%d %H:%i:%s')" : NULL).",
'".$TMP['ESTADO']."',
'".$TMP['EXT']."',
'".(($TMP['EXT']) ? $TMP['IDREFERENCIA'] : 0)."')";
$result = mysql_query($SQL, $conn);
if (!$result) savelog("ERR LOAD RECORDS: IMPORT_CALLEXT_REFERENCIAS_".$DATE."\n".mysql_error($conn)."\nLINE: ".$cnt."\n"); else $imp++;
}
}
}
fclose($handle);
savelog("OK LOAD RECORDS: IMPORT_CALLEXT_REFERENCIAS_".$DATE." [".$imp."/".$tot."]");
}
// update bajas EXT = 0
$SQL = "UPDATE REFERENCIAS t, IMPORT_CALLEXT_REFERENCIAS_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = i.ESTADO
WHERE t.IDREFERENCIA = i.IDREFERENCIA
AND i.ESTADO = 0
AND i.EXT = 0";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: REFERENCIAS (UPDATE BAJAS) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// insert where EXT = $EXT
$SQL = "INSERT INTO REFERENCIAS (IDCONTACTO,REFERENCIA,TELEFONO,FECHAALTA,FECHABAJA,ESTADO,EXT,IDREFERENCIAEXT)
SELECT i.IDCONTACTO,i.REFERENCIA,i.TELEFONO,i.FECHAALTA,i.FECHABAJA,i.ESTADO,i.EXT,i.IDREFERENCIAEXT
FROM IMPORT_CALLEXT_REFERENCIAS_".$DATE." i
WHERE i.EXT = ".$EXT."
AND NOT EXISTS (SELECT 1 FROM REFERENCIAS t WHERE t.EXT = i.EXT AND t.IDREFERENCIAEXT = i.IDREFERENCIAEXT)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: REFERENCIAS (INSERT EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// update bajas EXT = $EXT
$SQL = "UPDATE REFERENCIAS t, IMPORT_CALLEXT_REFERENCIAS_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = 0
WHERE t.IDREFERENCIAEXT = i.IDREFERENCIAEXT
AND i.ESTADO = 0
AND i.EXT = ".$EXT;
//mysql_query($SQL, $conn);
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: REFERENCIAS (UPDATE BAJAS EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
} else {
savelog("ERR FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['REFERENCIAS']);
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************* REFERENCIAS *************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************* DIRECCIONES *************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
if (file_exists($PATH.$TARFILE.$DATEINV."/".$FILE['DIRECCIONES'])) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['DIRECCIONES']);
// create temporary table
$SQL = "CREATE TEMPORARY TABLE IMPORT_CALLEXT_DIRECCIONES_".$DATE." (
IDDIRECCION int(11) unsigned NOT NULL,
IDCONTACTO int(11) unsigned NOT NULL DEFAULT '0',
CALLE varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
NUMERO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
PISO int(11) unsigned DEFAULT NULL,
DEPTO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
LOCALIDAD varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
PROVINCIA varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
CODIGOPOSTAL varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
PLANO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
COORDENADAS varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
FECHAALTA datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
FECHABAJA datetime DEFAULT NULL,
ESTADO int(1) unsigned NOT NULL DEFAULT '1',
EXT int(1) unsigned NOT NULL DEFAULT '0',
IDDIRECCIONEXT int(11) unsigned NOT NULL DEFAULT '0',
KEY DIRECCIONESTADO (IDDIRECCION,ESTADO,EXT),
KEY DIRECCIONEXTESTADO (IDDIRECCIONEXT,ESTADO,EXT),
KEY IDCONTACTO (IDCONTACTO,FECHAALTA)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." CREATE TABLE: IMPORT_CALLEXT_DIRECCIONES_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
// read file into temporary table
$file = $PATH.$TARFILE.$DATEINV."/".$FILE['DIRECCIONES'];
$handle = @fopen($file, "r");
if ($handle) {
$cnt = 0;
$tot = 0;
$imp = 0;
while (!feof($handle)) {
$cnt++;
$line = str_replace("'","´",fgets($handle));
if ($line) {
$tot++;
$TMP = null;
$TMP['IDCONTACTO'] = substr($line,0,11);
$TMP['IDDIRECCION'] = substr($line,11,11);
$TMP['CALLE'] = substr($line,22,255);
$TMP['NUMERO'] = substr($line,277,255);
$TMP['PISO'] = substr($line,532,11);
$TMP['DEPTO'] = substr($line,543,255);
$TMP['LOCALIDAD'] = substr($line,798,255);
$TMP['CODIGOPOSTAL'] = substr($line,1053,255);
$TMP['FECHAALTA'] = substr($line,1308,19);
$TMP['FECHABAJA'] = substr($line,1327,19);
$TMP['ESTADO'] = substr($line,1346,1);
$TMP['EXT'] = substr($line,1347,1);
// copy new files into temporary table
if (!$TMP['ESTADO'] || $TMP['EXT']) { // only BAJA or EXT
$SQL = "INSERT INTO IMPORT_CALLEXT_DIRECCIONES_".$DATE." (IDCONTACTO,IDDIRECCION,CALLE,NUMERO,PISO,DEPTO,LOCALIDAD,CODIGOPOSTAL,FECHAALTA,FECHABAJA,ESTADO,EXT,IDDIRECCIONEXT)
values ('".$TMP['IDCONTACTO']."',
'".((!$TMP['EXT']) ? $TMP['IDDIRECCION'] : 0)."',
'".$TMP['CALLE']."',
'".$TMP['NUMERO']."',
'".$TMP['PISO']."',
'".$TMP['DEPTO']."',
'".$TMP['LOCALIDAD']."',
'".$TMP['CODIGOPOSTAL']."',
str_to_date('".$TMP['FECHAALTA']."','%Y-%m-%d %H:%i:%s'),
".(($TMP['FECHABAJA']) ? "str_to_date('".$TMP['FECHABAJA']."','%Y-%m-%d %H:%i:%s')" : NULL).",
'".$TMP['ESTADO']."',
'".$TMP['EXT']."',
'".(($TMP['EXT']) ? $TMP['IDDIRECCION'] : 0)."')";
$result = mysql_query($SQL, $conn);
if (!$result) savelog("ERR LOAD RECORDS: IMPORT_CALLEXT_DIRECCIONES_".$DATE."\n".mysql_error($conn)."\nLINE: ".$cnt."\n"); else $imp++;
}
}
}
fclose($handle);
savelog("OK LOAD RECORDS: IMPORT_CALLEXT_DIRECCIONES_".$DATE." [".$imp."/".$tot."]");
}
// update bajas EXT = 0
$SQL = "UPDATE DIRECCIONES t, IMPORT_CALLEXT_DIRECCIONES_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = i.ESTADO
WHERE t.IDDIRECCION = i.IDDIRECCION
AND i.ESTADO = 0
AND i.EXT = 0";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: DIRECCIONES (UPDATE BAJAS) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// insert where EXT = 1
$SQL = "INSERT INTO DIRECCIONES (IDCONTACTO,CALLE,NUMERO,PISO,DEPTO,LOCALIDAD,CODIGOPOSTAL,FECHAALTA,FECHABAJA,ESTADO,EXT,IDDIRECCIONEXT)
SELECT i.IDCONTACTO,i.CALLE,i.NUMERO,i.PISO,i.DEPTO,i.LOCALIDAD,i.CODIGOPOSTAL,i.FECHAALTA,i.FECHABAJA,i.ESTADO,i.EXT,i.IDDIRECCIONEXT
FROM IMPORT_CALLEXT_DIRECCIONES_".$DATE." i
WHERE i.EXT = 1
AND NOT EXISTS (SELECT 1 FROM DIRECCIONES t WHERE t.EXT = 1 AND t.IDDIRECCIONEXT = i.IDDIRECCIONEXT)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: DIRECCIONES (INSERT EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// update bajas EXT = 1
$SQL = "UPDATE DIRECCIONES t, IMPORT_CALLEXT_DIRECCIONES_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = 0
WHERE t.IDDIRECCIONEXT = i.IDDIRECCIONEXT
AND i.ESTADO = 0
AND i.EXT = 1";
//mysql_query($SQL, $conn);
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: DIRECCIONES (UPDATE BAJAS EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
} else {
savelog("ERR FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['DIRECCIONES']);
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************* DIRECCIONES *************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*************** EMPLEOS ***************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
if (file_exists($PATH.$TARFILE.$DATEINV."/".$FILE['EMPLEOS'])) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['EMPLEOS']);
// create temporary table
$SQL = "CREATE TEMPORARY TABLE IMPORT_CALLEXT_EMPLEOS_".$DATE." (
IDEMPLEO int(11) unsigned NOT NULL,
IDCONTACTO int(11) unsigned NOT NULL DEFAULT '0',
EMPRESA varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
SECCION varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
DIRCALLE varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
DIRNUMERO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
DIRPISO int(11) unsigned DEFAULT NULL,
DIRDEPTO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
DIRLOCALIDAD varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
DIRCODIGOPOSTAL varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
TELCODIGOAREA int(11) unsigned DEFAULT NULL,
TELNUMERO int(11) unsigned DEFAULT NULL,
TELINTERNO int(11) unsigned DEFAULT NULL,
FECHAALTA datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
FECHABAJA datetime DEFAULT NULL,
ESTADO int(1) unsigned NOT NULL DEFAULT '1',
EXT int(1) unsigned NOT NULL DEFAULT '0',
IDEMPLEOEXT int(11) unsigned NOT NULL DEFAULT '0',
KEY EMPLEOESTADO (IDEMPLEO,ESTADO,EXT),
KEY EMPLEOEXTESTADO (IDEMPLEOEXT,ESTADO,EXT),
KEY IDCONTACTO (IDCONTACTO,FECHAALTA)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." CREATE TABLE: IMPORT_CALLEXT_EMPLEOS_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
// read file into temporary table
$file = $PATH.$TARFILE.$DATEINV."/".$FILE['EMPLEOS'];
$handle = @fopen($file, "r");
if ($handle) {
$cnt = 0;
$tot = 0;
$imp = 0;
while (!feof($handle)) {
$cnt++;
$line = str_replace("'","´",fgets($handle));
if ($line) {
$tot++;
$TMP = null;
$TMP['IDCONTACTO'] = substr($line,0,11);
$TMP['IDEMPLEO'] = substr($line,11,11);
$TMP['EMPRESA'] = substr($line,22,255);
$TMP['SECCION'] = substr($line,277,255);
$TMP['DIRCALLE'] = substr($line,532,255);
$TMP['DIRNUMERO'] = substr($line,787,255);
$TMP['DIRPISO'] = substr($line,1042,11);
$TMP['DIRDEPTO'] = substr($line,1053,255);
$TMP['DIRLOCALIDAD'] = substr($line,1308,255);
$TMP['DIRCODIGOPOSTAL'] = substr($line,1563,255);
$TMP['TELCODIGOAREA'] = substr($line,1818,11);
$TMP['TELNUMERO'] = substr($line,1829,11);
$TMP['TELINTERNO'] = substr($line,1840,11);
$TMP['FECHAALTA'] = substr($line,1851,19);
$TMP['FECHABAJA'] = substr($line,1870,19);
$TMP['ESTADO'] = substr($line,1889,1);
$TMP['EXT'] = substr($line,1890,1);
// copy new files into temporary table
if (!$TMP['ESTADO'] || $TMP['EXT']) { // only BAJA or EXT
$SQL = "INSERT INTO IMPORT_CALLEXT_EMPLEOS_".$DATE." (IDCONTACTO,IDEMPLEO,EMPRESA,SECCION,DIRCALLE,DIRNUMERO,DIRPISO,DIRDEPTO,DIRLOCALIDAD,DIRCODIGOPOSTAL,TELCODIGOAREA,TELNUMERO,TELINTERNO,FECHAALTA,FECHABAJA,ESTADO,EXT,IDEMPLEOEXT)
values ('".$TMP['IDCONTACTO']."',
'".((!$TMP['EXT']) ? $TMP['IDEMPLEO'] : 0)."',
'".$TMP['EMPRESA']."',
'".$TMP['SECCION']."',
'".$TMP['DIRCALLE']."',
'".$TMP['DIRNUMERO']."',
'".$TMP['DIRPISO']."',
'".$TMP['DIRDEPTO']."',
'".$TMP['DIRLOCALIDAD']."',
'".$TMP['DIRCODIGOPOSTAL']."',
'".$TMP['TELCODIGOAREA']."',
'".$TMP['TELNUMERO']."',
'".$TMP['TELINTERNO']."',
str_to_date('".$TMP['FECHAALTA']."','%Y-%m-%d %H:%i:%s'),
".(($TMP['FECHABAJA']) ? "str_to_date('".$TMP['FECHABAJA']."','%Y-%m-%d %H:%i:%s')" : NULL).",
'".$TMP['ESTADO']."',
'".$TMP['EXT']."',
'".(($TMP['EXT']) ? $TMP['IDEMPLEO'] : 0)."')";
$result = mysql_query($SQL, $conn);
if (!$result) savelog("ERR LOAD RECORDS: IMPORT_CALLEXT_EMPLEOS_".$DATE."\n".mysql_error($conn)."\nLINE: ".$cnt."\n"); else $imp++;
}
}
}
fclose($handle);
savelog("OK LOAD RECORDS: IMPORT_CALLEXT_EMPLEOS_".$DATE." [".$imp."/".$tot."]");
}
// update bajas EXT = 0
$SQL = "UPDATE EMPLEOS t, IMPORT_CALLEXT_EMPLEOS_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = i.ESTADO
WHERE t.IDEMPLEO = i.IDEMPLEO
AND i.ESTADO = 0
AND i.EXT = 0";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: EMPLEOS (UPDATE BAJAS) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// insert where EXT = 1
$SQL = "INSERT INTO EMPLEOS (IDCONTACTO,EMPRESA,SECCION,DIRCALLE,DIRNUMERO,DIRPISO,DIRDEPTO,DIRLOCALIDAD,DIRCODIGOPOSTAL,TELCODIGOAREA,TELNUMERO,TELINTERNO,FECHAALTA,FECHABAJA,ESTADO,EXT,IDEMPLEOEXT)
SELECT i.IDCONTACTO,i.EMPRESA,i.SECCION,i.DIRCALLE,i.DIRNUMERO,i.DIRPISO,i.DIRDEPTO,i.DIRLOCALIDAD,i.DIRCODIGOPOSTAL,i.TELCODIGOAREA,i.TELNUMERO,i.TELINTERNO,i.FECHAALTA,i.FECHABAJA,i.ESTADO,i.EXT,i.IDEMPLEOEXT
FROM IMPORT_CALLEXT_EMPLEOS_".$DATE." i
WHERE i.EXT = 1
AND NOT EXISTS (SELECT 1 FROM EMPLEOS t WHERE t.EXT = 1 AND t.IDEMPLEOEXT = i.IDEMPLEOEXT)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: EMPLEOS (INSERT EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// update bajas EXT = 1
$SQL = "UPDATE EMPLEOS t, IMPORT_CALLEXT_EMPLEOS_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = 0
WHERE t.IDEMPLEOEXT = i.IDEMPLEOEXT
AND i.ESTADO = 0
AND i.EXT = 1";
//mysql_query($SQL, $conn);
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: EMPLEOS (UPDATE BAJAS EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
} else {
savelog("ERR FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['EMPLEOS']);
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*************** EMPLEOS ***************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************* SEGUIMIENTO *************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
if (file_exists($PATH.$TARFILE.$DATEINV."/".$FILE['SEGUIMIENTO'])) {
savelog("OK FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['SEGUIMIENTO']);
// create temporary table
$SQL = "CREATE TEMPORARY TABLE IMPORT_CALLEXT_SEGUIMIENTO_".$DATE." (
IDSEGUIMIENTO int(11) unsigned NOT NULL,
IDUSUARIO int(11) unsigned NOT NULL DEFAULT '0',
IDCARTERA int(11) unsigned NOT NULL DEFAULT '0',
TELEFONO varchar(255) COLLATE latin1_spanish_ci DEFAULT NULL,
RESULTADO int(11) unsigned NOT NULL DEFAULT '0',
COMENTARIOS varchar(8000) COLLATE latin1_spanish_ci DEFAULT NULL,
NUMCREDITO varchar(7) COLLATE latin1_spanish_ci DEFAULT NULL,
FECHAALTA datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
FECHABAJA datetime DEFAULT NULL,
ESTADO int(1) unsigned NOT NULL DEFAULT '1',
EXT int(1) unsigned NOT NULL DEFAULT '0',
IDSEGUIMIENTOEXT int(11) unsigned NOT NULL DEFAULT '0',
KEY SEGUIMIENTOESTADO (IDSEGUIMIENTO,ESTADO,EXT),
KEY SEGUIMIENTOEXTESTADO (IDSEGUIMIENTOEXT,ESTADO,EXT),
KEY IDCARTERA (IDCARTERA,FECHAALTA)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." CREATE TABLE: IMPORT_CALLEXT_SEGUIMIENTO_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
// read file into temporary table
$file = $PATH.$TARFILE.$DATEINV."/".$FILE['SEGUIMIENTO'];
$handle = @fopen($file, "r");
if ($handle) {
$cnt = 0;
$tot = 0;
$imp = 0;
while (!feof($handle)) {
$cnt++;
$line = str_replace("'","´",fgets($handle));
if ($line) {
$tot++;
$TMP = null;
$TMP['IDCARTERA'] = substr($line,0,11);
$TMP['IDSEGUIMIENTO'] = substr($line,11,11);
$TMP['TELEFONO'] = substr($line,22,255);
$TMP['COMENTARIOS'] = substr($line,277,8000);
$TMP['NUMCREDITO'] = substr($line,8277,7);
$TMP['FECHAALTA'] = substr($line,8284,19);
$TMP['FECHABAJA'] = substr($line,8303,19);
$TMP['ESTADO'] = substr($line,8322,1);
$TMP['EXT'] = substr($line,8323,1);
// copy new files into temporary table
if (!$TMP['ESTADO'] || $TMP['EXT']) { // only BAJA or EXT
$SQL = "INSERT INTO IMPORT_CALLEXT_SEGUIMIENTO_".$DATE." (IDCARTERA,IDSEGUIMIENTO,IDUSUARIO,TELEFONO,COMENTARIOS,NUMCREDITO,FECHAALTA,FECHABAJA,ESTADO,EXT,IDSEGUIMIENTOEXT)
values ('".$TMP['IDCARTERA']."',
'".((!$TMP['EXT']) ? $TMP['IDSEGUIMIENTO'] : 0)."',
(SELECT IDUSUARIO FROM DISTRIBUCION WHERE IDCARTERA = '".$TMP['IDCARTERA']."'),
'".$TMP['TELEFONO']."',
'".trim($TMP['COMENTARIOS'])."',
'".$TMP['NUMCREDITO']."',
str_to_date('".$TMP['FECHAALTA']."','%Y-%m-%d %H:%i:%s'),
".(($TMP['FECHABAJA']) ? "str_to_date('".$TMP['FECHABAJA']."','%Y-%m-%d %H:%i:%s')" : NULL).",
'".$TMP['ESTADO']."',
'".$TMP['EXT']."',
'".(($TMP['EXT']) ? $TMP['IDSEGUIMIENTO'] : 0)."')";
$result = mysql_query($SQL, $conn);
if (!$result) savelog("ERR LOAD RECORDS: IMPORT_CALLEXT_SEGUIMIENTO_".$DATE."\n".mysql_error($conn)."\nLINE: ".$cnt."\n"); else $imp++;
}
}
}
fclose($handle);
savelog("OK LOAD RECORDS: IMPORT_CALLEXT_SEGUIMIENTO_".$DATE." [".$imp."/".$tot."]");
}
// update bajas EXT = 0
$SQL = "UPDATE SEGUIMIENTO t, IMPORT_CALLEXT_SEGUIMIENTO_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = i.ESTADO
WHERE t.IDSEGUIMIENTO = i.IDSEGUIMIENTO
AND i.ESTADO = 0
AND i.EXT = 0";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: SEGUIMIENTO (UPDATE BAJAS) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// insert where EXT = 1
$SQL = "INSERT INTO SEGUIMIENTO (IDCARTERA,IDSEGUIMIENTO,IDUSUARIO,TELEFONO,COMENTARIOS,FECHAALTA,FECHABAJA,ESTADO,EXT,IDSEGUIMIENTOEXT)
SELECT i.IDCARTERA,i.IDSEGUIMIENTO,(SELECT dd.IDUSUARIO FROM DISTRIBUCION dd WHERE dd.IDCARTERA = i.IDCARTERA) IDUSUARIO,i.TELEFONO,i.COMENTARIOS,i.FECHAALTA,i.FECHABAJA,i.ESTADO,i.EXT,i.IDSEGUIMIENTOEXT
FROM IMPORT_CALLEXT_SEGUIMIENTO_".$DATE." i
WHERE i.EXT = 1
AND NOT EXISTS (SELECT 1 FROM SEGUIMIENTO t WHERE t.EXT = 1 AND t.IDSEGUIMIENTOEXT = i.IDSEGUIMIENTOEXT)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: SEGUIMIENTO (INSERT EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
// update bajas EXT = 1
$SQL = "UPDATE SEGUIMIENTO t, IMPORT_CALLEXT_SEGUIMIENTO_".$DATE." i
SET t.FECHABAJA = i.FECHABAJA,
t.ESTADO = 0
WHERE t.IDSEGUIMIENTOEXT = i.IDSEGUIMIENTOEXT
AND i.ESTADO = 0
AND i.EXT = 1";
//mysql_query($SQL, $conn);
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." LOAD RECORDS: SEGUIMIENTO (UPDATE BAJAS EXT) [".mysql_affected_rows($conn)."]".(($result) ? "" : "\n".mysql_error($conn)));
} else {
savelog("ERR FILE EXISTS: ".$PATH.$TARFILE.$DATEINV."/".$FILE['SEGUIMIENTO']);
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************* SEGUIMIENTO *************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
shell_exec("rm -fR ".$PATH.$TARFILE.$DATEINV.";");
?>
<file_sep>comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
varLog=/home/callcenter/interfaz/proceso/logs/php_log.txt
cd /home/callcenter/htdocs/phpinclude
/usr/bin/php distribucion.php
$comprobar $? $varLog distribucion.php
<file_sep>varLog=/home/callcenter/interfaz/proceso/logs/asignacion.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mensaje=/home/callcenter/interfaz/proceso/archivos/messageAsignacion.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
from="<EMAIL>"
queries=/home/callcenter/interfaz/proceso/queries
procesar=/home/callcenter/interfaz/procesar
query01=$queries/correrLimpiarUsuarios.sql
#query02=$queries/correrLimpiarUsuarios.sql
query1=$queries/asignacionPaso1ColumnaO.sql
query2=$queries/asignacionPaso2ColumnaP.sql
query3=$queries/asignacionPaso3ColumnaQ.sql
query4=$queries/asignacionPaso4ColumnaR.sql
query5=$queries/asignacionPaso5.sql
ejecutarQuery=/home/callcenter/interfaz/proceso/run_n_log_query.sh
ejecutarQuery ()
{
query=$(cat $1)
mysql -se "$query"
}
armarMensajeProcesoAsignacion ()
{
if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nLa asignacion del mes se realizo correctamente\n===========================" > $mensaje
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: La asignacion del mes\n===========================" > $mensaje
fi
}
procesoAsignacion ()
{
$ejecutarQuery $query01 $varLog
$ejecutarQuery $query1 $varLog
$ejecutarQuery $query2 $varLog
$ejecutarQuery $query3 $varLog
$ejecutarQuery $query4 $varLog
$ejecutarQuery $query5 $varLog
echo hola
armarMensajeProcesoAsignacion $?
mandarMailDestinatarios "Asignacion%$mensaje%1%<EMAIL>"
$comprobar $? $varLog asignacion.sh
}
esFechaDeCierre ()
{
mes=$(date +%D | cut -d "/" -f 1)
dia=$(date +%D | cut -d "/" -f 2)
anio=$(date +%D | cut -d "/" -f 3)
#FECHAS DE CIERRE EXACTAS SIN SUMAR NADA
if [[ $dia -eq 29 && $mes -eq 1 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 26 && $mes -eq 2 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 27 && $mes -eq 3 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 26 && $mes -eq 4 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 29 && $mes -eq 5 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 28 && $mes -eq 6 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 28 && $mes -eq 7 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 29 && $mes -eq 8 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 27 && $mes -eq 9 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 29 && $mes -eq 10 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 28 && $mes -eq 11 && $anio -eq 18 ]]
then
procesoAsignacion
fi
if [[ $dia -eq 27 && $mes -eq 12 && $anio -eq 18 ]]
then
procesoAsignacion
fi
}
mandarMailDestinatarios ()
{
#parametro 1=subject, 2=mensaje,3 cantidad De mails destinatarios, 4 en adelante lista de mails
#en realidad es un solo parametro que es un string y de el se extraen los parametros porque sino hay problemas
#ya que el mensaje tiene espacios y los espacios hace creer a linux que son muchos parametros por mas
#que el mismo se encuentre entre comillas
subject="$(echo $1 | cut -d "%" -f 1)"
destinatario="$(echo $1 | cut -d "%" -f 4)"
cantDestinatarios=$(echo $1 | cut -d "%" -f 3)
let cantDestinatarios=cantDestinatarios+3
#echo -e "echo -e $mensaje | mail -s "$subject" -r "$from" "$(echo $1 | cut -d "%" -f 3)""
for i in $(seq 4 $cantDestinatarios)
do
echo -e "$(cat $mensaje)" | mail -s "$subject" -r "$from" "$(echo $1 | cut -d "%" -f $i)"
done
}
esFechaDeCierre<file_sep>if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nEl proceso diario se realizo correctamente\n===========================" > /home/callcenter/interfaz/proceso/archivos/message.txt
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: en el proceso diario\n===========================" > /home/callcenter/interfaz/proceso/archivos/message.txt
fi<file_sep>SELECT * FROM Agentes;<file_sep>SELECT COUNT(*) FRoM fechas_cierre where fecha=date_add('<file_sep><?
date_default_timezone_set ('America/Argentina/Buenos_Aires');
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** CUSTOM DATA ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// local path
$PATH = "/home/callcenter/interfaz/sms/out/";
$SENTPATH = "/home/callcenter/interfaz/sms/out/sent/";
// log
$LOG = "/home/callcenter/interfaz/sms/log/out.log";
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** CUSTOM DATA ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// include
include("/home/callcenter/htdocs/conndb/conndb.php");
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/callcenter/htdocs/phplib/phpseclib/');
include('Net/SFTP.php');
// date
$DATE = date("Ymd",time());
// files
$FILE['SMS30'] = "sms30_".$DATE.".txt";
$FILE['SMS60'] = "sms60_".$DATE.".txt";
$FILE['SMS90'] = "sms90_".$DATE.".txt";
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ LOG ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
function savelog($msg) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - $msg\r\n" );
@fclose($handle);
}
}
function errorlog($type, $info, $file, $row) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - ERR --> $type: $info FILE: $file - Row $row\r\n" );
@fclose($handle);
}
}
set_error_handler(errorlog, E_USER_ERROR);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ LOG ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** SMS 30 ***********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE[SMS30], "w");
// get query
$SQL = "SELECT
ca.IDCARTERA IDCARTERA,
ca.IDMOROSO IDMOROSO,
LPAD(IFNULL(ca.SUCURSAL,''),3,'0') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,'0') NUMCREDITO,
(SELECT CONCAT(CODIGOAREA,NUMERO)
FROM TELEFONOS t
WHERE ca.IDMOROSO=t.IDCONTACTO
AND ESTADO=1
ORDER BY FECHAALTA DESC
LIMIT 1) TELEFONO,
DATE_FORMAT(DATE_ADD(ca.FECHA, INTERVAL CASE WHEN ca.TIPOCREDITO IN ('BI','BY') THEN ca.ULTIMACUOTA*2 ELSE ca.ULTIMACUOTA END MONTH),'%d/%m/%y') FECVEN
FROM CARTERA ca
WHERE ca.TIPOPROCESO='1AT'
AND ca.FECHAPROCESO = (SELECT MAX(FECHAPROCESO) FROM CARTERA)
AND ca.ESTADO NOT IN (3,5,10,14)
AND ca.ULTIMACUOTA=0
AND ca.SUCURSAL in ('001','002','004','005','010','021','026','033','037','045','054','056','059','061','064','065','070','071','083','084','106','107','116','122','126','130','133','134','136','145','148','153','160','162','163')";
$result = mysql_query($SQL, $conn);
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'].";";
$buffer.= $rs['IDMOROSO'].";";
$buffer.= $rs['SUCURSAL'].";";
$buffer.= $rs['NUMCREDITO'].";";
$buffer.= $rs['TELEFONO'].";";
$buffer.= "Le recordamos que está venciendo su crédito número ".$rs['SUCURSAL'].$rs['NUMCREDITO']." de la compra realizada en FRAVEGA, si ya abono por favor desestimar el mensaje. Muchas Gracias";
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** SMS 30 ***********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** SMS 60 ***********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE[SMS60], "w");
// get query
$SQL = "SELECT
ca.IDCARTERA IDCARTERA,
ca.IDMOROSO IDMOROSO,
LPAD(IFNULL(ca.SUCURSAL,''),3,'0') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,'0') NUMCREDITO,
(SELECT CONCAT(CODIGOAREA,NUMERO)
FROM TELEFONOS t
WHERE ca.IDMOROSO=t.IDCONTACTO
AND ESTADO=1
ORDER BY FECHAALTA DESC
LIMIT 1) TELEFONO,
DATE_FORMAT(DATE_ADD(ca.FECHA, INTERVAL CASE WHEN ca.TIPOCREDITO IN ('BI','BY') THEN ca.ULTIMACUOTA*2 ELSE ca.ULTIMACUOTA END MONTH),'%d/%m/%y') FECVEN
FROM CARTERA ca
WHERE ca.TIPOPROCESO='002'
AND ca.FECHAPROCESO = (SELECT MAX(FECHAPROCESO) FROM CARTERA)
AND ca.ESTADO NOT IN (3,5,10,14)
AND ca.ULTIMACUOTA=0
AND ca.SUCURSAL in ('001','009','025','026','033','051','054','071','104','108','113','118','126','134','148','153')";
$result = mysql_query($SQL, $conn);
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'].";";
$buffer.= $rs['IDMOROSO'].";";
$buffer.= $rs['SUCURSAL'].";";
$buffer.= $rs['NUMCREDITO'].";";
$buffer.= $rs['TELEFONO'].";";
$buffer.= "Lo citamos a concurrir a fravega con la finalidad de resolver su situacion crediticia ".$rs['SUCURSAL'].$rs['NUMCREDITO']." con 2 meses de atraso.Si ya abono descarte este mensaje.Gracias";
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** SMS 60 ***********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** SMS 90 ***********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE[SMS90], "w");
// get query
$SQL = "SELECT
ca.IDCARTERA IDCARTERA,
ca.IDMOROSO IDMOROSO,
LPAD(IFNULL(ca.SUCURSAL,''),3,'0') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,'0') NUMCREDITO,
(SELECT CONCAT(CODIGOAREA,NUMERO)
FROM TELEFONOS t
WHERE ca.IDMOROSO=t.IDCONTACTO
AND ESTADO=1
ORDER BY FECHAALTA DESC
LIMIT 1) TELEFONO,
DATE_FORMAT(DATE_ADD(ca.FECHA, INTERVAL CASE WHEN ca.TIPOCREDITO IN ('BI','BY') THEN ca.ULTIMACUOTA*2 ELSE ca.ULTIMACUOTA END MONTH),'%d/%m/%y') FECVEN
FROM CARTERA ca
WHERE ca.TIPOPROCESO='003'
AND ca.FECHAPROCESO = (SELECT MAX(FECHAPROCESO) FROM CARTERA)
AND ca.ESTADO NOT IN (3,5,10,14)
AND ca.ULTIMACUOTA=0
AND ca.SUCURSAL in ('001','009','025','026','033','051','054','071','104','108','113','118','126','134','148','153')";
$result = mysql_query($SQL, $conn);
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'].";";
$buffer.= $rs['IDMOROSO'].";";
$buffer.= $rs['SUCURSAL'].";";
$buffer.= $rs['NUMCREDITO'].";";
$buffer.= $rs['TELEFONO'].";";
$buffer.= "Por favor presentese en FRAVEGA a regularizar su credito ".$rs['SUCURSAL'].$rs['NUMCREDITO']." con 3 meses de atraso. Si ya abono descarte este mensaje. Gracias.";
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** SMS 90 ***********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
?>
<file_sep><?
date_default_timezone_set ('America/Argentina/Buenos_Aires');
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** CUSTOM DATA ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// EXT: Código de Call Center Externo
$EXT = "1";
// local path
$PATH = "/home/callcenter/interfaz/cc_externo/gering/out/";
$SENTPATH = "/home/callcenter/interfaz/cc_externo/gering/out/sent/";
// log
$LOG = "/home/callcenter/interfaz/cc_externo/gering/log/out.log";
// sftp
$SFTP = 1;
$SFTPSERVER = "sftp.gering.com.ar";
$SFTPPORT = "20022";
$SFTPUSER = "fvg";
$SFTPPASS = "<PASSWORD>";
$SFTPPATH = "/inbox/";
// ftp
$FTPSERVER = "";
$FTPUSER = "";
$FTPPASS = "";
$FTPPATH = "/inbox/";
//zip extension
$ZIPEXT = ".tar.gz";
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** CUSTOM DATA ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// include
include("/home/callcenter/htdocs/conndb/conndb.php");
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/callcenter/htdocs/phplib/phpseclib/');
include('Net/SFTP.php');
// date
$DATE = date("Ymd",time());
// files
$FILE['CARTERA'] = "CARTERA_".$DATE.".txt";
$FILE['MOROSOS'] = "MOROSOS_".$DATE.".txt";
$FILE['TELEFONOS'] = "TELEFONOS_".$DATE.".txt";
$FILE['REFERENCIAS'] = "REFERENCIAS_".$DATE.".txt";
$FILE['DIRECCIONES'] = "DIRECCIONES_".$DATE.".txt";
$FILE['EMPLEOS'] = "EMPLEOS_".$DATE.".txt";
$FILE['CREDITOS'] = "CREDITOS_".$DATE.".txt";
$FILE['PRODUCTOS'] = "PRODUCTOS_".$DATE.".txt";
$FILE['SEGUIMIENTO'] = "SEGUIMIENTO_".$DATE.".txt";
// idusuario
$IDUSUARIO = "";
$SQL = "SELECT IDUSUARIO FROM USUARIOS WHERE CODIGO LIKE 'GSA%'";
$result = mysql_query($SQL, $conn);
while($rs = mysql_fetch_array($result)) {
if ($IDUSUARIO) $IDUSUARIO.= ",";
$IDUSUARIO.= $rs['IDUSUARIO'];
}
/*
$IDUSUARIO = "102150,
102151,
102152,
102153,
102154,
102155,
102156,
102157,
102158,
102159,
102160,
102161,
102162,
102163,
102164,
102165";
*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ LOG ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
function savelog($msg) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - $msg\r\n" );
@fclose($handle);
}
}
function errorlog($type, $info, $file, $row) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - ERR --> $type: $info FILE: $file - Row $row\r\n" );
@fclose($handle);
}
}
set_error_handler(errorlog, E_USER_ERROR);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ LOG ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** TABLA TEMPORAL **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
$SQL = "CREATE TABLE EXPORT_CALLEXT_".$DATE." as
SELECT DISTINCT ca.IDCARTERA IDCARTERA, ca.IDMOROSO IDMOROSO
FROM CARTERA ca
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN SUCURSALES su ON ca.SUCURSAL=su.SUCURSAL
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA
AND di.IDLOTE=1
AND di.IDUSUARIO in ($IDUSUARIO)
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5";
mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." TABLE: EXPORT_CALLEXT_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** TABLA TEMPORAL **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** CARTERA **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['CARTERA'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['CARTERA']);
// get query
$SQL = "SELECT LPAD(IFNULL(ca.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(ca.IDMOROSO,''),11,' ') IDMOROSO,
RPAD(SUBSTRING(IFNULL(ca.SUCURSAL,''),1,10),10,' ') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
RPAD(SUBSTRING(IFNULL(ca.CATEGORIA,''),1,11),11,' ') CATEGORIA,
LPAD(TRUNCATE(IFNULL((ca.SALDO+ca.SALDOBCO+ca.SALDOPESOS),'0.00'),2),13,'0') SALDOTOMAR,
RPAD(SUBSTRING(IFNULL(pe.PERFIL,''),1,50),50,' ') PERFIL,
RPAD(SUBSTRING(IFNULL(ca.TIPOPROCESO,''),1,10),10,' ') TIPOPROCESO,
RPAD(SUBSTRING(IFNULL(ca.TIPOCREDITO,''),1,10),10,' ') TIPOCREDITO,
LPAD(IFNULL(ca.FECHAAGENDA,''),19,' ') FECHAAGENDA,
LPAD(IFNULL(ca.FECHAPROCESO,''),19,' ') FECHAPROCESO,
LPAD(IFNULL(ce.ESTADO,''),11,' ') CARTERAESTADO,
RPAD(SUBSTRING(IFNULL(ce.DETALLE,''),1,50),50,' ') DETALLEESTADO,
LPAD(IFNULL(ce.ORDEN,''),11,' ') ORDEN
FROM CARTERA ca
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN SUCURSALES su ON ca.SUCURSAL=su.SUCURSAL
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA
AND di.IDLOTE=1
AND di.SUCURSAL IN (SELECT a.IDSUCURSAL FROM USUARIOPERFILES a WHERE a.IDUSUARIO in ($IDUSUARIO))
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: CARTERA".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['IDMOROSO'];
$buffer.= $rs['SUCURSAL'];
$buffer.= $rs['NUMCREDITO'];
$buffer.= $rs['CATEGORIA'];
$buffer.= $rs['SALDOTOMAR'];
$buffer.= $rs['PERFIL'];
$buffer.= $rs['TIPOPROCESO'];
$buffer.= $rs['TIPOCREDITO'];
$buffer.= $rs['FECHAAGENDA'];
$buffer.= $rs['FECHAPROCESO'];
$buffer.= $rs['CARTERAESTADO'];
$buffer.= $rs['DETALLEESTADO'];
$buffer.= $rs['ORDEN'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** CARTERA **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** MOROSOS **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['MOROSOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['MOROSOS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(co.IDCONTACTO,''),11,' ') IDCONTACTO,
RPAD(SUBSTRING(IFNULL(co.NOMBRE,''),1,255),255,' ') NOMBRE,
LPAD(IFNULL(co.DOCUMENTONUMERO,''),11,' ') DOCUMENTONUMERO,
LPAD(IFNULL(co.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(co.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(co.ESTADO,'0') ESTADO
FROM CONTACTOS co
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = co.IDCONTACTO";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: MOROSOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['NOMBRE'];
$buffer.= $rs['DOCUMENTONUMERO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** MOROSOS **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********* TELEFONOS *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['TELEFONOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['TELEFONOS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(t.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(t.IDTELEFONO,''),11,' ') IDTELEFONO,
LPAD(IFNULL(t.CODIGOAREA,''),11,' ') CODIGOAREA,
LPAD(IFNULL(t.NUMERO,''),11,' ') NUMERO,
LPAD(IFNULL(t.INTERNO,''),11,' ') INTERNO,
RPAD(SUBSTRING(IFNULL(t.HORARIO,''),1,255),255,' ') HORARIO,
RPAD(SUBSTRING(IFNULL(t.COMENTARIOS,''),1,255),255,' ') COMENTARIOS,
LPAD(IFNULL(t.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(t.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(t.ESTADO,'0') ESTADO
FROM TELEFONOS t
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = t.IDCONTACTO
WHERE t.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: TELEFONOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDTELEFONO'];
$buffer.= $rs['CODIGOAREA'];
$buffer.= $rs['NUMERO'];
$buffer.= $rs['INTERNO'];
$buffer.= $rs['HORARIO'];
$buffer.= $rs['COMENTARIOS'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********* TELEFONOS *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** REFERENCIAS ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['REFERENCIAS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['REFERENCIAS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(r.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(r.IDREFERENCIA,''),11,' ') IDREFERENCIA,
RPAD(SUBSTRING(IFNULL(r.REFERENCIA,''),1,255),255,' ') REFERENCIA,
RPAD(SUBSTRING(IFNULL(r.TELEFONO,''),1,255),255,' ') TELEFONO,
LPAD(IFNULL(r.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(r.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(r.ESTADO,'0') ESTADO
FROM REFERENCIAS r
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = r.IDCONTACTO
WHERE r.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: REFERENCIAS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDREFERENCIA'];
$buffer.= $rs['REFERENCIA'];
$buffer.= $rs['TELEFONO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** REFERENCIAS ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** DIRECCIONES ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['DIRECCIONES'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['DIRECCIONES']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(d.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(d.IDDIRECCION,''),11,' ') IDDIRECCION,
RPAD(SUBSTRING(IFNULL(d.CALLE,''),1,255),255,' ') CALLE,
RPAD(SUBSTRING(IFNULL(d.NUMERO,''),1,255),255,' ') NUMERO,
LPAD(IFNULL(d.PISO,''),11,' ') PISO,
RPAD(SUBSTRING(IFNULL(d.DEPTO,''),1,255),20,' ') DEPTO,
RPAD(SUBSTRING(IFNULL(d.LOCALIDAD,''),1,255),20,' ') LOCALIDAD,
RPAD(SUBSTRING(IFNULL(d.CODIGOPOSTAL,''),1,255),20,' ') CODIGOPOSTAL,
LPAD(IFNULL(d.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(d.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(d.ESTADO,'0') ESTADO
FROM DIRECCIONES d
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = d.IDCONTACTO
WHERE d.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: DIRECCIONES".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDDIRECCION'];
$buffer.= $rs['CALLE'];
$buffer.= $rs['NUMERO'];
$buffer.= $rs['PISO'];
$buffer.= $rs['DEPTO'];
$buffer.= $rs['LOCALIDAD'];
$buffer.= $rs['CODIGOPOSTAL'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** DIRECCIONES ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** EMPLEOS **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['EMPLEOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['EMPLEOS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(e.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(e.IDEMPLEO,''),11,' ') IDEMPLEO,
RPAD(SUBSTRING(IFNULL(e.EMPRESA,''),1,255),255,' ') EMPRESA,
RPAD(SUBSTRING(IFNULL(e.SECCION,''),1,255),255,' ') SECCION,
RPAD(SUBSTRING(IFNULL(e.DIRCALLE,''),1,255),255,' ') DIRCALLE,
RPAD(SUBSTRING(IFNULL(e.DIRNUMERO,''),1,255),255,' ') DIRNUMERO,
LPAD(IFNULL(e.DIRPISO,''),11,' ') DIRPISO,
RPAD(SUBSTRING(IFNULL(e.DIRDEPTO,''),1,255),255,' ') DIRDEPTO,
RPAD(SUBSTRING(IFNULL(e.DIRLOCALIDAD,''),1,255),255,' ') DIRLOCALIDAD,
RPAD(SUBSTRING(IFNULL(e.DIRCODIGOPOSTAL,''),1,255),255,' ') DIRCODIGOPOSTAL,
LPAD(IFNULL(e.TELCODIGOAREA,''),11,' ') TELCODIGOAREA,
LPAD(IFNULL(e.TELNUMERO,''),11,' ') TELNUMERO,
LPAD(IFNULL(e.TELINTERNO,''),11,' ') TELINTERNO,
LPAD(IFNULL(e.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(e.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(e.ESTADO,'0') ESTADO
FROM EMPLEOS e
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = e.IDCONTACTO
WHERE e.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: EMPLEOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDEMPLEO'];
$buffer.= $rs['EMPRESA'];
$buffer.= $rs['SECCION'];
$buffer.= $rs['DIRCALLE'];
$buffer.= $rs['DIRNUMERO'];
$buffer.= $rs['DIRPISO'];
$buffer.= $rs['DIRDEPTO'];
$buffer.= $rs['DIRLOCALIDAD'];
$buffer.= $rs['DIRCODIGOPOSTAL'];
$buffer.= $rs['TELCODIGOAREA'];
$buffer.= $rs['TELNUMERO'];
$buffer.= $rs['TELINTERNO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** EMPLEOS **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** CREDITOS *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['CREDITOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['CREDITOS']);
// get query
$SQL = "SELECT LPAD(IFNULL(ca.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(ca.SUCURSAL,''),11,' ') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
RPAD(SUBSTR(IFNULL(pe.PERFIL,''),1,50),50,' ') PERFIL,
LPAD(IFNULL((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())),''),11,' ') DIASC,
LPAD(SUBSTR(IFNULL((DATE_FORMAT(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),'%d/%m/%y')),''),1,8),8,' ') FECVEN,
LPAD(IFNULL(ca.CUOTAS,''),2,' ') CUOTAS,
LPAD(IFNULL(ca.ULTIMACUOTA,''),2,' ') ULTIMACUOTA,
LPAD(IFNULL(ca.IMPORTE,''),13,' ') IMPORTE,
LPAD(IFNULL((ca.SALDO+ca.SALDOBCO+ca.SALDOPESOS),''),13,' ') SALDOTOMAR,
LPAD(IFNULL((CASE WHEN TIPOCREDITO='BI' OR TIPOCREDITO = 'BY' OR TIPOCREDITO = 'AP' THEN '' ELSE ROUND(pr.PORCENTAJE*ca.IMPORTE/100,2) END),''),13,' ') PRORROGA,
LPAD(IFNULL((CASE WHEN (-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())) < 31 THEN (CASE WHEN (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) < 3 THEN 3 ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 3 END) ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 15 END),''),10,' ') PUNITORIO,
RPAD(SUBSTR(IFNULL(ce.DETALLE,''),1,50),50,' ') ESTADOCE
FROM CARTERA ca
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA = ca.IDCARTERA
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
LEFT JOIN DISTRIBUCION di ON di.IDCARTERA=ca.IDCARTERA
LEFT JOIN USUARIOS us ON us.IDUSUARIO=di.IDUSUARIO
JOIN PRORROGAS pr ON ca.AUXNUEVO=pr.PRORROGAS
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5
UNION
SELECT LPAD(IFNULL(ca.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(ca.SUCURSAL,''),11,' ') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
RPAD(SUBSTR(IFNULL(pe.PERFIL,''),1,50),50,' ') PERFIL,
LPAD(IFNULL((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())),''),11,' ') DIASC,
RPAD(SUBSTR(IFNULL((DATE_FORMAT(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),'%d/%m/%y')),''),1,8),8,' ') FECVEN,
LPAD(IFNULL(ca.CUOTAS,''),2,' ') CUOTAS,
LPAD(IFNULL(ca.ULTIMACUOTA,''),2,' ') ULTIMACUOTA,
LPAD(IFNULL(ca.IMPORTE,''),13,' ') IMPORTE,
LPAD(IFNULL((ca.SALDO + ca.SALDOBCO + ca.SALDOPESOS),''),13,' ') SALDOTOMAR,
LPAD(IFNULL((CASE WHEN TIPOCREDITO='BI' OR TIPOCREDITO = 'BY' OR TIPOCREDITO = 'AP' THEN '-' ELSE ROUND(pr.PORCENTAJE*ca.IMPORTE/100,2) END),''),13,' ') PRORROGA,
LPAD(IFNULL((CASE WHEN (-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())) < 31 THEN (CASE WHEN (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) < 3 THEN 3 ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 3 END) ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 15 END),''),10,' ') PUNITORIO,
RPAD(SUBSTR(IFNULL(ce.DETALLE,''),1,50),50,' ') ESTADOCE
FROM (SELECT ca.*
FROM CARTERA ca
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA
JOIN LOTES lt ON lt.IDLOTE=di.IDLOTE AND lt.ACTUAL=1
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA <> ca.IDCARTERA AND tmp.IDMOROSO = ca.IDMOROSO) ca
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN PRORROGAS pr ON ca.AUXNUEVO=pr.PRORROGAS
LEFT JOIN DISTRIBUCION di ON di.IDCARTERA=ca.IDCARTERA
LEFT JOIN USUARIOS us ON us.IDUSUARIO=di.IDUSUARIO
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: CREDITOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['SUCURSAL'];
$buffer.= $rs['NUMCREDITO'];
$buffer.= $rs['PERFIL'];
$buffer.= $rs['DIASC'];
$buffer.= $rs['FECVEN'];
$buffer.= $rs['CUOTAS'];
$buffer.= $rs['ULTIMACUOTA'];
$buffer.= $rs['IMPORTE'];
$buffer.= $rs['SALDOTOMAR'];
$buffer.= $rs['PRORROGA'];
$buffer.= $rs['PUNITORIO'];
$buffer.= $rs['ESTADOCE'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** CREDITOS *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** PRODUCTOS **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['PRODUCTOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['PRODUCTOS']);
// get query
$SQL = "SELECT LPAD(IFNULL(p.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(p.IDPRODUCTO,''),11,' ') IDPRODUCTO,
RPAD(SUBSTR(IFNULL(p.PRODUCTO,''),1,255),255,' ') PRODUCTO
FROM PRODUCTOS p
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA = p.IDCARTERA";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: PRODUCTOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['IDPRODUCTO'];
$buffer.= $rs['PRODUCTO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** PRODUCTOS **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******* SEGUIMIENTO *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['SEGUIMIENTO'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['SEGUIMIENTO']);
// get query
$SQL = "SELECT LPAD(IFNULL(s.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(s.IDSEGUIMIENTO,''),11,' ') IDSEGUIMIENTO,
RPAD(SUBSTR(IFNULL(s.TELEFONO,''),1,255),255,' ') TELEFONO,
RPAD(SUBSTR(IFNULL(s.COMENTARIOS,''),1,8000),8000,' ') COMENTARIOS,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
LPAD(IFNULL(s.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(s.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(s.ESTADO,'0') ESTADO
FROM SEGUIMIENTO s
JOIN CARTERA ca ON s.IDCARTERA=ca.IDCARTERA
JOIN CARTERA ce ON ca.IDMOROSO=ce.IDMOROSO AND ce.IDCARTERA=s.IDCARTERA
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA = s.IDCARTERA
WHERE s.ESTADO=1
AND s.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: SEGUIMIENTO".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['IDSEGUIMIENTO'];
$buffer.= $rs['TELEFONO'];
$buffer.= $rs['COMENTARIOS'];
$buffer.= $rs['NUMCREDITO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******* SEGUIMIENTO *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** TABLA TEMPORAL **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
$SQL = "DROP TABLE EXPORT_CALLEXT_".$DATE;
mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." DROP: EXPORT_CALLEXT_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** TABLA TEMPORAL **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** TAR *************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// tar/gzip files
shell_exec("cd ".$PATH."; tar --remove-files -zcvf ".$DATE.".tar.gz *_".$DATE.".txt");
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** tar *************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** SFTP ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// connect to SFTP server (port 22)
if ($SFTP) {
$sftp = new Net_SFTP($SFTPSERVER, $SFTPPORT);
if (!$sftp->login($SFTPUSER, $SFTPPASS)) {
savelog('ERR SFTP CONNECT: '.$SFTPSERVER);
$SFTP = 0;
} else {
savelog('OK SFTP CONNECT: '.$SFTPSERVER);
$sftp->chdir($SFTPPATH);
savelog(((!$sftp->put($DATE.$ZIPEXT, $PATH.$DATE.$ZIPEXT, NET_SFTP_LOCAL_FILE)) ? 'ERR SFTP: ':'OK SFTP:').$DATE.$ZIPEXT);
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** SFTP ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ FTP ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// connect to FTP server (port 21)
if (!$SFTP) {
$conn_id = ftp_connect($FTPSERVER, 21);
savelog(((!$conn_id) ? 'ERR FTP: ':'OK FTP: ').$FTPSERVER);
if ($conn_id) {
// send access parameters
ftp_login($conn_id, $FTPUSER, $FTPPASS);
// turn on passive mode transfers
ftp_pasv ($conn_id, true);
$arr_size=count($FILE);
// perform file upload
$upload = ftp_put($conn_id, $FTPPATH.$DATE.$ZIPEXT, $PATH.$DATE.$ZIPEXT, FTP_BINARY);
// check upload status:
savelog(((!$upload) ? 'ERR FTP: ':'OK FTP: ').$DATE.$ZIPEXT);
// close the FTP stream
ftp_close($conn_id);
}
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ FTP ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/*********** MOVE ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// move files to sent folder
savelog(((!rename($PATH.$DATE.$ZIPEXT, $SENTPATH.$DATE.$ZIPEXT)) ? 'ERR MOVE: ':'OK MOVE: ').$DATE.$ZIPEXT);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*********** MOVE ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
?>
<file_sep>INSERT INTO INICIO SELECT d.GRUPO,CODIGO,NOMBRE,SUM(CANTIDADPENDIENTE)CANTIDADPENDIENTE,SUM(PENDIENTE)PENDIENTE,SUM(CANTIDADTOTAL)CANTIDADTOTAL,
SUM(CANTIDADCANCELADO)CANTIDADCANCELADO,SUM(CANCELADO) CANCELADO,SUM(CANTIDADPROMESA)CANTIDADPROMESA,SUM(PROMESA) PROMESA,
SUM(TOTAL)TOTAL,SUM(TOTALCARTERAPROP)TOTALCARTERAPROP,SUM(TOTALCARTERA)TOTALCARTERA,SUM(PENDIENTE)/SUM(TOTALCARTERAPROP)*100 EFICIENCIA FROM (
SELECT SUM( TOTALCARTERAPROP)TOTALCARTERAPROP, SUM( TOTALCARTERA)TOTALCARTERA,IDUSUARIO,GRPTRAMO
FROM(
SELECT a.TOTAL,ROUND(a.TOTAL/b.TOTAL*c.TOTALCARTERA*1000) TOTALCARTERAPROP,TOTALCARTERA*1000 TOTALCARTERA,a.IDUSUARIO,a.IDSUCURSAL,a.GRPTRAMO FROM
(SELECT SUM(MONTO)TOTAL,IDUSUARIO,pe.GRPTRAMO,SUCURSAL IDSUCURSAL FROM DISTRIBUCION di
JOIN PERFILES pe ON di.IDPERFIL=pe.IDPERFIL
GROUP BY IDUSUARIO,pe.GRPTRAMO,SUCURSAL
) a
JOIN (SELECT SUM(MONTO)TOTAL,SUCURSAL IDSUCURSAL ,pe.GRPTRAMO FROM DISTRIBUCION di
JOIN PERFILES pe ON di.IDPERFIL=pe.IDPERFIL
GROUP BY SUCURSAL,pe.GRPTRAMO) b ON b.IDSUCURSAL=a.IDSUCURSAL AND a.GRPTRAMO=b.GRPTRAMO
JOIN TOTALCARTERA c ON a.IDSUCURSAL=c.IDSUCURSAL
ORDER BY a.IDSUCURSAL
) a GROUP BY IDUSUARIO,GRPTRAMO
) a
JOIN (
SELECT us.IDUSUARIO, us.CODIGO, TRIM(CONCAT(us.Nombre,' ',us.Apellido)) NOMBRE,
SUM(CASE
WHEN(ca.FECHAPROCESO=maca.FECHAPROCESO AND pedi.IDPERFIL = pe.IDPERFIL) THEN
1
ELSE
0
END) CANTIDADPENDIENTE,
SUM(CASE
WHEN(ca.FECHAPROCESO=maca.FECHAPROCESO AND pedi.IDPERFIL = pe.IDPERFIL) THEN
di.MONTO
ELSE
0
END) PENDIENTE,
SUM(CASE
WHEN(ca.FECHAPROCESO<maca.FECHAPROCESO OR pedi.IDPERFIL <> pe.IDPERFIL) THEN
1
ELSE
0
END) CANTIDADCANCELADO,
SUM(CASE
WHEN(ca.FECHAPROCESO<maca.FECHAPROCESO OR pedi.IDPERFIL <> pe.IDPERFIL) THEN
di.MONTO
ELSE
0
END) CANCELADO,
SUM(CASE
WHEN ca.ESTADO=3 AND DATE(ca.FECHAAGENDA)>=ca.FECHAPROCESO AND (ca.FECHAPROCESO=maca.FECHAPROCESO AND pedi.IDPERFIL = pe.IDPERFIL) THEN
1
ELSE
0
END) CANTIDADPROMESA,
SUM(CASE
WHEN ca.ESTADO=3 AND DATE(ca.FECHAAGENDA)>=ca.FECHAPROCESO AND (ca.FECHAPROCESO=maca.FECHAPROCESO AND pedi.IDPERFIL = pe.IDPERFIL) THEN
di.MONTO
ELSE
0
END) PROMESA,
COUNT(*) CantidadTotal,
SUM(di.MONTO) TOTAL,
LOWER(gr.GRUPO) GRUPO,pedi.GRPTRAMO
FROM CARTERA ca
JOIN (SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA) maca ON 1=1
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA AND di.IDLOTE=1
JOIN PERFILES pedi ON di.IDPERFIL=pedi.IDPERFIL
JOIN USUARIOS us ON di.IDUSUARIO=us.IDUSUARIO
JOIN GRUPOS gr ON di.IDGRUPO=gr.IDGRUPO
JOIN SUCURSALES su ON ca.SUCURSAL=su.SUCURSAL
LEFT JOIN USUARIOPERFILES upe ON su.IDSUCURSAL=upe.IDSUCURSAL AND upe.IDUSUARIO=di.IDUSUARIO AND upe.IDPERFIL=pe.IDPERFIL
GROUP BY us.IDUSUARIO, us.CODIGO,TRIM(CONCAT(us.Nombre,' ',us.Apellido)),LOWER(gr.GRUPO),pedi.GRPTRAMO ORDER BY LOWER(gr.GRUPO),TRIM(CONCAT(us.Nombre,' ',us.Apellido))
) d ON a.IDUSUARIO=d.IDUSUARIO AND d.GRPTRAMO=a.GRPTRAMO
GROUP BY d.GRUPO,CODIGO,NOMBRE
<file_sep>SELECT flag FROM flagVigenteEnDistribucion limit 1;
<file_sep>UPDATE flagVigenteEnDistribucion SET FLAG=<file_sep>INSERT INTO CARTERA_Backup SELECT IDCARTERA,IDMOROSO,IDGARANTE,TIPOCARTERA,TIPOPROCESO,FECHAPROCESO,SUCURSAL,
NUMCREDITO,DOLARES,IMPORTE,FECHA,CUOTAS,ULTIMACUOTA,DIAS,SALDO,FRAVSAENZ,CUOTASATRASADAS,AUXNUEVO,CANTATRASADAS,
CATEGORIA,TIPOCREDITO,VENDEDOR,OBSERVACIONES,DEBEPAGARINT,FECVENCIMIENTO,SALDOBCO,TIPOTARJETA,SALDOPESOS,SALDODOLAR,
CANTIMP,FECHAAGENDA,FECHAALTA,FECHABAJA,ESTADO,DEBAUTO,now()
from CARTERA;<file_sep>fecha=$(date +%d-%m-%Y)
hora=$(date +%H:%M)
mensaje=/home/callcenter/interfaz/proceso/mensajePlantillaReporteEvolutivo.txt
echo -e "Estimados, adjuntamos los reportes correspondientes a la evolucion de las cobranzas del mes en curso, generados el dia $fecha a las $hora HS.\n\nSaludos\n\nSistemas-Call Mora" >$mensaje<file_sep>queries=/home/callcenter/interfaz/proceso/queries
queriesLog=$2
ejecutarQuery ()
{
#tomo query a query la ejecuto y registro su output(si fue correcto queda un espacio en blanco
#o el resultado de salida si es un select y si hay error el error)
maximo=$(wc -l $1 | cut -d " " -f 1)
let maximo=maximo+1
for i in $(seq 1 $maximo)
do
query=$(cat $1 | head -$i | tail -1)
#echo $query
error=$(mysql -se "$query" 2>&1)
fecha=$(date +%d-%m-%Y-%H.%M)
if [ "$(echo $error | cut -d " " -f1)" == "ERROR" ]
then
echo -e "===============================================================================\n$fecha\n$query\n$error">>$queriesLog
else
echo -e "===============================================================================\n$fecha\n$query">>$queriesLog
fi
done
}
#este script debe ser llamado desde otro script, hay que mandarle como primer parametro la query ( en un archivo guardado) y el log asociado ( archivo)
ejecutarQuery $1 $2
<file_sep>if [ $1 -eq 0 ]
then
echo -e "===========================\nEl cierre de mes se realizo correctamente\n===========================" >> /home/callcenter/interfaz/proceso/archivos/message.txt
else
echo -e "===========================\nERROR: en el cierre de mes\n===========================" >> /home/callcenter/interfaz/proceso/archivos/message.txt
fi<file_sep>generarReporte=/home/callcenter/interfaz/proceso/generarReporte.sh
paso1=/home/callcenter/interfaz/proceso/queries/reporteDiarioEvolutivoPaso1.sql
paso2=/home/callcenter/interfaz/proceso/queries/reporteDiarioEvolutivoPaso2.sql
paso3=reporteDiarioEvolutivoPaso3PorGrupo.sql
paso4=reporteDiarioEvolutivoPaso4PorUsuario.sql
ejecutarQuery=/home/callcenter/interfaz/proceso/ejecutarQuery.sh
eMail=/home/callcenter/interfaz/proceso/eMail.sh
/home/callcenter/interfaz/proceso/plantillaMensaje.sh > mensajePlantillaReporteEvolutivo.txt
mensaje=$(cat /home/callcenter/interfaz/proceso/mensajePlantillaReporteEvolutivo.txt)
reportes=/home/callcenter/interfaz/proceso/reportes
archivo1=/home/callcenter/interfaz/proceso/ultimaFechaGuardada1.txt
archivo2=/home/callcenter/interfaz/proceso/ultimaFechaGuardada2.txt
$ejecutarQuery $paso1
$ejecutarQuery $paso2
$generarReporte $paso3 reporteDiarioEvolutivoPorGrupo $archivo1
$generarReporte $paso4 reporteDiarioEvolutivoPorUsuario $archivo2
ultimaFecha1=$(cat $archivo1)
ultimaFecha2=$(cat $archivo2)
$eMail <EMAIL> "[Desarrollo] Reporte" "$mensaje" $reportes/reporteDiarioEvolutivoPorGrupo$ultimaFecha1.xls $reportes/reporteDiarioEvolutivoPorUsuario$ultimaFecha2.xls<file_sep>SELECT ca.SUCURSAL AS SUCURSAL,
ca.NUMCREDITO AS NRO_CREDITO,
grp.GRUPO as GRUPO,
(ca.SALDO+ca.SALDOBCO+ca.SALDOPESOS) AS SALDOTOMAR,
pe.PERFIL as PERFIL,
ce.DETALLE AS ESTADO_DESC,
ce.ESTADO AS ESTADO_COD,
ca.FECHAPROCESO AS FECHAPROCESO
FROM CARTERA ca
JOIN (SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA) maca ON 1=1
JOIN CONTACTOS co ON co.IDCONTACTO=ca.IDMOROSO
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN SUCURSALES su ON ca.SUCURSAL=su.SUCURSAL
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA
JOIN USUARIOS us ON us.IDUSUARIO=di.IDUSUARIO
JOIN GRUPOS grp ON grp.IDGRUPO=di.IDGRUPO
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO<maca.FECHAPROCESO OR di.IDPERFIL<>pe.IDPERFIL THEN 5
WHEN ca.ESTADO=2 AND DATE(ca.FECHAAGENDA)<=CURRENT_DATE() THEN 6
WHEN ca.ESTADO=3 AND ca.FECHAAGENDA<ca.FECHAPROCESO AND ca.FECHAPROCESO=maca.FECHAPROCESO THEN 4
WHEN ca.ESTADO=14 AND ca.FECHAAGENDA<ca.FECHAPROCESO AND ca.FECHAPROCESO=maca.FECHAPROCESO THEN 15
WHEN ca.ESTADO=7 AND ca.FECHAAGENDA<ca.FECHAPROCESO AND ca.FECHAPROCESO=maca.FECHAPROCESO THEN 9
WHEN ca.ESTADO=10 AND ca.FECHAAGENDA<ca.FECHAPROCESO AND ca.FECHAPROCESO=maca.FECHAPROCESO THEN 11
ELSE ca.ESTADO END)
WHERE CAST(CONCAT(CAST(CONCAT(ca.SUCURSAL,CAST(ca.NUMCREDITO AS CHAR)) AS SIGNED),2) AS SIGNED) NOT IN (SELECT CAST(NUMERO AS SIGNED) FROM legales_registros_copy); <file_sep>update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA001';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA002';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA003';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA004';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA005';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA006';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA007';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA008';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA009';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA010';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA011';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA012';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA013';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA014';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA015';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA016';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA017';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA018';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA019';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA020';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA021';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA022';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA023';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA024';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA025';
update USUARIOS set NOMBRE='Del<NAME>' where CODIGO='GSA026';
update USUARIOS set NOMBRE='Sosa Noelia' where CODIGO='GSA027';
update USUARIOS set NOMBRE='Fer<NAME>' where CODIGO='GSA028';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA029';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA030';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA031';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA032';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA033';
update USUARIOS set NOMBRE='Rom<NAME>' where CODIGO='GSA034';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GSA035';
update USUARIOS set NOMBRE='OPERADOR_1' where CODIGO='OPER001';
update USUARIOS set NOMBRE='OPERADOR_2' where CODIGO='OPER002';
update USUARIOS set NOMBRE='OPERADOR_3' where CODIGO='OPER003';
update USUARIOS set NOMBRE='OPERADOR_4' where CODIGO='OPER004';
update USUARIOS set NOMBRE='OPERADOR_5' where CODIGO='OPER005';
update USUARIOS set NOMBRE='OPERADOR_6' where CODIGO='OPER006';
update USUARIOS set NOMBRE='OPERADOR_7' where CODIGO='OPER007';
update USUARIOS set NOMBRE='OPERADOR_8' where CODIGO='OPER008';
update USUARIOS set NOMBRE='OPERADOR_9' where CODIGO='OPER009';
update USUARIOS set NOMBRE='OPERADOR_10' where CODIGO='OPER010';
update USUARIOS set NOMBRE='OPERADOR_11' where CODIGO='OPER011';
update USUARIOS set NOMBRE='OPERADOR_12' where CODIGO='OPER012';
update USUARIOS set NOMBRE='OPERADOR_13' where CODIGO='OPER013';
update USUARIOS set NOMBRE='OPERADOR_14' where CODIGO='OPER014';
update USUARIOS set NOMBRE='OPERADOR_15' where CODIGO='OPER015';
update USUARIOS set NOMBRE='OPERADOR_16' where CODIGO='OPER016';
update USUARIOS set NOMBRE='OPERADOR_17' where CODIGO='OPER017';
update USUARIOS set NOMBRE='OPERADOR_18' where CODIGO='OPER018';
update USUARIOS set NOMBRE='OPERADOR_19' where CODIGO='OPER019';
update USUARIOS set NOMBRE='OPERADOR_20' where CODIGO='OPER020';
update USUARIOS set NOMBRE='OPERADOR_21' where CODIGO='OPER021';
update USUARIOS set NOMBRE='OPERADOR_22' where CODIGO='OPER022';
update USUARIOS set NOMBRE='OPERADOR_23' where CODIGO='OPER023';
update USUARIOS set NOMBRE='OPERADOR_24' where CODIGO='OPER024';
update USUARIOS set NOMBRE='OPERADOR_25' where CODIGO='OPER025';
update USUARIOS set NOMBRE='OPERADOR_26' where CODIGO='OPER026';
update USUARIOS set NOMBRE='OPERADOR_27' where CODIGO='OPER027';
update USUARIOS set NOMBRE='OPERADOR_28' where CODIGO='OPER028';
update USUARIOS set NOMBRE='OPERADOR_29' where CODIGO='OPER029';
update USUARIOS set NOMBRE='OPERADOR_30' where CODIGO='OPER030';
update USUARIOS set NOMBRE='Russo, Roxana Fernanda' where CODIGO='GAR031';
update USUARIOS set NOMBRE='Benitez, S<NAME>aya' where CODIGO='GAR032';
update USUARIOS set NOMBRE='<NAME>, <NAME>' where CODIGO='GAR033';
update USUARIOS set NOMBRE='Debora Degleve' where CODIGO='GAR034';
update USUARIOS set NOMBRE='Spiteri, Natalia Soledad' where CODIGO='GAR035';
update USUARIOS set NOMBRE='Spinelli, <NAME>' where CODIGO='GAR036';
update USUARIOS set NOMBRE='Chiarante, Carolina' where CODIGO='GAR037';
update USUARIOS set NOMBRE='Caraballo, Flavia' where CODIGO='GAR038';
update USUARIOS set NOMBRE='Millares, Magdalena Victoria' where CODIGO='GAR039';
update USUARIOS set NOMBRE='Caseres, <NAME>' where CODIGO='GAR040';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR041';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR042';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR043';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR044';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR045';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR046';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR047';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR048';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR049';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR050';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR051';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR052';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR053';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR054';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR055';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR056';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR057';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR058';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR059';
update USUARIOS set NOMBRE='<NAME>am<NAME>' where CODIGO='GAR060';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR061';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR062';
update USUARIOS set NOMBRE='Lecumberry, <NAME>' where CODIGO='GAR063';
update USUARIOS set NOMBRE='Renus, <NAME>' where CODIGO='GAR064';
update USUARIOS set NOMBRE='Giusti , <NAME>' where CODIGO='GAR065';
update USUARIOS set NOMBRE='Cardozo , <NAME>' where CODIGO='GAR066';
update USUARIOS set NOMBRE='Monzon, <NAME>' where CODIGO='GAR067';
update USUARIOS set NOMBRE='<NAME>, <NAME>' where CODIGO='GAR068';
update USUARIOS set NOMBRE='Migliorisi, <NAME>' where CODIGO='GAR069';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR070';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR071';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR072';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR073';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR074';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR075';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR076';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='GAR077';
update USUARIOS set NOMBRE='RE, SABRINA' where CODIGO='3497';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='7393';
update USUARIOS set NOMBRE='VALDIVIESO, FACUNDO' where CODIGO='3990';
update USUARIOS set NOMBRE='PONCE, EVELINE' where CODIGO='3321';
update USUARIOS set NOMBRE='PORCEL, ROCIO' where CODIGO='7449';
update USUARIOS set NOMBRE='DORADO, SILVIA' where CODIGO='5908';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='10168';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='7571';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='7467';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='7383';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='2005';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='6677';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='5368';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='8712';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='5302';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='8265';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='8280';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='6492';
update USUARIOS set NOMBRE='<NAME>' where CODIGO='3075';
update USUARIOS set NOMBRE='Usuario 1' where CODIGO='ARG001';
update USUARIOS set NOMBRE='Usuario 2' where CODIGO='ARG002';
update USUARIOS set NOMBRE='Usuario 3' where CODIGO='ARG003';
update USUARIOS set NOMBRE='Usuario 4' where CODIGO='ARG004';
update USUARIOS set NOMBRE='Usuario 5' where CODIGO='ARG005';
update USUARIOS set NOMBRE='Usuario 6' where CODIGO='ARG006';
update USUARIOS set NOMBRE='Usuario 7' where CODIGO='ARG007';
update USUARIOS set NOMBRE='Usuario 8' where CODIGO='ARG008';
update USUARIOS set NOMBRE='Usuario 9' where CODIGO='ARG009';
update USUARIOS set NOMBRE='Usuario 10' where CODIGO='ARG010';
update USUARIOS set NOMBRE='Usuario 11' where CODIGO='ARG011';
update USUARIOS set NOMBRE='Usuario 12' where CODIGO='ARG012';
update USUARIOS set NOMBRE='Usuario 13' where CODIGO='ARG013';
update USUARIOS set NOMBRE='Usuario 14' where CODIGO='ARG014';
update USUARIOS set NOMBRE='Usuario 15' where CODIGO='ARG015';
update USUARIOS set NOMBRE='Usuario 16' where CODIGO='ARG016';
update USUARIOS set NOMBRE='Usuario 17' where CODIGO='ARG017';
update USUARIOS set NOMBRE='Usuario 18' where CODIGO='ARG018';
update USUARIOS set NOMBRE='Usuario 19' where CODIGO='ARG019';
update USUARIOS set NOMBRE='Usuario 20' where CODIGO='ARG020';
update USUARIOS set NOMBRE='Usuario 21' where CODIGO='ARG021';
update USUARIOS set NOMBRE='Usuario 22' where CODIGO='ARG022';
update USUARIOS set NOMBRE='Usuario 23' where CODIGO='ARG023';
update USUARIOS set NOMBRE='Usuario 24' where CODIGO='ARG024';
update USUARIOS set NOMBRE='Usuario 25' where CODIGO='ARG025';
update USUARIOS set NOMBRE='Usuario 26' where CODIGO='ARG026';
update USUARIOS set NOMBRE='Usuario 27' where CODIGO='ARG027';
update USUARIOS set NOMBRE='' where CODIGO='WPCS01';
update USUARIOS set NOMBRE='' where CODIGO='WPCS02';
update USUARIOS set NOMBRE='' where CODIGO='WPCS03';
update USUARIOS set NOMBRE='' where CODIGO='WPCS04';
update USUARIOS set NOMBRE='' where CODIGO='WPCS05';
update USUARIOS set NOMBRE='' where CODIGO='WPCS06';
update USUARIOS set NOMBRE='' where CODIGO='WPCS07';
update USUARIOS set NOMBRE='Usuario 301' where CODIGO='WPC301';
update USUARIOS set NOMBRE='Usuario 302' where CODIGO='WPC302';
update USUARIOS set NOMBRE='Usuario 303' where CODIGO='WPC303';
update USUARIOS set NOMBRE='Usuario 304' where CODIGO='WPC304';
update USUARIOS set NOMBRE='Usuario 305' where CODIGO='WPC305';
update USUARIOS set NOMBRE='Usuario 306' where CODIGO='WPC306';
update USUARIOS set NOMBRE='Usuario 307' where CODIGO='WPC307';
update USUARIOS set NOMBRE='Usuario 308' where CODIGO='WPC308';
update USUARIOS set NOMBRE='Usuario 309' where CODIGO='WPC309';
update USUARIOS set NOMBRE='Usuario 310' where CODIGO='WPC310';
update USUARIOS set NOMBRE='Usuario 311' where CODIGO='WPC311';
update USUARIOS set NOMBRE='Usuario 312' where CODIGO='WPC312';
update USUARIOS set NOMBRE='Usuario 313' where CODIGO='WPC313';
update USUARIOS set NOMBRE='Usuario 314' where CODIGO='WPC314';
update USUARIOS set NOMBRE='Usuario 315' where CODIGO='WPC315';
update USUARIOS set NOMBRE='Usuario 316' where CODIGO='WPC316';
update USUARIOS set NOMBRE='Usuario 317' where CODIGO='WPC317';
update USUARIOS set NOMBRE='Usuario 318' where CODIGO='WPC318';
update USUARIOS set NOMBRE='Usuario 319' where CODIGO='WPC319';
update USUARIOS set NOMBRE='Usuario 320' where CODIGO='WPC320';
update USUARIOS set NOMBRE='Usuario 321' where CODIGO='WPC321';
update USUARIOS set NOMBRE='Usuario 322' where CODIGO='WPC322';
<file_sep>varLog=/home/callcenter/interfaz/proceso/logs/procesoDiarioMes.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mes=$(date +%D | cut -d "/" -f 1)
dia=$(date +%D | cut -d "/" -f 2)
anio=$(date +%D | cut -d "/" -f 3)
cerrarMes=/home/callcenter/interfaz/proceso/cierreDeMes.sh
armarMensaje=/home/callcenter/interfaz/proceso/mailingProcesoDistribucion.sh
#TENER EN CUENTA QUE SE LE DEBE SUMAR UN DIA AL DIA DE CIERRE, PORQUE SE PROCESA LA MADRUGADA DEL DIA POSTERIOR
if [[ $dia -eq 28 && $mes -eq 12 && $anio -eq 17 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 1 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 27 && $mes -eq 2 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 27 && $mes -eq 4 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 5 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 29 && $mes -eq 6 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 29 && $mes -eq 7 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 8 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 28 && $mes -eq 9 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 10 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 29 && $mes -eq 11 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 28 && $mes -eq 12 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
$armarMensaje $error
$comprobar $error $varLog cierreDeMes.sh
fi<file_sep>-- REPORTE DIARIO EVOLUCIÓN DE CARTERA
-- PASO 1
DELETE FROM callcenter.HSTREPORTE1_DIARIA;
-- PASO 2
insert into callcenter.HSTREPORTE1_DIARIA
(PERIODO,
IDUSUARIO,
CODIGO,
NOMBRE,
CANTIDADPENDIENTE,
PENDIENTE,
CANTIDADCANCELADO,
CANCELADO,
CANTIDADPROMESA,
PROMESA,
CantidadTotal,
TOTAL,
GRUPO,
TOTALCARTERAPROP)
select concat(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE())) PERIODO,
d.IDUSUARIO,
CODIGO,
NOMBRE,
sum(CANTIDADPENDIENTE)CANTIDADPENDIENTE,
sum(PENDIENTE)PENDIENTE,
sum(CANTIDADCANCELADO)CANTIDADCANCELADO,
sum(CANCELADO) CANCELADO,
sum(CANTIDADPROMESA)CANTIDADPROMESA,
sum(PROMESA) PROMESA,
sum(CANTIDADTOTAL)CANTIDADTOTAL,
sum(TOTAL)TOTAL,
d.GRUPO,
sum(TOTALCARTERAPROP)TOTALCARTERAPROP
from (
select sum( TOTALCARTERAPROP)TOTALCARTERAPROP, sum( TOTALCARTERA)TOTALCARTERA,IDUSUARIO,GRPTRAMO from(
select a.TOTAL,round(a.TOTAL/b.TOTAL*c.TOTALCARTERA*1000) TOTALCARTERAPROP,TOTALCARTERA*1000 TOTALCARTERA,a.IDUSUARIO,a.IDSUCURSAL,a.GRPTRAMO from
(select sum(MONTO)TOTAL,IDUSUARIO,pe.GRPTRAMO,SUCURSAL IDSUCURSAL from DISTRIBUCION di
join PERFILES pe on di.IDPERFIL=pe.IDPERFIL
group by IDUSUARIO,pe.GRPTRAMO,SUCURSAL) a
join (select sum(MONTO)TOTAL,SUCURSAL IDSUCURSAL ,pe.GRPTRAMO from DISTRIBUCION di
join PERFILES pe on di.IDPERFIL=pe.IDPERFIL
group by SUCURSAL,pe.GRPTRAMO) b on b.IDSUCURSAL=a.IDSUCURSAL and a.GRPTRAMO=b.GRPTRAMO
join TOTALCARTERA c on a.IDSUCURSAL=c.IDSUCURSAL order by a.IDSUCURSAL
) a group by IDUSUARIO,GRPTRAMO
) a
join (
select us.IDUSUARIO, us.CODIGO, trim(concat(Nombre,' ',Apellido)) NOMBRE,
sum(Case
when(ca.FECHAPROCESO=maca.FECHAPROCESO ) then
1
else
0
end) CANTIDADPENDIENTE,
sum(Case
when(ca.FECHAPROCESO=maca.FECHAPROCESO ) then
di.MONTO
else
0
end) PENDIENTE,
sum(Case
when(ca.FECHAPROCESO<maca.FECHAPROCESO ) then
1
else
0
end) CANTIDADCANCELADO,
sum(Case
when(ca.FECHAPROCESO<maca.FECHAPROCESO ) then
di.MONTO
else
0
end) CANCELADO,
sum(Case
when ca.ESTADO=3 and (ca.FECHAPROCESO=maca.FECHAPROCESO ) then
1
else
0
end) CANTIDADPROMESA,
sum(Case
when ca.ESTADO=3 and (ca.FECHAPROCESO=maca.FECHAPROCESO ) then
di.MONTO
else
0
end) PROMESA,
count(*) CantidadTotal,
Sum(di.MONTO) TOTAL,
lower(gr.GRUPO) GRUPO,pedi.GRPTRAMO
from CARTERA ca
join (select max(FECHAPROCESO)FECHAPROCESO from CARTERA) maca on 1=1
join DISTRIBUCION di on ca.IDCARTERA=di.IDCARTERA and di.IDLOTE=1
join PERFILES pedi on di.IDPERFIL=pedi.IDPERFIL
join USUARIOS us on di.IDUSUARIO=us.IDUSUARIO
join GRUPOS gr on di.IDGRUPO=gr.IDGRUPO
join SUCURSALES su on ca.SUCURSAL=su.SUCURSAL
left join USUARIOPERFILES upe on su.IDSUCURSAL=upe.IDSUCURSAL and upe.IDUSUARIO=di.IDUSUARIO
group by us.IDUSUARIO, us.CODIGO,trim(concat(Nombre,' ',Apellido)),lower(gr.GRUPO),pedi.GRPTRAMO
order by lower(gr.GRUPO),trim(concat(Nombre,' ',Apellido))
) d on a.IDUSUARIO=d.IDUSUARIO and d.GRPTRAMO=a.GRPTRAMO
group by d.GRUPO,CODIGO,NOMBRE;
-- PASO 3 - QUERY POR GRUPOS
SELECT
GRUPO,
SUM(CANTIDADPENDIENTE) CANTIDADPENDIENTE,
ROUND(SUM(PENDIENTE)) PENDIENTE,
SUM(CANTIDADCANCELADO)CANTIDADCANCELADO,
ROUND(SUM(CANCELADO)) CANCELADO,
SUM(CANTIDADTOTAL)CANTIDADTOTAL,
ROUND(SUM(TOTAL)) TOTAL,
SUM(TOTALCARTERAPROP) TOTALCARTERA,
SUM(CANCELADO)/SUM(TOTAL)*100 RECUPERO,
SUM(PENDIENTE)/SUM(TOTALCARTERAPROP)*100 Eficiencia,
SUM(TOTAL)/SUM(TOTALCARTERAPROP)*100 EFICIENCIA_INICIAL
FROM HSTREPORTE1_DIARIA WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()))
GROUP BY GRUPO;
-- PASO 4 - QUERY POR USUARIO
SELECT
CODIGO,
GRUPO,
NOMBRE,
CANTIDADPENDIENTE,
ROUND(PENDIENTE) PENDIENTE,
CANTIDADCANCELADO,
ROUND(CANCELADO) CANCELADO,
ROUND(TOTAL) TOTAL,
TOTALCARTERAPROP,
CANCELADO/TOTAL*100 RECUPERO,
PENDIENTE/TOTALCARTERAPROP*100 Eficiencia,
TOTAL/TOTALCARTERAPROP*100 EFICIENCIA_INICIAL
FROM HSTREPORTE1_DIARIA WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()));<file_sep>Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA001','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA002','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA003','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA004','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA005','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA006','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA007','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA008','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA009','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA010','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA011','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA012','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA013','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA014','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA015','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA016','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA017','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA018','Chanquia Braian');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA019','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA020','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA021','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA022','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA023','V<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA024','Pietrafesa Marcelo');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA025','Espada Mariana');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA026','Delgado Paola');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA027','Sosa Noelia');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA028','Ferreira Milena');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA029','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA030','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA031','Sanche<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA032','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA033','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA034','Romero Yansan');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GSA035','Balassanian Mariana');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER001','OPERADOR_1');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER002','OPERADOR_2');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER003','OPERADOR_3');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER004','OPERADOR_4');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER005','OPERADOR_5');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER006','OPERADOR_6');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER007','OPERADOR_7');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER008','OPERADOR_8');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER009','OPERADOR_9');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER010','OPERADOR_10');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER011','OPERADOR_11');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER012','OPERADOR_12');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER013','OPERADOR_13');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER014','OPERADOR_14');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER015','OPERADOR_15');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER016','OPERADOR_16');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER017','OPERADOR_17');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER018','OPERADOR_18');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER019','OPERADOR_19');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER020','OPERADOR_20');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER021','OPERADOR_21');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER022','OPERADOR_22');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER023','OPERADOR_23');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER024','OPERADOR_24');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER025','OPERADOR_25');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER026','OPERADOR_26');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER027','OPERADOR_27');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER028','OPERADOR_28');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER029','OPERADOR_29');
Insert into USUARIOS(CODIGO,NOMBRE) values ('OPER030','OPERADOR_30');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR031','Russo, Roxana Fernanda');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR032','Benitez, Sara Soraya');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR033','<NAME>, <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR034','Debora Degleve');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR035','Spiteri, Natalia Soledad');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR036','Spinelli, F<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR037','Chiarante, Carolina');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR038','Caraballo, Flavia');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR039','Millares, Magdalena Victoria');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR040','Caseres, C<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR041','Paola Carbajal');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR042','Peña Sanche<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR043','H<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR044','Goicoechea Mariela Soledad');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR045','Mallo Carolina Lorena');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR046','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR047','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR048','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR049','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR050','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR051','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR052','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR053','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR054','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR055','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR056','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR057','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR058','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR059','Zapata, Doraly');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR060','Quinteros Yamila Constanza');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR061','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR062','Arcos, Jessica');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR063','Lecumberry, <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR064','Renus, <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR065','Giusti , <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR066','Cardozo , <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR067','Monzon, <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR068','<NAME>, <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR069','Migliorisi, <NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR070','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR071','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR072','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR073','Esquivel Liza Sabina');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR074','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR075','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR076','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('GAR077','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('3497','RE, SABRINA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('7393','TORRES, NANCY');
Insert into USUARIOS(CODIGO,NOMBRE) values ('3990','VALDIVIESO, FACUNDO');
Insert into USUARIOS(CODIGO,NOMBRE) values ('3321','PONCE, EVELINE');
Insert into USUARIOS(CODIGO,NOMBRE) values ('7449','PORCEL, ROCIO');
Insert into USUARIOS(CODIGO,NOMBRE) values ('5908','DORADO, SILVIA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('10168','SALVATIERRA, RICARDO');
Insert into USUARIOS(CODIGO,NOMBRE) values ('7571','RODRIGUEZ, ANALIA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('7467','MACAYA, LILIANA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('7383','RETTA, GIMENA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('2005','DOMINGUEZ, PAOLA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('6677','PEREZ, CLAUDIA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('5368','ROBLEDO, LAURA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('8712','ROJAS, MARIA FLAVIA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('5302','MANNO, KARINA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('8265','BRIGNARDELO, GABRIELA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('8280','ROJAS, ROMINA');
Insert into USUARIOS(CODIGO,NOMBRE) values ('6492','BENEGAS, MIRIAM');
Insert into USUARIOS(CODIGO,NOMBRE) values ('3075','<NAME>');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG001','Usuario 1');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG002','Usuario 2');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG003','Usuario 3');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG004','Usuario 4');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG005','Usuario 5');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG006','Usuario 6');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG007','Usuario 7');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG008','Usuario 8');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG009','Usuario 9');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG010','Usuario 10');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG011','Usuario 11');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG012','Usuario 12');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG013','Usuario 13');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG014','Usuario 14');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG015','Usuario 15');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG016','Usuario 16');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG017','Usuario 17');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG018','Usuario 18');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG019','Usuario 19');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG020','Usuario 20');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG021','Usuario 21');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG022','Usuario 22');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG023','Usuario 23');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG024','Usuario 24');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG025','Usuario 25');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG026','Usuario 26');
Insert into USUARIOS(CODIGO,NOMBRE) values ('ARG027','Usuario 27');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS01','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS02','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS03','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS04','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS05','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS06','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPCS07','');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC301','Usuario 301');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC302','Usuario 302');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC303','Usuario 303');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC304','Usuario 304');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC305','Usuario 305');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC306','Usuario 306');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC307','Usuario 307');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC308','Usuario 308');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC309','Usuario 309');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC310','Usuario 310');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC311','Usuario 311');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC312','Usuario 312');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC313','Usuario 313');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC314','Usuario 314');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC315','Usuario 315');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC316','Usuario 316');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC317','Usuario 317');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC318','Usuario 318');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC319','Usuario 319');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC320','Usuario 320');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC321','Usuario 321');
Insert into USUARIOS(CODIGO,NOMBRE) values ('WPC322','Usuario 322');
<file_sep>insert into USUARIOPERFILES_Backup select IDUSUARIOPERFILES,IDUSUARIO,IDGRUPO,IDPERFIL,IDSUCURSAL,FACTOR,TOPEPTF,
TOPE,VETRAMOCOMPLETO,FECHAALTA,FECHABAJA,ESTADO,now()
from USUARIOPERFILES;<file_sep>varLog=/home/callcenter/interfaz/proceso/logs/asignacion.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mensaje=/home/callcenter/interfaz/proceso/archivos/messageAsignacion.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
from="<EMAIL>"
queries=/home/callcenter/interfaz/proceso/queries
procesar=/home/callcenter/interfaz/procesar
query01=$queries/correrLimpiarUsuarios.sql
#query02=$queries/correrLimpiarUsuarios.sql
query1=$queries/asignacionPaso1ColumnaO.sql
query2=$queries/asignacionPaso2ColumnaP.sql
query3=$queries/asignacionPaso3ColumnaQ.sql
query4=$queries/asignacionPaso4ColumnaR.sql
query5=$queries/asignacionPaso5.sql
ejecutarQuery=/home/callcenter/interfaz/proceso/run_n_log_query.sh
queryFechaBaseCount=$(cat $queries/fechaBaseCount.sql)
queryCierreBase=$(cat $queries/fechaCierreBase.sql)
fechaHoy=$(date +%Y-%m-%d)
resultadoFlagNecesarioParaEjecutarCierre=$(mysql -se "$queryCierreBase $fechaHoy',interval -1 day) limit 1" | cut -d " " -f1)
cantResultadoFechaCierre=$(mysql -se "$queryFechaBaseCount $fechaHoy',interval -1 day) limit 1")
cantResultadoFechaInicio=$(mysql -se "$queryFechaBaseCount $fechaHoy',interval -2 day) limit 1")
cantResultadoFechaAsignacion=$(mysql -se "$queryFechaBaseCount $fechaHoy',interval 0 day) limit 1")
queryFlagDistribucionSQL=$queries/obtenerFlagDistribucion.sql
queryActualizarFlagDistribucion=$queries/actualizarFlagDistribucion.sql
fecha=$(date +%d-%m-%Y-%H.%M)
varLogCierreAsigInicio=/home/callcenter/interfaz/proceso/logs/cierreInicioAsignacionFlag.txt
ejecutarQuery ()
{
query=$(cat $1)
mysql -se "$query"
}
armarMensajeProcesoAsignacion ()
{
if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nLa asignacion del mes se realizo correctamente\n===========================" > $mensaje
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: La asignacion del mes\n===========================" > $mensaje
fi
}
procesoAsignacion ()
{
$ejecutarQuery $query01 $varLog
$ejecutarQuery $query1 $varLog
$ejecutarQuery $query2 $varLog
$ejecutarQuery $query3 $varLog
$ejecutarQuery $query4 $varLog
$ejecutarQuery $query5 $varLog
echo SE EJECUTARON TODAS LAS QUERIES CORRESPONDIENTES A LA ASIGNACION
armarMensajeProcesoAsignacion $?
mandarMailDestinatarios "Asignacion%$mensaje%1%est<EMAIL>"
$comprobar $? $varLog asignacion.sh
}
loguearCierreOAsignacionOInicio()
{
fecha=$(date +%d-%m-%Y-%H.%M)
case $1 in
1)
echo -e "=============================\n$fecha\nNo es fecha de inicio, no se realizaron actividades de inicio.\n=============================" >>$varLogCierreAsigInicio
;;
2)
echo -e "=============================\n$fecha\nSe realizaron las actividades de inicio.\n=============================" >>$varLogCierreAsigInicio
;;
3)
echo -e "=============================\n$fecha\nNo es fecha de cierre, no se realizaron actividades de cierre.\n=============================" >>$varLogCierreAsigInicio
;;
4)
echo -e "=============================\n$fecha\nSe han ejecutado las actividades de cierre y se ha modificado el valor del flag.\n=============================" >>$varLogCierreAsigInicio
;;
5)
echo -e "=============================\n$fecha\nNo se ejecutaron actividades de cierre porque si bien la fecha es de cierre, el flag Necesario y el actual no coinciden.\n=============================" >>$varLogCierreAsigInicio
;;
6)
echo -e "=============================\n$fecha\nNo es fecha de asignacion, no se ejecutaron actividades de asignación.\n=============================" >>$varLogCierreAsigInicio
;;
7)
echo -e "=============================\n$fecha\nSe han ejecutado actividades de asignacion.\n=============================" >>$varLogCierreAsigInicio
;;
*)
echo -e "=============================\n$fecha\nERROR: No recibí ningun numero como parametro.\n=============================" >>$varLogCierreAsigInicio
;;
esac
}
esFechaDeAsignacion ()
{
#Pregunto si es fecha de asignacion ( el mismo dia que la fecha de cierre del banco)
if [ $cantResultadoFechaAsignacion -eq 0 ]
then
loguearCierreOAsignacionOInicio 6
else
procesoAsignacion
loguearCierreOAsignacionOInicio 7
fi
}
mandarMailDestinatarios ()
{
#parametro 1=subject, 2=mensaje,3 cantidad De mails destinatarios, 4 en adelante lista de mails
#en realidad es un solo parametro que es un string y de el se extraen los parametros porque sino hay problemas
#ya que el mensaje tiene espacios y los espacios hace creer a linux que son muchos parametros por mas
#que el mismo se encuentre entre comillas
subject="$(echo $1 | cut -d "%" -f 1)"
destinatario="$(echo $1 | cut -d "%" -f 4)"
cantDestinatarios=$(echo $1 | cut -d "%" -f 3)
let cantDestinatarios=cantDestinatarios+3
#echo -e "echo -e $mensaje | mail -s "$subject" -r "$from" "$(echo $1 | cut -d "%" -f 3)""
for i in $(seq 4 $cantDestinatarios)
do
echo -e "$(cat $mensaje)" | mail -s "$subject" -r "$from" "$(echo $1 | cut -d "%" -f $i)"
done
}
esFechaDeAsignacion <file_sep>DELETE FROM callcenter.HSTREPORTE1_DIARIA;<file_sep>queries=/home/callcenter/interfaz/proceso/queries
archivos=/home/callcenter/interfaz/proceso/archivos
paso1=$queries/reporte_Paso1Inicio.sql
paso2=$queries/reporte_Paso2Inicio.sql
paso3=$queries/reporte_Paso3Inicio.sql
eMail=/home/callcenter/interfaz/proceso/eMailReporte.sh
reportes=/home/callcenter/interfaz/proceso/reportes
archivo1=$archivos/ultimaFechaGuardadaInicio1.txt
plantilla=/home/callcenter/interfaz/proceso/archivos/mensajePlantillaReporteDeInicio.txt
from="<EMAIL>"
varLog=/home/callcenter/interfaz/proceso/logs/reportes_log.txt
comprobarErrores ()
{
#El parametro 3 es el nombre del script ejecutado y el parametro 2 es la direccion donde se encuentra el log, parametro 1 es $?
if [ $1 -eq 0 ]
then
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nSe ejecuto correctamente $3\n==============================="
echo -e $mensajeLog >> $2
else
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nHubo un error al ejecutar $3\n==============================="
echo -e "$mensajeLog" >> $2
fi
}
generarReporte ()
{
query=$(cat $1)
fecha=$(date +%d-%m-%Y-%H.%M)
echo $fecha > $3
#Esto te pide como primer parametro la query a ejecutar de la carpeta queries, y como segundo parametro el string para generar el reporte
mysql -se "$query" > /home/callcenter/interfaz/proceso/reportes/$2$fecha.xls
error=$?
comprobarErrores $error $varLog $2
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$2" -r "$from" <EMAIL>
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$2" -r "$from" <EMAIL>
}
ejecutarQuery ()
{
query=$(cat $1)
mysql -se "$query"
}
ejecutarQuery $paso1
ejecutarQuery $paso2
generarReporte $paso3 Reporte_de_Inicio $archivo1
ultimaFecha1=$(cat $archivo1)
$eMail 1 <EMAIL> "[CallMora]-Reporte_de_Inicio" $reportes/Reporte_de_Inicio$ultimaFecha1.xls
$eMail 1 <EMAIL> "[CallMora]-Reporte_de_Inicio" $reportes/Reporte_de_Inicio$ultimaFecha1.xls
$eMail 1 <EMAIL> "[CallMora]-Reporte_de_Inicio" $reportes/Reporte_de_Inicio$ultimaFecha1.xls
$eMail 1 <EMAIL> "[CallMora]-Reporte_de_Inicio" $reportes/Reporte_de_Inicio$ultimaFecha1.xls
#$eMail 1 <EMAIL> "[CallMora]-Reporte_de_Inicio" $reportes/Reporte_de_Inicio$ultimaFecha1.xls
<file_sep><?
date_default_timezone_set ('America/Argentina/Buenos_Aires');
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** CUSTOM DATA ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// EXT: Código de Call Center Externo
$EXT = "1";
// idusuario
$IDUSUARIO = "GAR%";
// local path
$PATH = "/home/callcenter/interfaz/cc_externo/contactogarantido/out/";
$SENTPATH = "/home/callcenter/interfaz/cc_externo/contactogarantido/out/sent/";
// log
$LOG = "/home/callcenter/interfaz/cc_externo/contactogarantido/log/out.log";
// sftp
$SFTP = 1;
$SFTPSERVER = "172.16.58.3";
$SFTPPORT = "18024";
$SFTPUSER = "fvgdatos";
$SFTPPASS = "<PASSWORD>";
$SFTPPATH = "/inbox/";
// ftp
$FTPSERVER = "ftp.contactogarantido.com";
$FTPUSER = "fravega";
$FTPPASS = "<PASSWORD>";
$FTPPATH = "/inbox/";
//zip extension
$ZIPEXT = ".tar.gz";
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** CUSTOM DATA ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
// include
include("/home/callcenter/htdocs/conndb/conndb.php");
set_include_path(get_include_path() . PATH_SEPARATOR . '/home/callcenter/htdocs/phplib/phpseclib/');
include('Net/SFTP.php');
// date
$DATE = date("Ymd",time());
// files
$FILE['CARTERA'] = "CARTERA_".$DATE.".txt";
$FILE['MOROSOS'] = "MOROSOS_".$DATE.".txt";
$FILE['TELEFONOS'] = "TELEFONOS_".$DATE.".txt";
$FILE['REFERENCIAS'] = "REFERENCIAS_".$DATE.".txt";
$FILE['DIRECCIONES'] = "DIRECCIONES_".$DATE.".txt";
$FILE['EMPLEOS'] = "EMPLEOS_".$DATE.".txt";
$FILE['CREDITOS'] = "CREDITOS_".$DATE.".txt";
$FILE['PRODUCTOS'] = "PRODUCTOS_".$DATE.".txt";
$FILE['SEGUIMIENTO'] = "SEGUIMIENTO_".$DATE.".txt";
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/************ LOG ************/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
function savelog($msg) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - $msg\r\n" );
@fclose($handle);
}
}
function errorlog($type, $info, $file, $row) {
global $LOG;
if ($handle = fopen($LOG, "a")) {
@fwrite($handle, date("Y-m-d H:i:s")." - ERR --> $type: $info FILE: $file - Row $row\r\n" );
@fclose($handle);
}
}
set_error_handler(errorlog, E_USER_ERROR);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/************ LOG ************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** TABLA TEMPORAL **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
$SQL = "CREATE TABLE EXPORT_CALLEXT_".$DATE." as
SELECT DISTINCT ca.IDCARTERA, ca.IDMOROSO
FROM CARTERA ca
JOIN SUCURSALES s ON s.SUCURSAL = ca.SUCURSAL
JOIN USUARIOPERFILES up ON up.IDSUCURSAL = s.IDSUCURSAL
JOIN USUARIOS u ON u.IDUSUARIO = up.IDUSUARIO
WHERE u.CODIGO LIKE '".$IDUSUARIO."'
AND ca.TIPOPROCESO in ('1AT','002','003');";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." TABLE: EXPORT_CALLEXT_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
$SQL = "create index a343 on EXPORT_CALLEXT_".$DATE." (IDCARTERA)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." create index a343".(($result) ? "" : "\n".mysql_error($conn)));
$SQL = "create index a3423 on EXPORT_CALLEXT_".$DATE." (IDMOROSO)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." create index a3423".(($result) ? "" : "\n".mysql_error($conn)));
$SQL = "create index a3a343 on EXPORT_CALLEXT_".$DATE." (IDMOROSO,IDCARTERA)";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." create index a3a343".(($result) ? "" : "\n".mysql_error($conn)));
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** TABLA TEMPORAL **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** CARTERA **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['CARTERA'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['CARTERA']);
// get query
$SQL = "SELECT LPAD(IFNULL(ca.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(ca.IDMOROSO,''),11,' ') IDMOROSO,
RPAD(SUBSTRING(IFNULL(ca.SUCURSAL,''),1,10),10,' ') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
RPAD(SUBSTRING(IFNULL(ca.CATEGORIA,''),1,11),11,' ') CATEGORIA,
LPAD(TRUNCATE(IFNULL((ca.SALDO+ca.SALDOBCO+ca.SALDOPESOS),'0.00'),2),13,'0') SALDOTOMAR,
RPAD(SUBSTRING(IFNULL(pe.PERFIL,''),1,50),50,' ') PERFIL,
RPAD(SUBSTRING(IFNULL(ca.TIPOPROCESO,''),1,10),10,' ') TIPOPROCESO,
RPAD(SUBSTRING(IFNULL(ca.TIPOCREDITO,''),1,10),10,' ') TIPOCREDITO,
LPAD(IFNULL(ca.FECHAAGENDA,''),19,' ') FECHAAGENDA,
LPAD(IFNULL(ca.FECHAPROCESO,''),19,' ') FECHAPROCESO,
LPAD(IFNULL(ce.ESTADO,''),11,' ') CARTERAESTADO,
RPAD(SUBSTRING(IFNULL(ce.DETALLE,''),1,50),50,' ') DETALLEESTADO,
LPAD(IFNULL(ce.ORDEN,''),11,' ') ORDEN
FROM CARTERA ca
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA
JOIN EXPORT_CALLEXT_".$DATE." exp on ca.IDCARTERA=exp.IDCARTERA
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: CARTERA".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['IDMOROSO'];
$buffer.= $rs['SUCURSAL'];
$buffer.= $rs['NUMCREDITO'];
$buffer.= $rs['CATEGORIA'];
$buffer.= $rs['SALDOTOMAR'];
$buffer.= $rs['PERFIL'];
$buffer.= $rs['TIPOPROCESO'];
$buffer.= $rs['TIPOCREDITO'];
$buffer.= $rs['FECHAAGENDA'];
$buffer.= $rs['FECHAPROCESO'];
$buffer.= $rs['CARTERAESTADO'];
$buffer.= $rs['DETALLEESTADO'];
$buffer.= $rs['ORDEN'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** CARTERA **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** MOROSOS **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['MOROSOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['MOROSOS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(co.IDCONTACTO,''),11,' ') IDCONTACTO,
RPAD(SUBSTRING(IFNULL(co.NOMBRE,''),1,255),255,' ') NOMBRE,
LPAD(IFNULL(co.DOCUMENTONUMERO,''),11,' ') DOCUMENTONUMERO,
LPAD(IFNULL(co.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(co.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(co.ESTADO,'0') ESTADO
FROM CONTACTOS co
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = co.IDCONTACTO";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: MOROSOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['NOMBRE'];
$buffer.= $rs['DOCUMENTONUMERO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** MOROSOS **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********* TELEFONOS *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['TELEFONOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['TELEFONOS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(t.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(t.IDTELEFONO,''),11,' ') IDTELEFONO,
LPAD(IFNULL(t.CODIGOAREA,''),11,' ') CODIGOAREA,
LPAD(IFNULL(t.NUMERO,''),11,' ') NUMERO,
LPAD(IFNULL(t.INTERNO,''),11,' ') INTERNO,
RPAD(SUBSTRING(IFNULL(t.HORARIO,''),1,255),255,' ') HORARIO,
RPAD(SUBSTRING(IFNULL(t.COMENTARIOS,''),1,255),255,' ') COMENTARIOS,
LPAD(IFNULL(t.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(t.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(t.ESTADO,'0') ESTADO
FROM TELEFONOS t
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = t.IDCONTACTO
WHERE t.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: TELEFONOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDTELEFONO'];
$buffer.= $rs['CODIGOAREA'];
$buffer.= $rs['NUMERO'];
$buffer.= $rs['INTERNO'];
$buffer.= $rs['HORARIO'];
$buffer.= $rs['COMENTARIOS'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********* TELEFONOS *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** REFERENCIAS ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['REFERENCIAS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['REFERENCIAS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(r.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(r.IDREFERENCIA,''),11,' ') IDREFERENCIA,
RPAD(SUBSTRING(IFNULL(r.REFERENCIA,''),1,255),255,' ') REFERENCIA,
RPAD(SUBSTRING(IFNULL(r.TELEFONO,''),1,255),255,' ') TELEFONO,
LPAD(IFNULL(r.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(r.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(r.ESTADO,'0') ESTADO
FROM REFERENCIAS r
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = r.IDCONTACTO
WHERE r.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: REFERENCIAS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDREFERENCIA'];
$buffer.= $rs['REFERENCIA'];
$buffer.= $rs['TELEFONO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** REFERENCIAS ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** DIRECCIONES ********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['DIRECCIONES'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['DIRECCIONES']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(d.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(d.IDDIRECCION,''),11,' ') IDDIRECCION,
RPAD(SUBSTRING(IFNULL(d.CALLE,''),1,255),255,' ') CALLE,
RPAD(SUBSTRING(IFNULL(d.NUMERO,''),1,255),255,' ') NUMERO,
LPAD(IFNULL(d.PISO,''),11,' ') PISO,
RPAD(SUBSTRING(IFNULL(d.DEPTO,''),1,255),20,' ') DEPTO,
RPAD(SUBSTRING(IFNULL(d.LOCALIDAD,''),1,255),20,' ') LOCALIDAD,
RPAD(SUBSTRING(IFNULL(d.CODIGOPOSTAL,''),1,255),20,' ') CODIGOPOSTAL,
LPAD(IFNULL(d.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(d.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(d.ESTADO,'0') ESTADO
FROM DIRECCIONES d
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = d.IDCONTACTO
WHERE d.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: DIRECCIONES".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDDIRECCION'];
$buffer.= $rs['CALLE'];
$buffer.= $rs['NUMERO'];
$buffer.= $rs['PISO'];
$buffer.= $rs['DEPTO'];
$buffer.= $rs['LOCALIDAD'];
$buffer.= $rs['CODIGOPOSTAL'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** DIRECCIONES ********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** EMPLEOS **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['EMPLEOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['EMPLEOS']);
// get query
$SQL = "SELECT DISTINCT
LPAD(IFNULL(e.IDCONTACTO,''),11,' ') IDCONTACTO,
LPAD(IFNULL(e.IDEMPLEO,''),11,' ') IDEMPLEO,
RPAD(SUBSTRING(IFNULL(e.EMPRESA,''),1,255),255,' ') EMPRESA,
RPAD(SUBSTRING(IFNULL(e.SECCION,''),1,255),255,' ') SECCION,
RPAD(SUBSTRING(IFNULL(e.DIRCALLE,''),1,255),255,' ') DIRCALLE,
RPAD(SUBSTRING(IFNULL(e.DIRNUMERO,''),1,255),255,' ') DIRNUMERO,
LPAD(IFNULL(e.DIRPISO,''),11,' ') DIRPISO,
RPAD(SUBSTRING(IFNULL(e.DIRDEPTO,''),1,255),255,' ') DIRDEPTO,
RPAD(SUBSTRING(IFNULL(e.DIRLOCALIDAD,''),1,255),255,' ') DIRLOCALIDAD,
RPAD(SUBSTRING(IFNULL(e.DIRCODIGOPOSTAL,''),1,255),255,' ') DIRCODIGOPOSTAL,
LPAD(IFNULL(e.TELCODIGOAREA,''),11,' ') TELCODIGOAREA,
LPAD(IFNULL(e.TELNUMERO,''),11,' ') TELNUMERO,
LPAD(IFNULL(e.TELINTERNO,''),11,' ') TELINTERNO,
LPAD(IFNULL(e.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(e.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(e.ESTADO,'0') ESTADO
FROM EMPLEOS e
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDMOROSO = e.IDCONTACTO
WHERE e.EXT != '".$EXT."'";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: EMPLEOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCONTACTO'];
$buffer.= $rs['IDEMPLEO'];
$buffer.= $rs['EMPRESA'];
$buffer.= $rs['SECCION'];
$buffer.= $rs['DIRCALLE'];
$buffer.= $rs['DIRNUMERO'];
$buffer.= $rs['DIRPISO'];
$buffer.= $rs['DIRDEPTO'];
$buffer.= $rs['DIRLOCALIDAD'];
$buffer.= $rs['DIRCODIGOPOSTAL'];
$buffer.= $rs['TELCODIGOAREA'];
$buffer.= $rs['TELNUMERO'];
$buffer.= $rs['TELINTERNO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** EMPLEOS **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** CREDITOS *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['CREDITOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['CREDITOS']);
// get query
$SQL = "SELECT LPAD(IFNULL(ca.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(ca.SUCURSAL,''),11,' ') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
RPAD(SUBSTR(IFNULL(pe.PERFIL,''),1,50),50,' ') PERFIL,
LPAD(IFNULL((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())),''),11,' ') DIASC,
LPAD(SUBSTR(IFNULL((DATE_FORMAT(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),'%d/%m/%y')),''),1,8),8,' ') FECVEN,
LPAD(IFNULL(ca.CUOTAS,''),2,' ') CUOTAS,
LPAD(IFNULL(ca.ULTIMACUOTA,''),2,' ') ULTIMACUOTA,
LPAD(IFNULL(ca.IMPORTE,''),13,' ') IMPORTE,
LPAD(IFNULL((ca.SALDO+ca.SALDOBCO+ca.SALDOPESOS),''),13,' ') SALDOTOMAR,
LPAD(IFNULL((CASE WHEN TIPOCREDITO='BI' OR TIPOCREDITO = 'BY' OR TIPOCREDITO = 'AP' THEN '' ELSE ROUND(pr.PORCENTAJE*ca.IMPORTE/100,2) END),''),13,' ') PRORROGA,
LPAD(IFNULL((CASE WHEN (-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())) < 31 THEN (CASE WHEN (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) < 3 THEN 3 ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 3 END) ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 15 END),''),10,' ') PUNITORIO,
RPAD(SUBSTR(IFNULL(ce.DETALLE,''),1,50),50,' ') ESTADOCE
FROM CARTERA ca
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA = ca.IDCARTERA
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
LEFT JOIN DISTRIBUCION di ON di.IDCARTERA=ca.IDCARTERA
LEFT JOIN USUARIOS us ON us.IDUSUARIO=di.IDUSUARIO
JOIN PRORROGAS pr ON ca.AUXNUEVO=pr.PRORROGAS
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5
UNION
SELECT LPAD(IFNULL(ca.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(ca.SUCURSAL,''),11,' ') SUCURSAL,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
RPAD(SUBSTR(IFNULL(pe.PERFIL,''),1,50),50,' ') PERFIL,
LPAD(IFNULL((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())),''),11,' ') DIASC,
RPAD(SUBSTR(IFNULL((DATE_FORMAT(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),'%d/%m/%y')),''),1,8),8,' ') FECVEN,
LPAD(IFNULL(ca.CUOTAS,''),2,' ') CUOTAS,
LPAD(IFNULL(ca.ULTIMACUOTA,''),2,' ') ULTIMACUOTA,
LPAD(IFNULL(ca.IMPORTE,''),13,' ') IMPORTE,
LPAD(IFNULL((ca.SALDO + ca.SALDOBCO + ca.SALDOPESOS),''),13,' ') SALDOTOMAR,
LPAD(IFNULL((CASE WHEN TIPOCREDITO='BI' OR TIPOCREDITO = 'BY' OR TIPOCREDITO = 'AP' THEN '-' ELSE ROUND(pr.PORCENTAJE*ca.IMPORTE/100,2) END),''),13,' ') PRORROGA,
LPAD(IFNULL((CASE WHEN (-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE())) < 31 THEN (CASE WHEN (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) < 3 THEN 3 ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 3 END) ELSE (CEIL(((-DATEDIFF(DATE_ADD(FECHA, INTERVAL CASE WHEN TIPOCREDITO IN ('BI','BY') THEN ULTIMACUOTA*2 ELSE ULTIMACUOTA END MONTH),CURRENT_DATE()))-1)*0.005*IMPORTE)) + 15 END),''),10,' ') PUNITORIO,
RPAD(SUBSTR(IFNULL(ce.DETALLE,''),1,50),50,' ') ESTADOCE
FROM (SELECT ca.*
FROM CARTERA ca
JOIN DISTRIBUCION di ON ca.IDCARTERA=di.IDCARTERA
JOIN LOTES lt ON lt.IDLOTE=di.IDLOTE AND lt.ACTUAL=1
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA <> ca.IDCARTERA AND tmp.IDMOROSO = ca.IDMOROSO) ca
JOIN PERFILES pe ON ca.TIPOCARTERA=pe.TIPOCARTERA AND ca.TIPOPROCESO=pe.TIPOPROCESO
JOIN PRORROGAS pr ON ca.AUXNUEVO=pr.PRORROGAS
LEFT JOIN DISTRIBUCION di ON di.IDCARTERA=ca.IDCARTERA
LEFT JOIN USUARIOS us ON us.IDUSUARIO=di.IDUSUARIO
JOIN CARTERAESTADOS ce ON ce.ESTADO = (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END)
AND (CASE WHEN ca.FECHAPROCESO < ((SELECT MAX(FECHAPROCESO)FECHAPROCESO FROM CARTERA)) OR di.IDPERFIL<>pe.IDPERFIL THEN 5 ELSE ca.ESTADO END) <> 5";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: CREDITOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['SUCURSAL'];
$buffer.= $rs['NUMCREDITO'];
$buffer.= $rs['PERFIL'];
$buffer.= $rs['DIASC'];
$buffer.= $rs['FECVEN'];
$buffer.= $rs['CUOTAS'];
$buffer.= $rs['ULTIMACUOTA'];
$buffer.= $rs['IMPORTE'];
$buffer.= $rs['SALDOTOMAR'];
$buffer.= $rs['PRORROGA'];
$buffer.= $rs['PUNITORIO'];
$buffer.= $rs['ESTADOCE'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** CREDITOS *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******** PRODUCTOS **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
// open file
$fp = fopen($PATH.$FILE['PRODUCTOS'], "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH.$FILE['PRODUCTOS']);
// get query
$SQL = "SELECT LPAD(IFNULL(p.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(p.IDPRODUCTO,''),11,' ') IDPRODUCTO,
RPAD(SUBSTR(IFNULL(p.PRODUCTO,''),1,255),255,' ') PRODUCTO
FROM PRODUCTOS p
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA = p.IDCARTERA";
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: PRODUCTOS".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['IDPRODUCTO'];
$buffer.= $rs['PRODUCTO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
}
// close file
fclose($fp);
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******** PRODUCTOS **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******* SEGUIMIENTO *********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
$cntRow=0;
$maxRow=5000;
$maxRow=999999999999;
$fileName=0;
// get query
$SQL = "SELECT LPAD(IFNULL(s.IDCARTERA,''),11,' ') IDCARTERA,
LPAD(IFNULL(s.IDSEGUIMIENTO,''),11,' ') IDSEGUIMIENTO,
RPAD(SUBSTR(IFNULL(s.TELEFONO,''),1,255),255,' ') TELEFONO,
RPAD(SUBSTR(IFNULL(s.COMENTARIOS,''),1,8000),8000,' ') COMENTARIOS,
LPAD(IFNULL(ca.NUMCREDITO,''),7,' ') NUMCREDITO,
LPAD(IFNULL(s.FECHAALTA,''),19,' ') FECHAALTA,
LPAD(IFNULL(s.FECHABAJA,''),19,' ') FECHABAJA,
IFNULL(s.ESTADO,'0') ESTADO
FROM SEGUIMIENTO s
JOIN CARTERA ca ON s.IDCARTERA=ca.IDCARTERA
JOIN EXPORT_CALLEXT_".$DATE." tmp ON tmp.IDCARTERA = s.IDCARTERA
WHERE s.ESTADO=1
AND s.EXT != '".$EXT."'";
//AND DATE(s.fechaalta)>=DATE_SUB('".date('Y-m-d')."', INTERVAL 3 DAY)
$result = mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." QUERY: SEGUIMIENTO".(($result) ? "" : "\n".mysql_error($conn)));
while($rs = mysql_fetch_array($result)) {
if ($cntRow==0) {
// open file
$fp = fopen($PATH."tmp/".$FILE['SEGUIMIENTO'].".".str_pad($fileName,5,"0", STR_PAD_LEFT), "w");
savelog(((!$fp) ? 'ERR FILE: ':'OK FILE: ').$PATH."tmp/".$FILE['SEGUIMIENTO'].".".str_pad($fileName,5,"0", STR_PAD_LEFT));
}
// clear line buffer
$buffer = "";
$buffer.= $rs['IDCARTERA'];
$buffer.= $rs['IDSEGUIMIENTO'];
$buffer.= $rs['TELEFONO'];
$buffer.= $rs['COMENTARIOS'];
$buffer.= $rs['NUMCREDITO'];
$buffer.= $rs['FECHAALTA'];
$buffer.= $rs['FECHABAJA'];
$buffer.= $rs['ESTADO'];
$buffer.= "\n";
// write line buffer to file
fwrite($fp, $buffer);
$cntRow++;
if ($cntRow>=$maxRow) {
// close file
fclose($fp);
$cntRow=0;
$fileName++;
}
}
if($fp){
// close file
fclose($fp);
}
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/******* SEGUIMIENTO *********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/********** TABLA TEMPORAL **********/
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
$SQL = "DROP TABLE EXPORT_CALLEXT_".$DATE;
mysql_query($SQL, $conn);
savelog((($result) ? "OK" : "ERR")." DROP: EXPORT_CALLEXT_".$DATE.(($result) ? "" : "\n".mysql_error($conn)));
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
/********** TABLA TEMPORAL **********/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
?>
<file_sep>SELECT
CODIGO,
GRUPO,
NOMBRE,
CANTIDADPENDIENTE,
ROUND(PENDIENTE) PENDIENTE,
CANTIDADCANCELADO,
ROUND(CANCELADO) CANCELADO,
ROUND(TOTAL) TOTAL,
TOTALCARTERA,
CANCELADO/TOTAL*100 RECUPERO,
PENDIENTE/TOTALCARTERA*100 Eficiencia,
TOTAL/TOTALCARTERA*100 EFICIENCIA_INICIAL
FROM HSTREPORTE1 WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()));
<file_sep><?php
include('../../htdocs/conndb/conndb.php');
include('utils.php');
$DIRECTORYTO="/home/callcenter/interfaz/procesados/";
$FILE=exec ('ls -1 '.$DIRECTORYTO.'*140429* ',$FILES);
foreach($FILES as $FILE){
echo $FILE;
importar($FILE,$conn);
}
die();
function importar($FILE,$conn){
$gestor = fopen($FILE, "rb");
$contenido = '';
$C=1;
while (!feof($gestor)) {
$linea = fread($gestor, 1347);
//datos del Moroso
$DOCUMENTOTIPO=fixtext(substr($linea ,22,1));
$DOCUMENTONUMERO=fixtext(substr($linea ,23,8));
$TITULAR=fixtext(substr($linea ,149,30));
//echo $TITULAR;
$IDTITULAR='';
$TIPOCARTERA=fixtext(substr($linea ,6,3));
$TIPOPROCESO=fixtext(substr($linea ,9,3));
$SELECT= "select * from PERFILES pe where pe.TIPOCARTERA='$TIPOCARTERA' and pe.TIPOPROCESO='$TIPOPROCESO' ";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$PERFIL= $row['PERFIL'];
if (1==1){
$IDMOROSO=$IDTITULAR;
$TIPOCARTERA=fixtext(substr($linea ,6,3));
$FECHAPROCESO='20'.substr($linea ,0,2).'-'.substr($linea ,2,2).'-'.substr($linea ,4,2);
$TIPOPROCESO=fixtext(substr($linea ,9,3));
$SUCURSAL=fixtext(substr($linea ,32,3));
if($TIPOCARTERA=='LIC'){
$NUMCREDITO=$DOCUMENTONUMERO;}
else
$NUMCREDITO=fixtext(substr($linea ,36,7));
$DOLARES=fixtext(substr($linea ,43,3));
$IMPORTE=fixtext(substr($linea ,47,10))/100;
$FECHA='20'.substr($linea ,64,2).'-'.substr($linea ,61,2).'-'.substr($linea ,58,2);
$CUOTAS=fixtext(substr($linea ,67,2));
$ULTIMACUOTA =fixtext(substr($linea ,70,2));
$DIAS=fixtext(substr($linea ,73,3));
$SALDO=fixtext(substr($linea ,78,14)/100);
$FRAVSAENZ=fixtext(substr($linea ,115,7));
$CUOTASATRASADAS=fixtext(substr($linea ,123,2));
$AUXNUEVO=fixtext(substr($linea ,126,2));
if (!$AUXNUEVO)$AUXNUEVO='00';
$CANTATRASADAS=fixtext(substr($linea ,134,5));
$CATEGORIA=fixtext(substr($linea ,255,1));
$TIPOCREDITO=fixtext(substr($linea ,489,2));
$VENDEDOR=fixtext(substr($linea ,492,4));
$OBSERVACIONES=fixtext(substr($linea ,828,30));
$DEBEPAGARINT=fixtext(substr($linea ,869,12));
$FECVENCIMIENTO=fixtext(substr($linea ,882,6));
$SALDOBCO=fixtext(substr($linea ,889,10));
$TIPOTARJETA=fixtext(substr($linea ,900,10));
$SALDOPESOS=fixtext(substr($linea ,911,10)/100);
$SALDODOLAR=fixtext(substr($linea ,922,10)/100);
$CANTIMP=fixtext(substr($linea ,932,4));
$UPDATE= "update CARTERA_201405 set
TIPOCARTERA='$TIPOCARTERA',
TIPOPROCESO='$TIPOPROCESO',
SALDOTOMAR='$SALDO',
PERFIL='$PERFIL'
where
NUMCREDITO='$NUMCREDITO' and SUCURSAL='$SUCURSAL' ";
mysql_query($UPDATE);
echo 1;
}
}
}
fclose($gestor);
}
?>
<file_sep><?php
include('../../htdocs/conndb/conndb.php');
include('utils.php');
$DIRECTORY="/home/callcenter/interfaz/procesar/";
$DIRECTORYTO="/home/callcenter/interfaz/procesados/";
$TOTALES="suc148geuimp";
$FILE=$DIRECTORY.$TOTALES;
if(file_exists ($FILE ))importar($FILE,$conn);
$FILETO=$DIRECTORYTO.date("Ymd").$FILES[$a];
//rename($FILE,$FILETO);
function importar($FILE,$conn){
$CONTENIDO=file_get_contents($FILE);
$CONTENIDO=str_replace(" "," ",$CONTENIDO);
$CONTENIDO=str_replace(" "," ",$CONTENIDO);
$CONTENIDO=str_replace(" "," ",$CONTENIDO);
$CONTENIDO=str_replace(" "," ",$CONTENIDO);
$CONTENIDO=str_replace(" "," ",$CONTENIDO);
$CONTENIDO=str_replace(" "," ",$CONTENIDO);
$row=explode(chr(10),$CONTENIDO);
$SQL="Truncate TABLE TOTALCARTERA";
mysql_query($SQL, $conn);
foreach ($row as $rs){
$rs1=explode(" ",$rs);
$SQL="select IDSUCURSAL FROM SUCURSALES where SUCURSAL ='".substr($rs1[0],0,3)."'";
echo $SQL;
$result = mysql_query($SQL, $conn );
if ($row1= mysql_fetch_array($result)){
$INSERT= "insert into TOTALCARTERA(IDSUCURSAL,TOTALCARTERA) values ((select IDSUCURSAL FROM SUCURSALES where SUCURSAL ='".substr($rs1[0],0,3)."'),".$rs1[1].")";
mysql_query($INSERT, $conn );
}else
echo $rs1[0];
}
}
?>
<file_sep>armarMensajeProcesoDistribucion ()
{
if [ $1 -eq 0 ]
then
echo -e "===========================\nEl cierre de mes se realizo correctamente\n===========================" >> /home/callcenter/interfaz/proceso/archivos/message.txt
else
echo -e "===========================\nERROR: en el cierre de mes\n===========================" >> /home/callcenter/interfaz/proceso/archivos/message.txt
fi
}
esFechaDeCierre ()
{
varLog=/home/callcenter/interfaz/proceso/logs/procesoDiarioMes.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mes=$(date +%D | cut -d "/" -f 1)
dia=$(date +%D | cut -d "/" -f 2)
anio=$(date +%D | cut -d "/" -f 3)
cerrarMes=/home/callcenter/interfaz/proceso/b.sh
#TENER EN CUENTA QUE SE LE DEBE SUMAR UN DIA AL DIA DE CIERRE, PORQUE SE PROCESA LA MADRUGADA DEL DIA POSTERIOR
if [[ $dia -eq 22 && $mes -eq 12 && $anio -eq 17 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 1 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 27 && $mes -eq 2 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 27 && $mes -eq 4 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 5 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 29 && $mes -eq 6 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 29 && $mes -eq 7 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 8 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 28 && $mes -eq 9 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 30 && $mes -eq 10 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 29 && $mes -eq 11 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
if [[ $dia -eq 28 && $mes -eq 12 && $anio -eq 18 ]]
then
$cerrarMes
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
fi
}
armarMensajeProcesoDiario ()
{
if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nEl proceso diario se realizo correctamente\n===========================" > /home/callcenter/interfaz/proceso/archivos/message.txt
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: en el proceso diario\n===========================" > /home/callcenter/interfaz/proceso/archivos/message.txt
fi
}
varLog=/home/callcenter/interfaz/proceso/logs/procesoDiarioMes.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mensaje=/home/callcenter/interfaz/proceso/archivos/message.txt
realizarProcesoDiario=/home/callcenter/interfaz/proceso/a.sh
#Se registra en el log lo que se realizó en el dia
$realizarProcesoDiario
error=$?
armarMensajeProcesoDiario $error
$comprobar $error $varLog procesoDiario.sh
#Se chequea si se trata de de una fecha de cierre de mes, en base a eso se decide si se ejecuta el script de cierre del mes o no
esFechaDeCierre
#Se envia por mail lo que se realizó a la gente encargada
cat $mensaje | mail -s "[Desarrollo] Proceso" "<EMAIL>"
cat $mensaje | mail -s "[Desarrollo] Proceso" "<EMAIL>"<file_sep>SELECT
CODIGO,
GRUPO,
NOMBRE,
CANTIDADPENDIENTE,
ROUND(PENDIENTE) PENDIENTE,
CANTIDADCANCELADO,
ROUND(CANCELADO) CANCELADO,
ROUND(TOTAL) TOTAL,
TOTALCARTERAPROP,
CANCELADO/TOTAL*100 RECUPERO,
PENDIENTE/TOTALCARTERAPROP*100 Eficiencia,
TOTAL/TOTALCARTERAPROP*100 EFICIENCIA_INICIAL
FROM HSTREPORTE1_DIARIA WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()));<file_sep>#El parametro 3 es el nombre del script ejecutado y el parametro 2 es la direccion donde se encuentra el log, parametro 1 es $?
if [ $1 -eq 0 ]
then
echo -e "===============================\n#$(date +%d/%m/%Y----%H:%M)\nSe ejecuto correctamente $3\n===============================">> $2
else
echo -e "===============================\n#$(date +%d/%m/%Y----%H:%M)\nHubo un error al ejecutar $3\n===============================" >> $2
fi<file_sep>insert into DISTRIBUCION_Backup select IDLOTE,IDDISTRIBUCION,IDUSUARIO,SUCURSAL,IDGRUPO,IDPERFIL,IDCARTERA,MONTO,
LLAMADOS,FECHAALTA,FECHABAJA,ESTADO,now()
from DISTRIBUCION;<file_sep>cd /home/callcenter/interfaz/proceso
php pfacil.php
<file_sep>varLog=/home/callcenter/interfaz/proceso/logs/procesoDiarioMes.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mensaje=/home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
realizarProcesoDiario=/home/callcenter/interfaz/proceso/proceso.sh
realizarReporteDeCierre=/home/callcenter/interfaz/proceso/reporteDeCierre.sh
realizarReporteDiarioEvolutivo=/home/callcenter/interfaz/proceso/reporteDiarioEvolutivo.sh
cerrarMes=/home/callcenter/interfaz/proceso/cierreDeMes.sh
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
realizarReporteDeInicio=/home/callcenter/interfaz/proceso/reporteDeInicio.sh
from="<EMAIL>"
queries=/home/callcenter/interfaz/proceso/queries
procesar=/home/callcenter/interfaz/procesar
errorMensaje=/home/callcenter/interfaz/proceso/archivos/mensajeErrorDirectorioVacio.txt
ejecutarQuery=/home/callcenter/interfaz/proceso/run_n_log_query.sh
queryFechaBaseCount=$(cat $queries/fechaBaseCount.sql)
queryCierreBase=$(cat $queries/fechaCierreBase.sql)
fechaHoy=$(date +%Y-%m-%d)
resultadoFlagNecesarioParaEjecutarCierre=$(mysql -se "$queryCierreBase $fechaHoy',interval -1 day) limit 1" | cut -d " " -f1)
cantResultadoFechaCierre=$(mysql -se "$queryFechaBaseCount $fechaHoy',interval -1 day) limit 1")
cantResultadoFechaInicio=$(mysql -se "$queryFechaBaseCount $fechaHoy',interval -2 day) limit 1")
cantResultadoFechaAsignacion=$(mysql -se "$queryFechaBaseCount $fechaHoy',interval 0 day) limit 1")
queryFlagDistribucionSQL=$queries/obtenerFlagDistribucion.sql
queryActualizarFlagDistribucion=$queries/actualizarFlagDistribucion.sql
fecha=$(date +%d-%m-%Y-%H.%M)
varLogCierreAsigInicio=/home/callcenter/interfaz/proceso/logs/cierreInicioAsignacionFlag.txt
obtenerFlagDistribucion()
{
flagDistribucionAux=$(cat $queryFlagDistribucionSQL)
flagVigenteEnDistribucion=$(mysql -se "$flagDistribucionAux")
}
actualizarFlagDistribucion()
{
queryBaseFlag=$(cat $queryActualizarFlagDistribucion)
if [ $1 -eq 1 ]
then
mysql -se "$queryBaseFlag 0"
echo -e "=============================\n$fecha\nSe modifico el flag de 1 a 0\n=============================" >>$varLogCierreAsigInicio
else
mysql -se "$queryBaseFlag 1"
echo -e "=============================\n$fecha\nSe modifico el flag de 0 a 1\n=============================" >>$varLogCierreAsigInicio
fi
}
loguearCierreOAsignacionOInicio()
{
fecha=$(date +%d-%m-%Y-%H.%M)
case $1 in
1)
echo -e "=============================\n$fecha\nNo es fecha de inicio, no se realizaron actividades de inicio.\n=============================" >>$varLogCierreAsigInicio
;;
2)
echo -e "=============================\n$fecha\nSe realizaron las actividades de inicio.\n=============================" >>$varLogCierreAsigInicio
;;
3)
echo -e "=============================\n$fecha\nNo es fecha de cierre, no se realizaron actividades de cierre.\n=============================" >>$varLogCierreAsigInicio
;;
4)
echo -e "=============================\n$fecha\nSe han ejecutado las actividades de cierre y se ha modificado el valor del flag.\n=============================" >>$varLogCierreAsigInicio
;;
5)
echo -e "=============================\n$fecha\nNo se ejecutaron actividades de cierre porque si bien la fecha es de cierre, el flag Necesario y el actual no coinciden.\n=============================" >>$varLogCierreAsigInicio
;;
6)
echo -e "=============================\n$fecha\nNo es fecha de asignacion, no se ejecutaron actividades de asignación.\n=============================" >>$varLogCierreAsigInicio
;;
7)
echo -e "=============================\n$fecha\nSe han ejecutado actividades de asignacion.\n=============================" >>$varLogCierreAsigInicio
;;
*)
echo -e "=============================\n$fecha\nERROR: No recibí ningun numero como parametro.\n=============================" >>$varLogCierreAsigInicio
;;
esac
}
registrarContadorDistribucionEnLog ()
{
resultadoContador=$(ejecutarQuery $queries/contadorDeDistribucion.sql)
echo -e "===========================\n$(date +%d/%m/%Y----%H:%M)\nSe distribuyeron $resultadoContador registros.\n===========================" >>$varLog
}
backupPreDistribucion()
{
$ejecutarQuery $queries/backupDistribucion.sql $varLog
$ejecutarQuery $queries/backupUsuariosPerfiles.sql $varLog
$ejecutarQuery $queries/backupUsuariosPerfilesTMP.sql $varLog
}
backupPostDistribucion()
{
backupPreDistribucion
$ejecutarQuery $queries/backupCartera.sql $varLog
}
armarMensajeProcesoDistribucion ()
{
if [ $1 -eq 0 ]
then
echo -e "===========================\nEl cierre de mes se realizo correctamente\n===========================" >> /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
else
echo -e "===========================\nERROR: en el cierre de mes\n===========================" >> /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
fi
}
actividadesCierre ()
{
backupPreDistribucion
$cerrarMes
registrarContadorDistribucionEnLog
backupPostDistribucion
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
$realizarReporteDeCierre
}
esFechaDeCierre ()
{
#Pregunto si es fecha de ejecución de cierre ( un día posterior a la fecha de cierre del banco)
if [ $cantResultadoFechaCierre -eq 0 ]
then
loguearCierreOAsignacionOInicio 3
else
obtenerFlagDistribucion
if [ $resultadoFlagNecesarioParaEjecutarCierre -eq $flagVigenteEnDistribucion ]
then
actividadesCierre
loguearCierreOAsignacionOInicio 4
actualizarFlagDistribucion $flagVigenteEnDistribucion
else
loguearCierreOAsignacionOInicio 5
fi
fi
}
actividadesDeInicio ()
{
$realizarReporteDeInicio
}
esFechaDeInicio ()
{
#Pregunto si es fecha de inicio ( dos días posteriores a la fecha de cierre del banco)
if [ $cantResultadoFechaInicio -eq 0 ]
then
loguearCierreOAsignacionOInicio 1
else
actividadesDeInicio
loguearCierreOAsignacionOInicio 2
fi
}
armarMensajeProcesoDiario ()
{
if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nEl proceso diario se realizo correctamente\n===========================" > /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: en el proceso diario\n===========================" > /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
fi
}
mandarMailDestinatarios ()
{
#parametro 1=subject, 2=mensaje,3 cantidad De mails destinatarios, 4 en adelante lista de mails
#en realidad es un solo parametro que es un string y de el se extraen los parametros porque sino hay problemas
#ya que el mensaje tiene espacios y los espacios hace creer a linux que son muchos parametros por mas
#que el mismo se encuentre entre comillas
subject="$(echo $1 | cut -d "%" -f 1)"
destinatario="$(echo $1 | cut -d "%" -f 4)"
cantDestinatarios=$(echo $1 | cut -d "%" -f 3)
let cantDestinatarios=cantDestinatarios+3
mensajeMail=$(cat $(echo $1 | cut -d "%" -f 2))
for i in $(seq 4 $cantDestinatarios)
do
echo $1 | cut -d "%" -f $i
echo -e "$mensajeMail" | mail -s "$subject" -r "$from" "$(echo $1 | cut -d "%" -f $i)"
done
}
if [ "$(ls -A $procesar)" ]
then
#Se registra en el log lo que se realizó en el dia
$realizarProcesoDiario
error=$?
armarMensajeProcesoDiario $error
$comprobar $error $varLog procesoDiario.sh
$realizarReporteDiarioEvolutivo
#Se chequea si se trata de una fecha de cierre de mes, en base a eso se decide si se ejecuta el script de cierre del mes o no, se checkea por fecha y por flag
#como medida de seguridad extra en caso que se quiera por x motivo ejecutar dos veces en un mismo mes el script.
esFechaDeCierre
esFechaDeInicio
#poner %numerodemails%mail1%mail2etc
mandarMailDestinatarios "[CallMora]-Proceso%$mensaje%4%<EMAIL>%<EMAIL>%<EMAIL>%<EMAIL>"
#Se envia por mail lo que se realizó a la gente encargada
else
echo -e "====================\n$(date +%d/%m/%Y-----%H.%M)\n\nError al Ejecutar Proceso Diario\n\nDetalle: No se encontraron archivos en el directorio Procesar.\n\nDistribucion no se ejecutara aunque corresponda por fecha, ya que no se realizo el proceso diario.\n====================">$errorMensaje
mandarMailDestinatarios "[CallMora]-Proceso%$errorMensaje%4%<EMAIL>%<EMAIL>%<EMAIL>%<EMAIL>"
$comprobar 1 $varLog Proceso_Diario_No_Hay_Archivos_En_Procesar
fi<file_sep>varLog=/home/callcenter/interfaz/proceso/logs/procesoDiarioMes.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
mensaje=/home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
realizarProcesoDiario=/home/callcenter/interfaz/proceso/proceso.sh
realizarReporteDeCierre=/home/callcenter/interfaz/proceso/reporteDeCierre.sh
realizarReporteDiarioEvolutivo=/home/callcenter/interfaz/proceso/reporteDiarioEvolutivo.sh
cerrarMes=/home/callcenter/interfaz/proceso/cierreDeMes.sh
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
realizarReporteDeInicio=/home/callcenter/interfaz/proceso/reporteDeInicio.sh
from="<EMAIL>"
queries=/home/callcenter/interfaz/proceso/queries
procesar=/home/callcenter/interfaz/procesar
errorMensaje=/home/callcenter/interfaz/proceso/archivos/mensajeErrorDirectorioVacio.txt
ejecutarQuery=/home/callcenter/interfaz/proceso/run_n_log_query.sh
#ejecutarQuery ()
#{
#query=$(cat $1)
#
#mysql -se "$query"
#
#}
registrarContadorDistribucionEnLog ()
{
resultadoContador=$(ejecutarQuery $queries/contadorDeDistribucion.sql)
echo -e "===========================\n$(date +%d/%m/%Y----%H:%M)\nSe distribuyeron $resultadoContador registros.\n===========================" >>$varLog
}
backupPreDistribucion()
{
$ejecutarQuery $queries/backupDistribucion.sql $varLog
$ejecutarQuery $queries/backupUsuariosPerfiles.sql $varLog
$ejecutarQuery $queries/backupUsuariosPerfilesTMP.sql $varLog
}
backupPostDistribucion()
{
backupPreDistribucion
$ejecutarQuery $queries/backupCartera.sql $varLog
}
armarMensajeProcesoDistribucion ()
{
if [ $1 -eq 0 ]
then
echo -e "===========================\nEl cierre de mes se realizo correctamente\n===========================" >> /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
else
echo -e "===========================\nERROR: en el cierre de mes\n===========================" >> /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
fi
}
actividadesCierre ()
{
backupPreDistribucion
$cerrarMes
registrarContadorDistribucionEnLog
backupPostDistribucion
error=$?
armarMensajeProcesoDistribucion $error
$comprobar $error $varLog cierreDeMes.sh
$realizarReporteDeCierre
}
esFechaDeCierre ()
{
mes=$(date +%D | cut -d "/" -f 1)
dia=$(date +%D | cut -d "/" -f 2)
anio=$(date +%D | cut -d "/" -f 3)
flagDistribucion=$(cat /home/callcenter/interfaz/proceso/archivos/flagDistribucion.txt)
flagDistribucionArchivo=/home/callcenter/interfaz/proceso/archivos/flagDistribucion.txt
#TENER EN CUENTA QUE SE LE DEBE SUMAR UN DIA AL CIERRE, PORQUE SE PROCESA LA MADRUGADA DEL DIA POSTERIOR
if [[ $dia -eq 30 && $mes -eq 1 && $anio -eq 18 && $flagDistribucion -eq 0 ]]
then
echo 1 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 27 && $mes -eq 2 && $anio -eq 18 && $flagDistribucion -eq 1 ]]
then
echo 0 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 28 && $mes -eq
fi
if [[ $dia -eq 27 && $mes -eq 4 && $anio -eq 18 && $flagDistribucion -eq 1 ]]
then
echo 0 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 30 && $mes -eq 5 && $anio -eq 18 && $flagDistribucion -eq 0 ]]
then
echo 1 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 29 && $mes -eq 6 && $anio -eq 18 && $flagDistribucion -eq 1 ]]
then
echo 0 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 29 && $mes -eq 7 && $anio -eq 18 && $flagDistribucion -eq 0 ]]
then
echo 1 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 30 && $mes -eq 8 && $anio -eq 18 && $flagDistribucion -eq 1 ]]
then
echo 0 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 28 && $mes -eq 9 && $anio -eq 18 && $flagDistribucion -eq 0 ]]
then
echo 1 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 30 && $mes -eq 10 && $anio -eq 18 && $flagDistribucion -eq 1 ]]
then
echo 0 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 29 && $mes -eq 11 && $anio -eq 18 && $flagDistribucion -eq 0 ]]
then
echo 1 > $flagDistribucionArchivo
actividadesCierre
fi
if [[ $dia -eq 28 && $mes -eq 12 && $anio -eq 18 && $flagDistribucion -eq 1 ]]
then
echo 0 > $flagDistribucionArchivo
actividadesCierre
fi
}
#===========================
actividadesDeInicio ()
{
$realizarReporteDeInicio
}
esFechaDeInicio ()
{
mes=$(date +%D | cut -d "/" -f 1)
dia=$(date +%D | cut -d "/" -f 2)
anio=$(date +%D | cut -d "/" -f 3)
#TENER EN CUENTA QUE SE LE DEBE SUMAR DOS DIAS AL DIA DE CIERRE, PORQUE SE PROCESA LA MADRUGADA DE DOS DIAS DESPUES
if [[ $dia -eq 31 && $mes -eq 1 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 28 && $mes -eq 2 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 29 && $mes -eq 3 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 28 && $mes -eq 4 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 31 && $mes -eq 5 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 30 && $mes -eq 6 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 30 && $mes -eq 7 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 31 && $mes -eq 8 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 29 && $mes -eq 9 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 31 && $mes -eq 10 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 30 && $mes -eq 11 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
if [[ $dia -eq 29 && $mes -eq 12 && $anio -eq 18 ]]
then
actividadesDeInicio
fi
}
#===========================
armarMensajeProcesoDiario ()
{
if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nEl proceso diario se realizo correctamente\n===========================" > /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: en el proceso diario\n===========================" > /home/callcenter/interfaz/proceso/archivos/messageProcesoDiario.txt
fi
}
mandarMailDestinatarios ()
{
#parametro 1=subject, 2=mensaje,3 cantidad De mails destinatarios, 4 en adelante lista de mails
#en realidad es un solo parametro que es un string y de el se extraen los parametros porque sino hay problemas
#ya que el mensaje tiene espacios y los espacios hace creer a linux que son muchos parametros por mas
#que el mismo se encuentre entre comillas
subject="$(echo $1 | cut -d "%" -f 1)"
destinatario="$(echo $1 | cut -d "%" -f 4)"
cantDestinatarios=$(echo $1 | cut -d "%" -f 3)
let cantDestinatarios=cantDestinatarios+3
mensajeMail=$(cat $(echo $1 | cut -d "%" -f 2))
for i in $(seq 4 $cantDestinatarios)
do
echo $1 | cut -d "%" -f $i
echo -e "$mensajeMail" | mail -s "$subject" -r "$from" "$(echo $1 | cut -d "%" -f $i)"
done
}
if [ "$(ls -A $procesar)" ]
then
#Se registra en el log lo que se realizó en el dia
$realizarProcesoDiario
error=$?
armarMensajeProcesoDiario $error
$comprobar $error $varLog procesoDiario.sh
$realizarReporteDiarioEvolutivo
#Se chequea si se trata de una fecha de cierre de mes, en base a eso se decide si se ejecuta el script de cierre del mes o no, se checkea por fecha y por flag
#como medida de seguridad extra en caso que se quiera por x motivo ejecutar dos veces en un mismo mes el script.
esFechaDeCierre
esFechaDeInicio
#poner %numerodemails%mail1%mail2etc
mandarMailDestinatarios "[CallMora]-Proceso%$mensaje%4%<EMAIL>%<EMAIL>%<EMAIL>%<EMAIL>"
#Se envia por mail lo que se realizó a la gente encargada
else
echo -e "====================\n$(date +%d/%m/%Y-----%H.%M)\n\nError al Ejecutar Proceso Diario\n\nDetalle: No se encontraron archivos en el directorio Procesar.\n\nDistribucion no se ejecutara aunque corresponda por fecha, ya que no se realizo el proceso diario.\n====================">$errorMensaje
mandarMailDestinatarios "[CallMora]-Proceso%$errorMensaje%4%<EMAIL>%<EMAIL>%<EMAIL>%<EMAIL>"
$comprobar 1 $varLog Proceso_Diario_No_Hay_Archivos_En_Procesar
fi<file_sep>contador=$(cat /home/callcenter/interfaz/proceso/archivos/backup_contador.txt)
contador_file=/home/callcenter/interfaz/proceso/archivos/backup_contador.txt
varLog=/home/callcenter/interfaz/proceso/logs/backup_log.txt
comprobar=/home/callcenter/interfaz/proceso/comprobadorDeErrores.sh
fecha=$(date +%d/%m/%Y-----%H:%M)
#Comprimir tambien es para que se entienda mejor el log, pero no es ningun comando
tar -czvf htdocs.tar.gz /home/callcenter/htdocs
$comprobar $? $varLog comprimir_htdocs.tar.gz
tar -czvf procesar.tar.gz /home/callcenter/interfaz/procesar
$comprobar $? $varLog comprimir_procesar.tar.gz
tar -czvf proceso.tar.gz /home/callcenter/interfaz/proceso
$comprobar $? $varLog comprimir_proceso.tar.gz
tar -czvf parametros.tar.gz /home/callcenter/interfaz/parametros
$comprobar $? $varLog comprimir_parametros.tar.gz
tar -czvf prorrogas.tar.gz /home/callcenter/interfaz/prorrogas
$comprobar $? $varLog comprimir_prorrogas.tar.gz
if [ $contador -gt 6 ]
then
contador=1
echo $contador>$contador_file
else
let contador=$contador+1
echo $contador>$contador_file
fi
#numeroDeCarpeta=cat $contador_file
carpeta=/home/callcenter/backup2/$(cat $contador_file)
#Pongo mover para que se entienda mejor el log file, pero mover no es ningun script ni comando
mv htdocs.tar.gz $carpeta
$comprobar $? $varLog Mover_htdocs.tar.gz
mv procesar.tar.gz $carpeta
$comprobar $? $varLog Mover_procesar.tar.gz
mv proceso.tar.gz $carpeta
$comprobar $? $varLog Mover_proceso.tar.gz
mv parametros.tar.gz $carpeta
$comprobar $? $varLog Mover_parametros.tar.gz
mv prorrogas.tar.gz $carpeta
$comprobar $? $varLog Mover_prorrogas.tar.gz
<file_sep>archivos=/home/callcenter/interfaz/proceso/archivos
mandarReportesEmail ()
{
from="<EMAIL>"
# more receiver like <EMAIL> <EMAIL> ...
to="$2"
subject="$3"
#you can also read content from the file just use $(cat yourfile)
j=1
for i in $(seq 4 $#);
do
files[$j]=$(echo $@ | cut -d " " -f $i)
let j=j+1
done
for att in "${files[@]}"; do
[ ! -f "$att" ] && echo "Warning: attachment $att not found, skipping" >&2 && continue
attargs+=( "-a" "$att" )
done
cat $plantilla | mail -s "$subject" -r "$from" "${attargs[@]}" "$to"
}
mailInicio()
{
plantilla=$archivos/mensajePlantillaReporteDeInicio.txt
fecha=$(date +%d-%m-%Y)
hora=$(date +%H.%M)
echo -e "Estimados, adjuntamos los reportes correspondientes al Inicio de cobranzas del mes en curso, generados el dia $fecha a las $hora HS.\n\nSaludos\n\nSistemas-Call Mora" >$plantilla
}
mailDiarioEvolutivo()
{
plantilla=$archivos/mensajePlantillaReporteEvolutivo.txt
fecha=$(date +%d-%m-%Y)
hora=$(date +%H.%M)
echo -e "Estimados, adjuntamos los reportes correspondientes a la evolucion de las cobranzas del mes en curso, generados el dia $fecha a las $hora HS.\n\nSaludos\n\nSistemas-Call Mora" >$plantilla
}
mailDeCierre()
{
plantilla=$archivos/mensajePlantillaReporteCierre.txt
fecha=$(date +%d-%m-%Y)
hora=$(date +%H.%M)
echo -e "Estimados, adjuntamos los reportes correspondientes al cierre de las cobranzas del mes en curso, generados el dia $fecha a las $hora HS.\n\nSaludos\n\nSistemas-Call Mora" >$plantilla
}
mailDeLegales()
{
plantilla=$archivos/mensajePlantillaReporteLegales.txt
fecha=$(date +%d-%m-%Y)
hora=$(date +%H.%M)
echo -e "Estimados, adjuntamos los reportes correspondientes a Legales, generados el dia $fecha a las $hora HS.\n\nSaludos\n\nSistemas-Call Mora" >$plantilla
}
if [ $1 -eq 1 ]
then
mailInicio
fi
if [ $1 -eq 2 ]
then
mailDiarioEvolutivo
fi
if [ $1 -eq 3 ]
then
mailDeCierre
fi
if [ $1 -eq 4 ]
then
mailDeLegales
fi
mandarReportesEmail $@ <file_sep><?php
include('../../htdocs/conndb/conndb.php');
include('utils.php');
$DIRECTORY="/home/callcenter/interfaz/procesar/";
$DIRECTORYTO="/home/callcenter/interfaz/procesados/";
$FILES=(getFiles($DIRECTORY));
for($a=0;$a<count($FILES);$a++){
$FILE=$DIRECTORY.$FILES[$a];
$FILETO=$DIRECTORYTO.date("Ymd").$FILES[$a];
importar($FILE,$conn);
rename($FILE,$FILETO);
}
function importar($FILE,$conn){
$gestor = fopen($FILE, "rb");
$contenido = '';
$C=1;
while (!feof($gestor)) {
$linea = fread($gestor, 1348);
//datos del Moroso
$DOCUMENTOTIPO=fixtext(substr($linea ,22,1));
$DOCUMENTONUMERO=fixtext(substr($linea ,23,8));
$TITULAR=fixtext(substr($linea ,149,30));
echo $TITULAR;
$IDTITULAR='';
$TIPOCARTERA=fixtext(substr($linea ,6,3));
$TIPOPROCESO=fixtext(substr($linea ,9,3));
$SELECT= "select * from PERFILES pe where pe.TIPOCARTERA='$TIPOCARTERA' and pe.TIPOPROCESO='$TIPOPROCESO' ";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
if ($TITULAR){
$SELECT= "select * from CONTACTOS where DOCUMENTONUMERO=$DOCUMENTONUMERO and DOCUMENTOTIPO='$DOCUMENTOTIPO'";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDTITULAR=$row['IDCONTACTO'];
$UPDATE= "update CONTACTOS set NOMBRE='$TITULAR' where IDCONTACTO=$IDTITULAR";
mysql_query($UPDATE);
}else{
$INSERT= "insert into CONTACTOS (DOCUMENTONUMERO,DOCUMENTOTIPO,NOMBRE,FECHAALTA) values ($DOCUMENTONUMERO,'$DOCUMENTOTIPO','$TITULAR',now())";
mysql_query($INSERT, $conn );
$IDTITULAR=mysql_insert_id();
}
}
if ($IDTITULAR){
$CALLE=fixtext(substr($linea ,180,30));
$NUMERO=fixtext(substr($linea ,210,5));
$PISO=fixtext(substr($linea ,216,2));
$DEPTO=fixtext(substr($linea ,219,2));
$LOCALIDAD=fixtext(substr($linea ,222,20));
$CODIGOPOSTAL=fixtext(substr($linea ,243,4));
$PLANO=fixtext(substr($linea ,248,3));
$COORDENADAS=fixtext(substr($linea ,252,2));
$SELECT= "select * from DIRECCIONES where CALLE='$CALLE' and NUMERO='$NUMERO' and LOCALIDAD='$LOCALIDAD' and IDCONTACTO=$IDTITULAR";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDDIRECCION=$row['IDDIRECCION'];
}else{
$INSERT= "insert into DIRECCIONES (IDCONTACTO,CALLE,NUMERO,PISO,DEPTO,LOCALIDAD,CODIGOPOSTAL,PLANO, COORDENADAS,FECHAALTA)
values ($IDTITULAR,'$CALLE','$NUMERO','$PISO','$DEPTO','$LOCALIDAD','$CODIGOPOSTAL','$PLANO','$COORDENADAS',now())";
mysql_query($INSERT);
$IDDIRECCION=mysql_insert_id();
}
}
if ($IDTITULAR){
$CODIGOAREA=fixtext(substr($linea ,93,5));
$NUMERO=fixtext(substr($linea ,99,15));
if ($NUMERO){
$SELECT= "select * from TELEFONOS where CODIGOAREA='$CODIGOAREA' and NUMERO='$NUMERO' and IDCONTACTO=$IDTITULAR";
$result = mysql_query($SELECT, $conn );
if (mysql_error()) echo $SELECT;
echo mysql_error();
if ($row = mysql_fetch_array($result)){
$IDTELEFONO=$row['IDTELEFONO'];
}else{
$INSERT= "insert into TELEFONOS (IDCONTACTO,CODIGOAREA,NUMERO,FECHAALTA) values ('$IDTITULAR','$CODIGOAREA','$NUMERO',now())";
mysql_query($INSERT, $conn );
$IDTELEFONO=mysql_insert_id();
}
}
}
if ($IDTITULAR){
$EMPRESA=fixtext(substr($linea ,266,20));
$DIRCALLE=fixtext(substr($linea ,287,19));
$DIRNUMERO=fixtext(substr($linea ,313,5));
$DIRLOCALIDAD=fixtext(substr($linea ,319,20));
$SECCION=fixtext(substr($linea ,340,10));
$TELCODIGOAREA=fixtext(substr($linea ,351,5));
$TELNUMERO=fixtext(substr($linea ,357,15));
$TELINTERNO=fixtext(substr($linea ,373,12));
$SELECT= "select * from EMPLEOS where EMPRESA='$EMPRESA' and DIRCALLE='$DIRCALLE' and TELNUMERO='$TELNUMERO' and IDCONTACTO=$IDTITULAR";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDEMPLEO=$row['IDEMPLEO'];
$UPDATE= "update EMPLEOS set DIRLOCALIDAD='$DIRLOCALIDAD' where EMPRESA='$EMPRESA' and DIRCALLE='$DIRCALLE' and TELNUMERO='$TELNUMERO' and IDCONTACTO=$IDTITULAR";
mysql_query($UPDATE, $conn );
}else{
$INSERT= "insert into EMPLEOS (IDCONTACTO,EMPRESA,DIRCALLE,DIRNUMERO,DIRLOCALIDAD,SECCION,TELCODIGOAREA,TELNUMERO,TELINTERNO,FECHAALTA)
values ('$IDTITULAR','$EMPRESA','$DIRCALLE','$DIRNUMERO','$DIRLOCALIDAD','$SECCION','$TELCODIGOAREA','$TELNUMERO','$TELINTERNO',now())";
mysql_query($INSERT, $conn );
$IDEMPLEO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
}
if ($IDTITULAR){
$REFERENCIA=fixtext(substr($linea ,395,30));
$TELEFONO=fixtext(substr($linea ,426,15));
$SELECT= "select * from REFERENCIAS where REFERENCIA='$REFERENCIA' and TELEFONO='$TELEFONO' and IDCONTACTO=$IDTITULAR";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$REFERENCIA1=$row['IDREFERENCIA'];
}else{
$INSERT= "insert into REFERENCIAS (IDCONTACTO,REFERENCIA,TELEFONO,FECHAALTA)
values ('$IDTITULAR','$REFERENCIA','$TELEFONO',now())";
mysql_query($INSERT, $conn );
$REFERENCIA1=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$REFERENCIA=fixtext(substr($linea ,442,30));
$TELEFONO=fixtext(substr($linea ,473,15));
$SELECT= "select * from REFERENCIAS where REFERENCIA='$REFERENCIA' and TELEFONO='$TELEFONO' and IDCONTACTO=$IDTITULAR";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$REFERENCIA2=$row['IDREFERENCIA'];
}else{
$INSERT= "insert into REFERENCIAS (IDCONTACTO,REFERENCIA,TELEFONO,FECHAALTA)
values ('$IDTITULAR','$REFERENCIA','$TELEFONO',now())";
mysql_query($INSERT, $conn );
$REFERENCIA2=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
}
$DOCUMENTOTIPO='T';
$DOCUMENTONUMEROG=fixtext(substr($linea ,36,7));
$GARANTE=fixtext(substr($linea ,506,30));
$IDGARANTE='';
if ($DOCUMENTONUMEROG&&$GARANTE){
$SELECT= "select * from CONTACTOS where DOCUMENTONUMERO=$DOCUMENTONUMEROG and DOCUMENTOTIPO='$DOCUMENTOTIPO'";
if (mysql_error()) echo $INSERT;
echo mysql_error();
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDGARANTE=$row['IDCONTACTO'];
$UPDATE= "update CONTACTOS set NOMBRE='$GARANTE' where IDCONTACTO=$IDGARANTE";
mysql_query($UPDATE);
}else{
$INSERT= "insert into CONTACTOS (DOCUMENTONUMERO,DOCUMENTOTIPO,NOMBRE,FECHAALTA) values ($DOCUMENTONUMEROG,'$DOCUMENTOTIPO','$GARANTE',now())";
mysql_query($INSERT, $conn );
$IDGARANTE=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
}
if ($IDGARANTE){
$CALLE=fixtext(substr($linea ,537,35));
$NUMERO=fixtext(substr($linea ,573,2));
$PISO=fixtext(substr($linea ,576,2));
$DEPTO=fixtext(substr($linea ,579,20));
$LOCALIDAD=fixtext(substr($linea ,600,4));
$SELECT= "select * from DIRECCIONES where CALLE='$CALLE' and NUMERO='$NUMERO' and PISO='$PISO' and DEPTO='$DEPTO' and LOCALIDAD='$LOCALIDAD' and IDCONTACTO=$IDGARANTE";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDDIRECCIONG=$row['IDDIRECCION'];
}else{
$INSERT= "insert into DIRECCIONES (IDCONTACTO,CALLE,NUMERO,PISO,DEPTO,LOCALIDAD,CODIGOPOSTAL,PLANO, COORDENADAS,FECHAALTA)
values ($IDGARANTE,'$CALLE','$NUMERO','$PISO','$DEPTO','$LOCALIDAD','$CODIGOPOSTAL','$PLANO','$COORDENADAS',now())";
mysql_query($INSERT);
$IDDIRECCIONG=mysql_insert_id();
}
}
if ($IDGARANTE){
$EMPRESA=fixtext(substr($linea ,614,20));
$DIRCALLE=fixtext(substr($linea ,635,25));
$NROEMPGARANTE=fixtext(substr($linea ,661,5));
$DIRNUMERO=fixtext(substr($linea ,667,20));
$SECCION=fixtext(substr($linea ,689,10));
$TELCODIGOAREA=fixtext(substr($linea ,609,5));
$TELNUMERO=fixtext(substr($linea ,705,15));
$TELINTERNO=fixtext(substr($linea ,721,12));
$SELECT= "select * from EMPLEOS where EMPRESA='$EMPRESA' and DIRCALLE='$DIRCALLE' and TELNUMERO='$TELNUMERO' and IDCONTACTO=$IDGARANTE";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDEMPLEOG=$row['IDEMPLEO'];
}else{
$INSERT= "insert into EMPLEOS (IDCONTACTO,EMPRESA,DIRCALLE,DIRNUMERO,SECCION,TELCODIGOAREA,TELNUMERO,TELINTERNO,FECHAALTA)
values ('$IDGARANTE','$EMPRESA','$DIRCALLE','$DIRNUMERO','$SECCION','$TELCODIGOAREA','$TELNUMERO','$TELINTERNO',now())";
mysql_query($INSERT, $conn );
$IDEMPLEOG=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
}
if ($IDTITULAR){
$IDMOROSO=$IDTITULAR;
$TIPOCARTERA=fixtext(substr($linea ,6,3));
$FECHAPROCESO='20'.substr($linea ,0,2).'-'.substr($linea ,2,2).'-'.substr($linea ,4,2);
$TIPOPROCESO=fixtext(substr($linea ,9,3));
$SUCURSAL=fixtext(substr($linea ,32,3));
if($TIPOCARTERA=='LIC'){
$NUMCREDITO=$DOCUMENTONUMERO;}
else
$NUMCREDITO=fixtext(substr($linea ,36,7));
$DOLARES=fixtext(substr($linea ,43,3));
$IMPORTE=fixtext(substr($linea ,47,10))/100;
$FECHA='20'.substr($linea ,64,2).'-'.substr($linea ,61,2).'-'.substr($linea ,58,2);
$CUOTAS=fixtext(substr($linea ,67,2));
$ULTIMACUOTA =fixtext(substr($linea ,70,2));
$DIAS=fixtext(substr($linea ,73,3));
$SALDO=fixtext(substr($linea ,78,14)/100);
$FRAVSAENZ=fixtext(substr($linea ,115,7));
$CUOTASATRASADAS=fixtext(substr($linea ,123,2));
$AUXNUEVO=fixtext(substr($linea ,126,2));
if (!$AUXNUEVO)$AUXNUEVO='00';
$CANTATRASADAS=fixtext(substr($linea ,134,5));
$CATEGORIA=fixtext(substr($linea ,255,1));
$TIPOCREDITO=fixtext(substr($linea ,489,2));
$VENDEDOR=fixtext(substr($linea ,492,4));
$OBSERVACIONES=fixtext(substr($linea ,828,30));
$DEBEPAGARINT=fixtext(substr($linea ,869,12));
$FECVENCIMIENTO=fixtext(substr($linea ,882,6));
$SALDOBCO=fixtext(substr($linea ,889,10));
$TIPOTARJETA=fixtext(substr($linea ,900,10));
$SALDOPESOS=fixtext(substr($linea ,911,10)/100);
$SALDODOLAR=fixtext(substr($linea ,922,10)/100);
$CANTIMP=fixtext(substr($linea ,932,4));
$DEBAUTO=fixtext(substr($linea ,1346,1));
$SELECT= "select * from HSTCARTERA where NUMCREDITO='$NUMCREDITO' and SUCURSAL='$SUCURSAL' and TIPOCARTERA='$TIPOCARTERA'";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$INSERT= "insert into CARTERA select * from HSTCARTERA where NUMCREDITO='$NUMCREDITO' and SUCURSAL='$SUCURSAL' and TIPOCARTERA='$TIPOCARTERA'";
mysql_query($INSERT, $conn );
$DELETE= "delete from HSTCARTERA where NUMCREDITO='$NUMCREDITO' and SUCURSAL='$SUCURSAL'";
mysql_query($DELETE, $conn );
}
$SELECT= "select * from CARTERA where NUMCREDITO='$NUMCREDITO' and SUCURSAL='$SUCURSAL'";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDCARTERA=$row['IDCARTERA'];
$UPDATE= "update CARTERA set
FECHAPROCESO= '$FECHAPROCESO',
AUXNUEVO='$AUXNUEVO',
IDMOROSO='$IDMOROSO',
TIPOCARTERA='$TIPOCARTERA',
TIPOPROCESO='$TIPOPROCESO',
SUCURSAL='$SUCURSAL',
IMPORTE='$IMPORTE',
FECHA='$FECHA',
CUOTAS='$CUOTAS',
ULTIMACUOTA='$ULTIMACUOTA',
DIAS='$DIAS',
SALDO='$SALDO',
FRAVSAENZ='$FRAVSAENZ',
CUOTASATRASADAS='$CUOTASATRASADAS',
CANTATRASADAS='$CANTATRASADAS',
CATEGORIA='$CATEGORIA',
TIPOCREDITO='$TIPOCREDITO',
VENDEDOR='$VENDEDOR',
OBSERVACIONES='$OBSERVACIONES',
DEBEPAGARINT='$DEBEPAGARINT',
FECVENCIMIENTO='$FECVENCIMIENTO',
SALDOBCO='$SALDOBCO',
TIPOTARJETA='$TIPOTARJETA',
SALDOPESOS='$SALDOPESOS',
SALDODOLAR='$SALDODOLAR',
CANTIMP='$CANTIMP',
DEBAUTO='$DEBAUTO'
where
NUMCREDITO='$NUMCREDITO' and SUCURSAL='$SUCURSAL' ";
mysql_query($UPDATE);echo mysql_error();
}else{
$INSERT= "insert into CARTERA (
IDMOROSO,
IDGARANTE,
TIPOCARTERA,
FECHAPROCESO,
TIPOPROCESO,
SUCURSAL,
NUMCREDITO,
DOLARES,
IMPORTE,
FECHA,
CUOTAS,
ULTIMACUOTA,
DIAS,
SALDO,
FRAVSAENZ,
CUOTASATRASADAS,
AUXNUEVO,
CANTATRASADAS,
CATEGORIA,
TIPOCREDITO,
VENDEDOR,
OBSERVACIONES,
DEBEPAGARINT,
FECVENCIMIENTO,
SALDOBCO,
TIPOTARJETA,
SALDOPESOS,
SALDODOLAR,
CANTIMP,FECHAALTA,DEBAUTO)
values (
'$IDMOROSO',
'$IDGARANTE',
'$TIPOCARTERA',
'$FECHAPROCESO',
'$TIPOPROCESO',
'$SUCURSAL',
'$NUMCREDITO',
'$DOLARES',
'$IMPORTE',
'$FECHA',
'$CUOTAS',
'$ULTIMACUOTA',
'$DIAS',
'$SALDO',
'$FRAVSAENZ',
'$CUOTASATRASADAS',
'$AUXNUEVO',
'$CANTATRASADAS',
'$CATEGORIA',
'$TIPOCREDITO',
'$VENDEDOR',
'$OBSERVACIONES',
'$DEBEPAGARINT',
'$FECVENCIMIENTO',
'$SALDOBCO',
'$TIPOTARJETA',
'$SALDOPESOS',
'$SALDODOLAR',
'$CANTIMP',NOW(),'$DEBAUTO')";
mysql_query($INSERT, $conn );
$IDCARTERA=mysql_insert_id();
echo mysql_error();
}
if ($IDCARTERA){
$CODIGOPRODUCTO=fixtext(substr($linea ,743,6));
$PRODUCTO=fixtext(substr($linea ,750,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,781,6));
$PRODUCTO=fixtext(substr($linea ,788,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,936,6));
$PRODUCTO=fixtext(substr($linea ,943,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,977,6));
$PRODUCTO=fixtext(substr($linea ,984,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,1018,6));
$PRODUCTO=fixtext(substr($linea ,1025,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,1059,6));
$PRODUCTO=fixtext(substr($linea ,1066,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,1100,6));
$PRODUCTO=fixtext(substr($linea ,1107,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,1141,6));
$PRODUCTO=fixtext(substr($linea ,1148,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
$CODIGOPRODUCTO=fixtext(substr($linea ,1182,6));
$PRODUCTO=fixtext(substr($linea ,1189,30));
$SELECT= "select * from PRODUCTOS where CODIGOPRODUCTO='$CODIGOPRODUCTO' and IDCARTERA=$IDCARTERA";
$result = mysql_query($SELECT, $conn );
if ($row = mysql_fetch_array($result)){
$IDPRODUCTO=$row['IDPRODUCTO'];
}elseif($CODIGOPRODUCTO){
$INSERT= "insert into PRODUCTOS (IDCARTERA,CODIGOPRODUCTO,PRODUCTO,FECHAALTA)
values ('$IDCARTERA','$CODIGOPRODUCTO','$PRODUCTO',now())";
mysql_query($INSERT, $conn );
$IDPRODUCTO=mysql_insert_id();
if (mysql_error()) echo $INSERT;
echo mysql_error();
}
}
}
}
echo $IDCARTERA."
";
}
fclose($gestor);
}
?>
<file_sep>from="<EMAIL>"
varLog=/home/callcenter/interfaz/proceso/logs/reportes_log.txt
eMail=/home/callcenter/interfaz/proceso/eMailReporte.sh
queries=/home/callcenter/interfaz/proceso/queries
archivos=/home/callcenter/interfaz/proceso/archivos
paso1=$queries/reporteDiarioEvolutivoPaso1.sql
paso2=$queries/reporteDiarioEvolutivoPaso2.sql
paso3=$queries/reporteDiarioEvolutivoPaso3PorGrupo.sql
paso4=$queries/reporteDiarioEvolutivoPaso4PorUsuario.sql
reportes=/home/callcenter/interfaz/proceso/reportes
archivo1=$archivos/ultimaFechaGuardada1.txt
archivo2=$archivos/ultimaFechaGuardada2.txt
ultimaFecha1=$(cat $archivo1)
ultimaFecha2=$(cat $archivo2)
comprobarErrores ()
{
#El parametro 3 es el nombre del script ejecutado y el parametro 2 es la direccion donde se encuentra el log, parametro 1 es $?
if [ $1 -eq 0 ]
then
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nSe ejecuto correctamente $3\n==============================="
echo -e $mensajeLog >> $2
else
mensajeLog="===============================\n$(date +%d/%m/%Y----%H.%M)\nHubo un error al ejecutar $3\n==============================="
echo -e "$mensajeLog" >> $2
fi
}
generarReporte ()
{
query=$(cat $1)
fecha=$(date +%d-%m-%Y-%H.%M)
echo $fecha > $3
#Esto te pide como primer parametro la query a ejecutar de la carpeta queries, y como segundo parametro el string para generar el reporte
mysql -se "$query" > /home/callcenter/interfaz/proceso/reportes/$2$fecha.xls
error=$?
comprobarErrores $error $varLog $2
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$2" -r "$from" <EMAIL>
echo -e "$mensajeLog" | mail -s "[CallMora]-Log_$2" -r "$from" <EMAIL>
}
ejecutarQuery ()
{
query=$(cat $1)
mysql -se "$query"
}
mandarMailAResponsablesReporteEvolutivo ()
{
$eMail 2 <EMAIL> "[CallMora]-Reporte_Diario_Evolutivo" $reportes/reporte_Diario_Evolutivo_Por_Grupo$ultimaFecha1.xls $reportes/reporte_Diario_Evolutivo_Por_Usuario$ultimaFecha2.xls
$eMail 2 <EMAIL> "[CallMora]-Reporte_Diario_Evolutivo" $reportes/reporte_Diario_Evolutivo_Por_Grupo$ultimaFecha1.xls $reportes/reporte_Diario_Evolutivo_Por_Usuario$ultimaFecha2.xls
#$eMail 2 <EMAIL> "[CallMora]-Reporte_Diario_Evolutivo" $reportes/reporte_Diario_Evolutivo_Por_Grupo$ultimaFecha1.xls $reportes/reporte_Diario_Evolutivo_Por_Usuario$ultimaFecha2.xls
}
ejecutarQuery $paso1
ejecutarQuery $paso2
generarReporte $paso3 reporte_Diario_Evolutivo_Por_Grupo $archivo1
generarReporte $paso4 reporte_Diario_Evolutivo_Por_Usuario $archivo2
mandarMailAResponsablesReporteEvolutivo<file_sep><?
//Funcion de lectura de archivos
function getFiles($directory) {
// Try to open the directory
if($dir = opendir($directory)) {
// Create an array for all files found
$tmp = Array();
// Add the files
while($file = readdir($dir)) {
// Make sure the file exists
if($file != "." && $file != ".." && $file[0] != '.') {
// If it's a directiry, list all files within it
if(is_dir($directory . "/" . $file)) {
$tmp2 = getFiles($directory . "/" . $file);
if(is_array($tmp2)) {
$tmp = array_merge($tmp, $tmp2);
}
} else {
array_push($tmp, $file);
}
}
}
// Finish off the function
closedir($dir);
return $tmp;
}
}
function fixtext($TEXT){
$TEXT=trim(str_replace("'","''",$TEXT));
$TEXT=trim(str_replace(chr(92).chr(92),"",$TEXT));
return $TEXT;
}
?>
<file_sep>#!/bin/bash
# Aquíonemos los datos de conexióSUARIO=usuario
USUARIO=fvgdatos
CLAVE=M0ntevide0
HOST=172.16.17.32
PUERTO=18024
lftp -e "set ftp:ssl-allow false" -p${PUERTO} -u ${USUARIO},${CLAVE} sftp://${HOST} << CMD
mput /home/callcenter/interfaz/data/*
bye
CMD
<file_sep>cd /home/callcenter/interfaz/proceso
/usr/bin/php totales.php
cd /home/callcenter/interfaz/procesar
mv a* ../auxiliar/
mv * ../procesados
mv ../auxiliar/* ./
gunzip *.gz
cd ../proceso
/usr/bin/php interfaz.php
# Call Externo Gering discontinuado
# /usr/bin/php ccext_gering_out.php
/usr/bin/php ccext_contactogarantido_in.php
/usr/bin/php ccext_contactogarantido_out.php
/usr/bin/php ccext_contactogarantido_out_send.php
cd /home/callcenter/htdocs/phpinclude
#CARGAR TABLA DE PARAMETROS DE FECHA DE CIERRE EFICIENCIA
#EN DISTRIBUCION.PHP TENGO QUE CONSULTAR ESTA TABLA Y METER UN IF PARA QUE CORRA O NO EL PROCESO
# D E S C O M E N T A R A LA NOCHE ANTERIOR DE LA DISTRIBUCION
# COMIENZA A EJECUTARSE A LAS 4am APROX
# /usr/bin/php distribucion.php
# C O M E N T A R AL DIA SIGUIENTE (SHELL DE LINUX)
#echo -e "=====\n$(date +%d/%m/%Y-----%H:%M) Proceso Original Diario Ejecutado\n=====" >> /home/callcenter/interfaz/proceso/logs/provisorio.txt
<file_sep>DELETE FROM USUARIOPERFILES_TMP WHERE IDGRUPO NOT IN (6,7,8,999,100) OR IDGRUPO IS NULL;<file_sep>if [ $1 -eq 0 ]
then
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nEl $2 se realizo correctamente\n===========================" > /home/callcenter/interfaz/proceso/message.txt
else
echo -e "$(date +%d/%m/%Y-----%H:%M)\n===========================\nERROR: en el $2\n===========================" > /home/callcenter/interfaz/proceso/message.txt
fi
cat /home/callcenter/interfaz/proceso/message.txt | mail -s "[Desarrollo] Reporte $2" "<EMAIL>"
#como parametro recibe el tipo de reporte que se va a realizar<file_sep> SELECT
GRUPO,
SUM(CANTIDADPENDIENTE) CANTIDADPENDIENTE,
ROUND(SUM(PENDIENTE)) PENDIENTE,
SUM(CANTIDADCANCELADO)CANTIDADCANCELADO,
ROUND(SUM(CANCELADO)) CANCELADO,
SUM(CANTIDADTOTAL)CANTIDADTOTAL,
ROUND(SUM(TOTAL)) TOTAL,
SUM(TOTALCARTERA) TOTALCARTERA,
SUM(CANCELADO)/SUM(TOTAL)*100 RECUPERO,
SUM(PENDIENTE)/SUM(TOTALCARTERA)*100 Eficiencia,
SUM(TOTAL)/SUM(TOTALCARTERA)*100 EFICIENCIA_INICIAL
FROM HSTREPORTE1 WHERE PERIODO=CONCAT(MONTH(CURRENT_DATE()),YEAR(CURRENT_DATE()))
GROUP BY GRUPO;
| 0985c1f954adc695b344853ae3f7b5b85f6fe3bd | [
"SQL",
"PHP",
"Shell"
] | 61 | SQL | yarito/callM | 3432da026286a12ed12f3747c843760a9fc7e4cf | 75104c3b64923680fef5c6227c1ff7cec674f45c |
refs/heads/master | <file_sep>// TODO
// Here we will contain a list of all possible actions for eventay
export const FETCH_EVENT = 'FETCH_EVENT';
export const RECEIVE_EVENT = 'RECEIVE_EVENT';
export const FETCH_FRIENDS = 'FETCH_FRIENDS';
export const RECEIVE_FRIENDS = 'RECEIVE_FRIENDS';
// Action to fetch current user info
export const RECEIVE_USERINFO = 'RECEIVE_USERINFO';
//action to fetch/recieve other users' info
export const RECEIVE_PROFILE = 'RECEIVE_PROFILE';
export const FETCH_PROFILE = 'FETCH_PROFILE';<file_sep>import React from 'react';
import Checkbox from 'material-ui/Checkbox';
const TimeOptions = props => {
return (
<div>
<h2 style={{fontWeight: '300'}}>Additional options:</h2>
<Checkbox
label="Exclude weekend times (Saturday/Sunday)"
name="excludeWeekends"
checked={props.excludeWeekends}
onCheck={props.handleCheckbox}
style={{ margin: '2%' }}
/>
<Checkbox
label="Exclude overnight times (11p-6a)"
name="excludeOvernight"
checked={props.excludeOvernight}
onCheck={props.handleCheckbox}
style={{ margin: '2%' }}
/>
<Checkbox
label="Exclude workday times (9a-4p)"
name="excludeWorkday"
checked={props.excludeWorkday}
onCheck={props.handleCheckbox}
style={{ margin: '2%' }}
/>
</div>
);
};
export default TimeOptions;
<file_sep>// each type of data/state should have its own individual reducer. This file will consolidate all reducers.
import { combineReducers } from 'redux';
import event from './eventReducer';
import friendsList from './friendReducer';
import userInfo from './userInfoReducer';
const rootReducer = combineReducers({
event,
friendsList,
userInfo
});
export default rootReducer;
<file_sep>const router = require('express').Router();
const controller = require('./attendantsController.js');
router.get('/:event_id', async (req, res) => {
try {
let data = await controller.getEventAttendants(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.get('/pendingInvites/:user_id', async (req, res) => {
try {
let data = await controller.getPendingAttending(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.route('/')
.post(async (req, res) => {
try {
await controller.addAttendant(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
})
.put(async (req, res) => {
try {
await controller.updateAttendant(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
})
.delete(async (req, res) => {
try {
await controller.removeAttendant(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
});
module.exports = router;
<file_sep>import React, { Component } from 'react';
import { ListItem, Avatar } from 'material-ui';
import ContentClear from 'material-ui/svg-icons/content/clear';
export default class Attendant extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<ListItem
primaryText={this.props.attendant.username}
leftAvatar={<Avatar src={this.props.attendant.profile_picture} />}
rightIcon={<ContentClear />}
onClick={() => this.props.uninvite(this.props.attendant.username)}
value={`${this.props.attendant.username} ${this.props.attendant.status}`}
key={this.props.id}
/>
</div>
);
}
}<file_sep>import initialState from './initialState';
import { FETCH_EVENT, RECEIVE_EVENT } from '../actions/actionTypes.js';
export default function auth(state = initialState.auth, action) {
let newState;
}
<file_sep>export default {
// add more states here.
event: [],
friendsList: [],
userInfo: {},
profileInfo: {}, // same object format as userInfo but specifically used for storing other user records
};
<file_sep>const db = require('../../db/db.js');
module.exports = {
addAttendant: async ({ access, status, user_id, event_id, invitor_id }) => {
try {
await db.queryAsync(`
INSERT INTO attendants (
access,
status,
user_id,
event_id,
invitor_id
) SELECT
'${access || 'member'}',
'${status || 'pending'}',
${user_id},
${event_id},
${invitor_id ? `'${invitor_id}'` : null}
`);
} catch (err) {
console.log('THE ERROR: ', err);
throw err;
}
},
getEventAttendants: async ({ event_id }) => {
try {
const attendants = [];
const { rows } = await db.queryAsync(`SELECT * FROM attendants WHERE event_id=${event_id}`);
for (let i = 0; i < rows.length; i++) {
const user = await db.queryAsync(`SELECT * FROM users WHERE id=${rows[i].user_id}`);
attendants.push(Object.assign(user.rows[0], rows[i]));
}
return attendants;
} catch (err) {
throw err;
}
},
getPendingAttending: async ({ user_id }) => {
try {
const getMyPendingInvites = await db.queryAsync(`
SELECT * FROM attendants
WHERE user_id=${user_id} AND status='pending'
`);
let getMyPendingEvents = [];
getMyPendingInvites.rows.forEach(invite => {
getMyPendingEvents.push(
db.queryAsync(`
SELECT * FROM events
WHERE id=${invite.event_id}
`)
);
});
return Promise.all(getMyPendingEvents).then(values =>
values.map(event => event.rows[0])
);
} catch (err) {
throw err;
}
},
getAllAttending: async ({ user_id }) => {
try {
const data = await db.queryAsync(`SELECT * FROM attendants WHERE user_id=${user_id}`);
return data.rows;
} catch (err) {
console.log(`Error during attendants GET request: ${err}`);
res.sendStatus(500);
}
},
showUserEvents: async user_id => {
try {
const userEvents = [];
const eventList = [];
let eventQuery;
const data = await db.queryAsync(
`SELECT * FROM attendants WHERE user_id=${user_id}`
);
data.rows.forEach(row => userEvents.push(row.event_id));
for (let i = 0; i < userEvents.length; i++) {
eventQuery = `SELECT * FROM events WHERE id=${userEvents[i]}`;
eventData = await db.queryAsync(eventQuery);
eventList.push(eventData.rows[0]);
}
return eventList;
} catch (err) {
throw err;
}
},
updateAttendant: async data => {
try {
let fields = Object.entries(data)
.map(
([key, value]) =>
typeof value === 'string'
? `${key} = '${value}'`
: `${key} = ${value}`
)
.join(', ');
await db.queryAsync(`
UPDATE attendants
SET ${fields}
WHERE user_id=${data.user_id} AND event_id=${data.event_id}
`);
} catch (err) {
throw err;
}
},
removeAttendant: async ({ user_id, event_id }) => {
try {
await db.queryAsync(`DELETE FROM attendants WHERE user_id=${user_id} AND event_id=${event_id}`);
} catch (err) {
throw err;
}
}
};
<file_sep>const db = require('./db.js');
let config;
try {
config = require('../config.js');
} catch (err) {
config = require('../config.example.js');
}
module.exports = {
drop: async (type, name) => {
try {
await db.queryAsync(`DROP ${type} IF EXISTS ${name}`);
console.log(`Successfully dropped ${type} ${name}.`);
} catch (err) {
console.log(`Error dropping ${type} ${name}.`);
}
},
useDatabase: async () => {
try {
await db.queryAsync(
`USE IF EXISTS ${
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
}`
);
console.log(
'Using database',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
} catch (err) {
console.log(
'Error using database',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
}
},
createDatabase: async () => {
try {
await db.queryAsync(
`CREATE DATABASE ${
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
}`
);
console.log(
'Successfully created database',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
} catch (err) {
console.log(
'Error creating database',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
}
},
createUsersTable: async () => {
try {
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS users
(
id SERIAL,
username VARCHAR(255) UNIQUE NOT NULL,
profile_picture VARCHAR(255),
bio TEXT,
likes_count INT NOT NULL DEFAULT 0,
CONSTRAINT users_pk
PRIMARY KEY(id)
)
`);
console.log('Successfully created users table.');
} catch (err) {
console.log('Error creating users table.', err);
}
},
createFriendsTable: async () => {
try {
await db.queryAsync('DROP TYPE IF EXISTS FRIEND_STATUS');
await db.queryAsync(`
CREATE TYPE FRIEND_STATUS AS ENUM (
'pending',
'accepted',
'blocked'
)
`);
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS friends
(
id SERIAL,
status FRIEND_STATUS NOT NULL DEFAULT 'pending',
user_id INT NOT NULL,
target_id INT NOT NULL,
CONSTRAINT friends_id
PRIMARY KEY(id),
CONSTRAINT fk_friends_user_id
FOREIGN KEY(user_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT fk_friends_target_id
FOREIGN KEY(target_id) REFERENCES users(id)
ON DELETE CASCADE
)
`);
console.log('Successfully created friends table.');
} catch (err) {
console.log('Error creating friends table.', err);
}
},
createEventsTable: async () => {
try {
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS events
(
id SERIAL,
title VARCHAR(255) NOT NULL,
description TEXT,
thumbnail VARCHAR(255),
location VARCHAR(255),
likes_count INT NOT NULL DEFAULT 0,
start_time TIMESTAMP,
end_time TIMESTAMP,
publicity BOOLEAN NOT NULL DEFAULT false,
host_id INT NOT NULL,
CONSTRAINT events_pk
PRIMARY KEY(id),
CONSTRAINT fk_events_host_id
FOREIGN KEY(host_id) REFERENCES users(id)
ON DELETE CASCADE
)
`);
console.log('Successfully created events table.');
} catch (err) {
console.log('Error creating events table.', err);
}
},
createAttendantsTable: async () => {
try {
await db.queryAsync('DROP TYPE IF EXISTS ATTENDANTS_STATUS');
await db.queryAsync(`
CREATE TYPE ATTENDANTS_STATUS AS ENUM (
'pending',
'going',
'declined',
'maybe'
)
`);
await db.queryAsync('DROP TYPE IF EXISTS ACCESS');
await db.queryAsync(`
CREATE TYPE ACCESS AS ENUM (
'host',
'privileged-member',
'member'
)
`);
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS attendants
(
id SERIAL,
status ATTENDANTS_STATUS NOT NULL DEFAULT 'pending',
access ACCESS NOT NULL DEFAULT 'member',
user_id INT NOT NULL,
event_id INT NOT NULL,
invitor_id INT,
CONSTRAINT attendants_id
PRIMARY KEY(id),
CONSTRAINT fk_attendants_user_id
FOREIGN KEY(user_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT fk_attendants_event_id
FOREIGN KEY(event_id) REFERENCES events(id)
ON DELETE CASCADE,
CONSTRAINT fk_attendants_invitor_id
FOREIGN KEY(invitor_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT uniq_user_id_event_id
UNIQUE (user_id, event_id)
)
`);
console.log('Successfully created attendants table.');
} catch (err) {
console.log('Error creating attendants table.', err);
}
},
createPostsTable: async () => {
try {
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS posts
(
id SERIAL,
body TEXT,
user_id INT NOT NULL,
event_id INT NOT NULL,
parent_id INT,
CONSTRAINT post_id
PRIMARY KEY(id),
CONSTRAINT fk_posts_user_id
FOREIGN KEY(user_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT fk_posts_event_id
FOREIGN KEY(event_id) REFERENCES events(id)
ON DELETE CASCADE,
CONSTRAINT fk_posts_parent_id
FOREIGN KEY(parent_id) REFERENCES posts(id)
ON DELETE CASCADE
)
`);
console.log('Successfully created posts table.');
} catch (err) {
console.log('Error creating posts table.', err);
}
},
createLikesTable: async () => {
try {
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS likes
(
id SERIAL,
user_id INT NOT NULL,
event_id iNT NOT NULL,
CONSTRAINT likes_id
PRIMARY KEY(id),
CONSTRAINT fk_likes_user_id
FOREIGN KEY(user_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT fk_likes_event_id
FOREIGN KEY(event_id) REFERENCES events(id)
ON DELETE CASCADE
)
`);
console.log('Successfully created likes table.');
} catch (err) {
console.log('Error creating likes table.', err);
}
},
createEmojisTable: async () => {
try {
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS emojis
(
id SERIAL,
body VARCHAR(255) NOT NULL,
user_id INT,
event_id INT,
CONSTRAINT emoji_id
PRIMARY KEY(id),
CONSTRAINT fk_emojis_user_id
FOREIGN KEY(user_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT fk_emojis_event_id
FOREIGN KEY(event_id) REFERENCES events(id)
ON DELETE CASCADE
)
`);
console.log('Successfully created emojis table.');
} catch (err) {
console.log('Error creating emojis table.', err);
}
},
createReactionsTable: async () => {
try {
await db.queryAsync(`
CREATE TABLE IF NOT EXISTS reactions
(
id SERIAL,
user_id INT NOT NULL,
emoji_id INT NOT NULL,
post_id INT NOT NULL,
CONSTRAINT reaction_id
PRIMARY KEY(id),
CONSTRAINT fk_reactions_user_id
FOREIGN KEY(user_id) REFERENCES users(id)
ON DELETE CASCADE,
CONSTRAINT fk_reactions_emoji_id
FOREIGN KEY(emoji_id) REFERENCES emojis(id)
ON DELETE CASCADE,
CONSTRAINT fk_reactions_post_id
FOREIGN KEY(post_id) REFERENCES posts(id)
ON DELETE CASCADE
)
`);
console.log('Successfully created reactions table.');
} catch (err) {
console.log('Error creating reactions table.', err);
}
}
};
<file_sep>const router = require('express').Router();
const controller = require('./usersController.js');
router.get('/:username', async (req, res) => {
try {
let data = await controller.getUserInfoByName(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.get('/id/:id', async (req, res) => {
try {
let data = await controller.getUserInfoById(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.route('/')
.put(async (req, res) => {
try {
let data = await controller.updateUser(req.body);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
module.exports = router;
<file_sep>import React from 'react';
import { Avatar, List, ListItem, Divider, TextField } from 'material-ui';
import axios from 'axios';
class Comment extends React.Component {
constructor(props) {
super(props);
this.state = {
inputTextComment: '',
comments: this.props.comments,
}
this.handleInputChange = this.handleInputChange.bind(this);
this.handlePostComment = this.handlePostComment.bind(this);
}
handleInputChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
handlePostComment(e) {
if (e.key === 'Enter' && !!this.state.inputTextComment.replace(/\s/g,'')) {
let bodyToSend = this.state.inputTextComment.replace("'", "''");
axios.post(`/api/post`, {
body: bodyToSend,
user_id: this.props.user.id,
event_id: this.props.event.id,
parent_id: this.props.postId,
}, this.props.config)
.then(res => {
const updatedCommentsList = this.state.comments;
axios.get(`/api/user/id/${res.data[0].user_id}`, this.props.config)
.then(({ data }) => {
const temp = res.data[0];
temp.userInfo = data;
updatedCommentsList.push(temp);
this.setState({ comments: updatedCommentsList });
});
});
this.setState({ inputTextComment: '' });
}
}
renderComments(commentList) {
return commentList.map(comment => {
return(
<ListItem
key={comment.id}
disabled={true}
leftAvatar={<Avatar
src={comment.userInfo.profile_picture}
style={{ objectFit: 'cover'}}
/>}
>
<span
onClick={() => this.props.history.push(`/profile/${comment.userInfo.username}`)}
><strong>{comment.userInfo.username}: </strong></span>
<p style={{ maxHeight: '8em', overflow: 'scroll', }}>
{comment.body}
</p>
</ListItem>
)
})
}
render() {
return(
<List>
{this.renderComments(this.state.comments)}
<TextField
disabled={this.props.role === 'stranger'}
name="inputTextComment"
value={this.state.inputTextComment}
onChange={this.handleInputChange}
onKeyDown={this.handlePostComment}
hintText="Respond..."
/>
</List>
)
}
}
export default Comment;<file_sep>const db = require('../../db/db');
module.exports = {
getUserInfoByName: async ({ username }) => {
try {
const data = await db.queryAsync(`SELECT * FROM users WHERE username='${username}'`);
return data.rows[0];
} catch (err) {
throw err;
}
},
getUserInfoById: async ({ id }) => {
try {
const data = await db.queryAsync(`SELECT * FROM users WHERE id=${id}`);
return data.rows[0];
} catch (err) {
throw err;
}
},
updateUser: async (data) => {
try {
let fields = Object.entries(data)
.map(([ key, value ]) =>
typeof value === 'string' ?
`${key} = '${value}'`
:
`${key} = ${value}`
)
.join(', ');
let user = await db.queryAsync(`UPDATE users SET ${fields} WHERE username='${data.username}' RETURNING profile_picture, bio, likes_count`);
return user.rows[0];
} catch (err) {
throw err;
}
}
};
<file_sep>const { Pool } = require('pg');
const Promise = require('bluebird');
let config;
try {
config = require('../config.js');
} catch (err) {
config = require('../config.example.js');
}
const db = new Pool({
user: config.rdb.user,
host: config.rdb.host,
database:
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev,
password: <PASSWORD>,
port: config.rdb.port,
max: 20
});
db.on('connect', () => {
console.log(
'Successfully connected to database',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
});
db.on('remove', client => {
console.log('Successfully removed client');
});
db.on('error', () => {
console.log(
'Error in database ',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
});
db.connect();
Promise.promisifyAll(db);
module.exports = db;
<file_sep>const login = require('./login.js');
const signup = require('./signup.js');
const { User } = require('./models/user.js');
module.exports = passportObj => {
passportObj.serializeUser((user, done) => {
done(null, user._id);
});
passportObj.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
// Passport strategies for login/signup
login(passportObj);
signup(passportObj);
};
<file_sep>const db = require('../../db/db');
module.exports = {
search: async (req, res) => {
const { user_id, query } = req.params;
try {
const makeQuery = (phrase, field) => {
let str = ``;
phrase.split(' ').forEach((word, i) => {
str += i
? ` OR LOWER(${field}) LIKE LOWER('%${word}%')`
: ` LOWER(${field}) LIKE LOWER('%${word}%')`;
});
return str;
};
const dbQueryFriends = `
SELECT * FROM users
WHERE ${makeQuery(query, 'username')}
`;
const dbQueryEvents = `
SELECT * FROM events
WHERE (host_id=${user_id} AND (${makeQuery(query, 'title')}))
OR (publicity=TRUE AND (${makeQuery(query, 'title')}))
`;
const dataFriends = await db.queryAsync(dbQueryFriends);
const dataEvents = await db.queryAsync(dbQueryEvents);
let obj = {};
obj.friends = dataFriends.rows;
obj.events = dataEvents.rows;
res.send(obj);
} catch (err) {
res.send(400);
}
}
};
<file_sep>import React from 'react';
import axios from 'axios';
import FriendsList from '../misc/friendsList.jsx';
import NavBar from './NavBar.jsx';
import Calendar from './Calendar.jsx';
import FriendsDrawer from './FriendsDrawer.jsx';
export default class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div
style={{
background: 'linear-gradient(#ffffea, #ffffff)',
}}
>
<NavBar history={this.props.history} />
{/* <FriendsList history={this.props.history} /> */}
<FriendsDrawer history={this.props.history} />
<Calendar history={this.props.history} />
</div>
);
}
}
<file_sep>import React from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn
} from 'material-ui/Table';
const FriendsTable = props => {
// TODO: add avatar pictures, pulling from user profiles
return (
<div>
<h2 style={{fontWeight: '300'}}>invite friends</h2>
<Table
multiSelectable={true}
onRowSelection={selectedRows => {
props.handleSelectionChange(selectedRows);
}}
>
<TableHeader>
<TableRow>
<TableHeaderColumn>Name</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody showRowHover={true} deselectOnClickaway={false}>
{props.allFriends &&
props.allFriends.map((friend, idx) => (
<TableRow selected={props.isSelected(idx)} key={friend[0]}>
<TableRowColumn>{friend[1]}</TableRowColumn>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
};
export default FriendsTable;
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const path = require('path');
const router = require('./router.js');
const app = express();
const authDb = require('./auth/db.js');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('tiny'));
app.use('/', express.static(path.join(__dirname, '/../client/public/')));
/* Start auth*/
const passportObj = require('passport');
const flash = require('connect-flash');
app.use(flash());
app.use(passportObj.initialize());
app.use(passportObj.session());
const initPassport = require('./auth/init.js');
initPassport(passportObj);
/*End auth*/
app.use('/api', router(passportObj));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, '/../client/public/index.html'), err => {
if (err) {
res.status(500).send(err);
}
});
});
// const port = 1337;
// app.listen(port, () => {
// console.log('Listening in port', port);
// });
module.exports.passportObj = passportObj;
module.exports.app = app;
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { Chip, Avatar, List, ListItem } from 'material-ui';
import { bindActionCreators } from 'redux';
import * as friendsActions from '../../actions/friendsActions';
import * as userInfoActions from '../../actions/userInfoActions';
import ContentAdd from 'material-ui/svg-icons/content/add';
import propTypes from 'prop-types';
class FriendsList extends React.Component {
constructor(props) {
super(props);
const user = JSON.parse(localStorage.getItem('userInfo'));
props.userInfoActions.receiveUserInfo(user);
this.getFriendsList();
this.state = {
enableForChat: false,
}
}
componentWillMount() {
this.props.history ? this.setState({ enableForChat: false }) : this.setState({ enableForChat: true });
}
getFriendsList() {
if (this.props.userInfo.id) {
this.props.friendsActions.fetchFriendsList(this.props.userInfo.id);
} else {
const user = JSON.parse(localStorage.getItem('userInfo'));
user
? this.props.friendsActions.fetchFriendsList(user.id)
: this.props.history.push('/login');
}
}
renderData(item) {
return (
<ListItem
primaryText={item.username}
rightIcon={this.props.invite ? <ContentAdd /> : null}
leftAvatar={<Avatar src={item.profile_picture} />}
onClick={
this.props.invite ? () => this.props.invite(item.username) :
this.props.history ?
() => this.props.history.push(`/profile/${item.username}`) :
() => this.props.handleChatWindow(item)
}
value={item.username}
key={item.id}
/>
);
}
render() {
if (this.props.friendsList.length) {
return (
<div>
<strong>Friends</strong> <br />
<List style={{ maxHeight: '10em', overflow: 'scroll', width: '20%', border: '1px solid #d3d3d3'}} >
{this.props.friendsList.map(friend => this.renderData(friend))}
</List>
</div>
);
} else {
return <div>No friends at the moment</div>;
}
}
}
FriendsList.propTypes = {
friendsActions: propTypes.object,
friendsList: propTypes.any
};
const mapStateToProps = state => {
return {
friendsList: state.friendsList,
userInfo: state.userInfo
};
};
const mapDispatchToProps = dispatch => {
return {
friendsActions: bindActionCreators(friendsActions, dispatch),
userInfoActions: bindActionCreators(userInfoActions, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(FriendsList);
<file_sep>var LocalStrategy = require('passport-local').Strategy;
var { User } = require('./models/user.js');
var bCrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
module.exports = passport => {
passport.use(
'signup',
new LocalStrategy(
{ session: false, passReqToCallback: true },
(req, username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) {
console.log('Error in signup: ' + err);
return done(err);
}
// User already exists
if (user) {
console.log('User already exists with username: ' + username);
return done(
null,
false /*req.flash('message', 'User Already Exists')*/
);
} else {
// Create new user
var newUser = new User();
newUser.username = username;
newUser.password = <PASSWORD>);
// Save the user
newUser.save(err => {
if (err) {
console.log('Error in Saving user:', err);
throw err;
}
console.log('User Registration successful');
const payload = {
userId: newUser._id,
username: newUser.username
};
// create a token string
const token = jwt.sign(payload, 'mySecret');
return done(null, newUser, token);
});
}
});
}
)
);
// Generates hash using bCrypt
var createHash = password =>
bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
<file_sep>const request = require('supertest');
const setup = require('../server/db/index.js');
const { app } = require('../server/index.js');
const auth = {};
beforeAll(async () => {
await setup();
const res = await request(app)
.post('/api/auth/signup')
.send({
username: 'testuser1',
password: 'pw1'
});
auth.token = res.body.token;
// await request(app)
// .post('/api/event')
// .send({ title: 'event1' });
// add token to header
// title,
// description,
// thumbnail,
// location,
// start_time,
// end_time,
// publicity,
// host_id;
// store the token in auth for each test to use
// create a user
// create an event
});
test('hi', () => {});
// describe('Posts', () => {
// test('Successfully create a post', async () => {
// // console.log('!!!', auth);
// // const res = await request(app)
// // .post('/api/post')
// // .send({
// // body: 'post1',
// // user_id: 1,
// // event_id: 1
// // });
// // // expect(res.statusCode).toBe(200);
// });
// });
<file_sep>import React, { Component } from 'react';
import BigCalendar from 'react-big-calendar';
import axios from 'axios';
import styles from 'react-big-calendar/lib/css/react-big-calendar.css';
import moment from 'moment';
BigCalendar.momentLocalizer(moment);
let formats = {
dayFormat: 'ddd' + ' ' + 'DD',
dayRangeHeaderFormat: ({ start, end }, culture, local) =>
local.format(start, 'MMM DD', culture) +
' - ' +
local.format(end, 'MMM DD', culture),
dateFormat: (date, culture, local) => local.format(date, 'DD', culture),
eventTimeRangeFormat: ({ start, end }, culture, local) =>
local.format(start, 'h:mm a', culture) +
' - ' +
local.format(end, 'h:mm a', culture)
};
export default class Calendar extends Component {
constructor(props) {
super(props);
this.state = { events: [] };
}
componentWillMount() {
const config = {
headers: { Authorization: 'bearer ' + localStorage.token }
};
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
if (userInfo) {
axios
.get(`/api/attendants/${userInfo.id}`, config)
.then(({ data }) => {
data = data.filter(event => event.status !== 'pending');
for (let i = 0; i < data.length; i++) {
axios
.get(`/api/event/eventinfo/${data[i].event_id}`, config)
.then(({ data: [event] }) => {
event.desc = event.description;
event.start = new Date(event.start_time);
event.end = new Date(event.end_time);
event.status = data[i].status;
let events = this.state.events;
events.push(event);
this.setState({ events: events });
});
}
})
.catch(err => {
console.log('Error:', err);
});
}
}
selectEvent(event) {
this.props.history.push({
pathname: `/event/${event.id}`,
state: { event: event }
});
}
eventPropGetter(event) {
return {
style: {
backgroundColor:
event.status === 'maybe'
? '#E8DEDE'
: event.status === 'declined' ? '#FE0000' : '#01FFFF'
}
};
}
render() {
return (
<div
id="calendar"
style={{
marginLeft: '10%',
marginRight: '10%',
}}
>
<BigCalendar
style={{
fontSize: '1.5em',
}}
{...this.props}
culture="en"
formats={formats}
events={this.state.events}
eventPropGetter={this.eventPropGetter}
onSelectEvent={this.selectEvent}
views={['month', 'week']}
startAccessor="start"
endAccessor="end"
defaultDate={new Date()}
showMultiDayTimes
popup={true}
/>
</div>
);
}
}
<file_sep>-- Insert dummy users
INSERT INTO users (username, profile_picture, bio) VALUES ('antonio',
'http://baypoint.academy/wp-content/uploads/2017/01/dummy-profile-pic-300x300.jpg', 'I love lamp');
INSERT INTO users (username, profile_picture, bio) VALUES ('alex',
'http://baypoint.academy/wp-content/uploads/2017/01/dummy-profile-pic-300x300.jpg', 'I love lamp');
INSERT INTO users (username, profile_picture, bio) VALUES ('will',
'http://baypoint.academy/wp-content/uploads/2017/01/dummy-profile-pic-300x300.jpg', 'I love lamp');
INSERT INTO users (username, profile_picture, bio) VALUES ('jason',
'http://baypoint.academy/wp-content/uploads/2017/01/dummy-profile-pic-300x300.jpg', 'I love lamp');
-- add friend relationships
INSERT INTO friends (status, user_id, target_id) VALUES ('accepted',
(SELECT id from users where username = 'antonio'), (SELECT id from users where username = 'alex'));
INSERT INTO friends (status, user_id, target_id) VALUES ('accepted',
(SELECT id from users where username = 'antonio'), (SELECT id from users where username = 'will'));
INSERT INTO friends (status, user_id, target_id) VALUES ('accepted',
(SELECT id from users where username = 'antonio'), (SELECT id from users where username = 'jason'));
-- add dummy events
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-07 09:00:00-07', '2018-05-07 11:00:00-07',
(SELECT id from users where username = 'antonio'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-07 13:00:00-07', '2018-05-07 14:00:00-07',
(SELECT id from users where username = 'antonio'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-07 15:00:00-07', '2018-05-07 17:00:00-07',
(SELECT id from users where username = 'antonio'), 'true');
('dummy event', 'this is a dummy event', '2018-05-07 10:00:00-07', '2018-05-07 12:00:00-07',
(SELECT id from users where username = 'will'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-07 15:00:00-07', '2018-05-07 17:00:00-07',
(SELECT id from users where username = 'will'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-07 11:00:00-07', '2018-05-07 12:00:00-07',
(SELECT id from users where username = 'alex'), 'true');
---
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 10:00:00-07', '2018-05-08 12:00:00-07',
(SELECT id from users where username = 'antonio'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 12:00:00-07', '2018-05-08 13:00:00-07',
(SELECT id from users where username = 'will'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 13:00:00-07', '2018-05-08 14:00:00-07',
(SELECT id from users where username = 'will'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 16:00:00-07', '2018-05-08 18:00:00-07',
(SELECT id from users where username = 'will'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 09:00:00-07', '2018-05-08 12:00:00-07',
(SELECT id from users where username = 'jason'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 11:00:00-07', '2018-05-08 11:30:00-07',
(SELECT id from users where username = 'alex'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-08 13:00:00-07', '2018-05-08 16:00:00-07',
(SELECT id from users where username = 'alex'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-09 10:00:00-07', '2018-05-09 12:00:00-07',
(SELECT id from users where username = 'jason'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-09 10:00:00-07', '2018-05-09 12:00:00-07',
(SELECT id from users where username = 'antonio'), 'true');
INSERT INTO events (title, description, start_time, end_time, host_id, publicity) VALUES
('dummy event', 'this is a dummy event', '2018-05-09 11:00:00-07', '2018-05-09 12:00:00-07',
(SELECT id from users where username = 'alex'), 'true');
<file_sep>import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import Signup from './components/routes/Signup.jsx';
import Home from './components/routes/Home.jsx';
import Login from './components/routes/Login.jsx';
import EventCreator from './components/routes/EventCreator/EventCreator.jsx';
import EventViewer from './components/routes/EventViewer.jsx';
import Profile from './components/routes/Profile.jsx';
import Protected from './components/Protected.jsx';
import Test from './components/routes/Test.jsx';
import Chat from './components/routes/Chat.jsx';
import Landing from './components/routes/landing/Landing.jsx';
import About from './components/routes/about/About.jsx';
export default class App extends Component {
render() {
return (
<Router>
<Switch>
<Route path="/test" exact component={Test} />
<Route path="/landing" component={Landing} />
<Route path="/about" component={About} />
<Route path="/signup" exact component={Signup} />
<Route path="/login" exact component={Login} />
<Route
path="/profile/:username"
component={props => <Protected component={Profile} {...props} />}
/>
<Route
path="/create"
component={props => (
<Protected component={EventCreator} {...props} />
)}
/>
<Route
path="/event/:id"
component={props => (
<Protected component={EventViewer} {...props} />
)}
/>
<Route
path="/chat"
component={props => <Protected component={Chat} {...props} />}
/>
<Route
path="/"
component={props => <Protected component={Home} {...props} />}
/>
</Switch>
</Router>
);
}
}
<file_sep>import React, { Component } from 'react';
import Avatar from 'material-ui/Avatar';
import './about.css';
import will from '../../../assets/will.jpg';
import tony from '../../../assets/tony.jpg';
import alex from '../../../assets/alex.jpg';
import jason from '../../../assets/jason.jpg';
import github from '../../../assets/GitHub.png';
export default class About extends Component {
render () {
return (
<div id="page">
<nav id="nav-top">
<div className='nav home'>
<a
href="/landing"
style={{
textDecoration: 'none',
color: 'black', paddingRight: '7%'
}}
>Home</a>
</div>
<div className='nav logo'>Eventé</div>
<div className='nav login'>
<div id='buttons'>
<a className="auth signup"
href="/signup"
style={{textDecoration: 'none', color: 'black', paddingRight: '7%'}}
>Signup</a>
<a className='auth log' href="/login"
style={{textDecoration: 'none', color: 'black'}}
>Login</a>
</div>
</div>
</nav>
<div id="levels">
<div id="will" className="dev">
<Avatar
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
src={will} size={230} />
<p className="dev-name" ><NAME></p>
<a
href="https://github.com/waruiz"
><img className="content" src={github} /></a>
<p className="content">
I enjoy the intellectual challenges of Software Engineering and the rewarding feeling of creating something that can touch millions of users' lives.
</p>
</div>
<div id="tony" className="dev">
<Avatar
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
src={tony} size={230} />
<p className="dev-name" ><NAME></p>
<a
href="https://github.com/toncas"
><img className="content" src={github} /></a>
<p className="content">
I deeply enjoy the spirit of collaboration and thrive within a team of exceptional developers.
</p>
</div>
<div id ="alex" className="dev">
<Avatar
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
src={alex} size={230} />
<p className="dev-name" ><NAME></p>
<a
href="https://github.com/alexmonirji"
><img className="content" src={github} /></a>
<p className="content">
Creating things brings me joy I cannot explain with words.
</p>
</div>
<div id="jason" className="dev">
<Avatar
style={{
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
}}
src={jason} size={230} />
<p className="dev-name" ><NAME></p>
<a
href="https://github.com/hirosato223"
><img className="content" src={github} /></a>
<p className="content">
I love taking on new challenges, learning new technologies, and empowering others to succeed.
</p>
</div>
</div>
</div>
);
}
}<file_sep>const db = require('../../db/db.js');
module.exports = {
addFriend: async ({ user_id, target_id }) => {
try {
await db.queryAsync(`
INSERT INTO friends (user_id, target_id)
SELECT ${user_id}, ${target_id}
WHERE NOT EXISTS (
SELECT * FROM friends
WHERE user_id=${user_id} AND target_id=${target_id} OR user_id=${target_id} AND target_id=${user_id}
)
`);
} catch (err) {
throw err;
}
},
checkFriendStatus: async ({ user_id, target_id }) => {
try {
const data = await db.queryAsync(`
SELECT * FROM friends
WHERE ((user_id='${user_id}' AND target_id='${target_id}') OR (user_id='${target_id}' AND target_id='${user_id}'))
`);
return data.rows;
} catch (err) {
throw err;
}
},
getPendingFriends: async ({ user_id }) => {
try {
const data = await db.queryAsync(`
SELECT id, username, profile_picture FROM users
WHERE id IN (
SELECT user_id FROM friends
WHERE target_id=${user_id} AND status='pending'
)
`);
return data.rows;
} catch (err) {
throw err;
}
},
getAllFriends: async ({ user_id }) => {
try {
const friendsUserInfo = [];
const data = await db.queryAsync(`
SELECT * FROM friends
WHERE (user_id=${user_id} OR target_id=${user_id}) AND status='accepted'
`);
for (let i = 0; i < data.rows.length; i++) {
const id =
data.rows[i].user_id === +user_id
? data.rows[i].target_id
: data.rows[i].user_id;
const userInfo = await db.queryAsync(
`SELECT * FROM users WHERE id=${id}`
);
friendsUserInfo.push(userInfo.rows[0]);
}
return friendsUserInfo;
} catch (err) {
throw err;
}
},
updateFriend: async ({ user_id, target_id, status }) => {
if (status === 'blocked') {
try {
await db.queryAsync(`
UPDATE friends
SET status='${status}'
WHERE (user_id=${target_id} AND target_id=${user_id}) OR (user_id=${user_id} AND target_id=${target_id})
`);
} catch (err) {
throw err;
}
} else {
try {
await db.queryAsync(`
UPDATE friends
SET status='${status}'
WHERE (user_id=${target_id} AND target_id=${user_id})
`);
} catch (err) {
throw err;
}
}
},
removeFriend: async ({ user_id, target_id }) => {
try {
const data = await db.queryAsync(`
DELETE FROM friends
WHERE (user_id=${user_id} AND target_id=${target_id}) OR (user_id=${target_id} AND target_id=${user_id})
`);
} catch (err) {
throw err;
}
}
};
<file_sep>const db = require('../../db/db');
module.exports = {
createEvent: async ({
title,
description,
thumbnail,
location,
start_time,
end_time,
publicity,
host_id
}) => {
try {
const data = await db.queryAsync(`
INSERT INTO events (
title,
description,
thumbnail,
location,
start_time,
end_time,
publicity,
host_id
) VALUES (
'${title}',
${description ? `'${description}'` : null},
${thumbnail ? `'${thumbnail}'` : null},
${location ? `'${location}'` : null},
${start_time ? `'${start_time}'` : null},
${end_time ? `'${end_time}'` : null},
${publicity ? `'${publicity}'` : false},
'${host_id}'
) RETURNING id
`);
await db.queryAsync(`
INSERT INTO attendants (access, status, user_id, event_id, invitor_id)
VALUES ('host', 'going', ${host_id}, ${data.rows[0].id}, null)
`);
return data.rows;
} catch (err) {
console.log('ERROR IS: ', err);
throw err;
}
},
getHostingEvents: async ({ user_id }) => {
try {
const data = await db.queryAsync(`SELECT * FROM events WHERE host_id='${user_id}'`);
return data.rows;
} catch (err) {
throw err;
}
},
updateEvent: async (data) => {
try {
console.log('data:', data);
let fields = Object.entries(data)
.map(([ key, value ]) =>
typeof value === 'string' ?
`${key}='${value}'`
:
`${key}=${value}`
)
.join(',');
console.log('fields:', fields)
await db.queryAsync(`UPDATE events SET ${fields} WHERE id=${data.id}`);
console.log('put');
} catch (err) {
console.log('err:', err);
throw err;
}
},
removeEvent: async ({ event_id }) => {
try {
await db.queryAsync(`
DELETE FROM events
WHERE id=${event_id}
`);
} catch (err) {
throw err;
}
},
getEventDetails: async ({event_id}) => {
try {
const data = await db.queryAsync(`
SELECT * FROM events
WHERE id=${event_id}`);
return data.rows;
} catch (err) {
throw err;
}
}
};
<file_sep>import React, { Component } from 'react';
// import '../../../../public/reset.css';
import styles from './landing.css';
import img_profile from '../../../assets/profile.png';
import create1 from '../../../assets/create1.png';
import notifs from '../../../assets/notifs.png';
export default class Landing extends Component {
constructor (props) {
super (props);
}
carousel (imgArr) {
return imgArr[0];
}
render () {
return (
<div id='page'>
<nav id='nav-top'>
<div className='nav about'>
<a
href="/about"
style={{
textDecoration: 'none',
color: 'black', paddingRight: '7%'
}}
>About</a>
</div>
<div className='nav logo'>Eventé</div>
<div className='nav login'>
<div id='buttons'>
<a className="auth signup"
href="/signup"
style={{textDecoration: 'none', color: 'black', paddingRight: '7%'}}
>Signup</a>
<a className='auth log' href="/login"
style={{textDecoration: 'none', color: 'black'}}
>Login</a>
</div>
</div>
</nav>
<div id='levels'>
<div id='profile-image'>
<img src={img_profile} />
</div>
<div id="profile-description">
<p>
Eventé makes it easy and fun to schedule times to meet others.
</p>
<p>
Scheduling a fun brunch or evening with friends should be about
the experiences you create and memories you share - it should not
be about asking everyone, rescheduling, and some of your friends
missing out due to scheduling conflicts.
</p>
</div>
<div id="event-description">
<p>
Eventé makes it easy to schedule events with friends and coworkers.
Simply create an event, select who you want to invite, and Eventé's
deep logic algorithms will only recommend times you are all available to meet.
</p>
</div>
<div id="event-image">
<img src={this.carousel([create1])} />
</div>
<div id="notifs-image">
<img src={this.carousel([notifs])} />
</div>
<div id="notifs-content">
<p>
Always be in the loop of when your friends and coworkers are meeting.
Never miss an update. You are instantly notified when someone's invited
you to a new event, or sent you a friend request.
</p>
<p>
You can also search your events, events you've been invited to, public
events local and worldwide, as well as public profiles.
</p>
</div>
</div>
</div>
);
}
}
<file_sep># Eventé
Eventé allows you to schedule and invite friends to events without worrying about the risk of scheduling conflicts
## Getting Started
Follow these instructions if you want a working copy of Eventé up and running in your local machine for contributions and testing purposes: (Note: Please look through the _Prerequisites_ section before proceeding)
1. Open up your terminal
2. `cd to/your/top/level/directory`
2. `git clone https://github.com/JawaScriptLA/eventay.git`
4. `cd eventay`
5. `npm install`
6. `npm run build`
7. `mongod`
8. `npm run chat:start`
9. `npm start`
10. Navigate to `127.0.0.1:1337` for glory.
### Prerequisites
What things you need to install the software and how to install them. Our team developed exclusively on OSX and we'll assume you are too. Google the appropriate instructions for your OS environment as needed.
**Homebrew (OSX only)**
You can find instructions on how to install Homebrew [here](https://brew.sh/).
**MongoDB**
[Install and Run MongoDB with Homebrew](https://treehouse.github.io/installation-guides/mac/mongo-mac.html)
**Postgres**
[Installing Postgres](https://www.codementor.io/engineerapart/getting-started-with-postgresql-on-mac-osx-are8jcopb#2-installing-postgres)
## Running the tests
Testing suite in progress
### Break down into end to end tests
Todo: Explain what these tests test and why
```
Todo: commands for tests
```
## Built With
* [NodeJS](https://nodejs.org/en/) - Runtime framework
* [npm](https://www.npmjs.com/) - Dependency Management
* [ReactJS](https://rometools.github.io/rome/) - Front-end framework
* [Material-ui](http://www.material-ui.com/) - UI library
* [Express]() - Runtime
* [TravisCI]() - Continuous Integration
* [Jest]() - Testing
* [Postgres]() - Primary DB
Others:
* [MongoDB]()
* [Passport]()
* [Redux]()
* [JWT]()
* [AWS]()
* [FileStack]()
* [Babel]()
## Contributing
We're currently not accepting contributions at this time. Perhaps some day in the future.
## Authors
_Owner_
* **<NAME>** - *Product Owner, Algorithm Guru, Testing* - [Github](https://github.com/hirosato223)
_Dev Team_
* **<NAME>** - *Full Stack, Deployment, and API* - [Github](https://github.com/alexmonirji)
* **<NAME>** - *Full Stack, API, Websockets* - [Github](https://github.com/toncas)
* **<NAME>** - *Full Stack, Database Schema Designer, API, nginx* - [Github](https://github.com/waruiz)
## License
This project is __Unlicensed__ - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
* Hack Reactor, Los Angeles
<file_sep>const mongoose = require('mongoose');
const config = require('../config.js');
const authDbName =
config.rdb.environment === 'test'
? config.auth.uri_testing
: config.auth.uri_dev;
mongoose.connect(authDbName);
const authDb = mongoose.connection;
authDb.once('open', () => {
console.log(`Mongoose connected successfully to ${authDbName}`);
});
authDb.on('error', () => {
console.log(`mongoose connection error with ${authDbName}`);
});
module.exports.authDb = authDb;
<file_sep>import React from 'react';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import { RaisedButton } from 'material-ui';
class CreatePost extends React.Component {
constructor(props) {
super(props);
this.state = {
postText: '',
}
this.handlePost = this.handlePost.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
handlePost(e) {
this.props.generatePost(this.state.postText);
this.setState({ postText: '' });
}
render() {
return (
<Paper
style={{ width: '50%', overflow: 'scroll', padding:'10px'}}
zDepth={1}
children={
<div>
<TextField
disabled={this.props.role === 'stranger'}
rows={1}
rowsMax={4}
hintText={(this.props.role !== 'stranger') ? 'Say something...': 'RSVP to post something...'}
name='postText'
fullWidth={true}
value={this.state.postText}
multiLine={true}
onChange={this.handleInputChange}
/>
<RaisedButton
disabled={!!!this.state.postText.replace(/\s/g,'')} // handles when user spams only whitespace
label='Post'
primary={true}
onClick={this.handlePost}
/>
</div>
}
/>
);
}
}
export default CreatePost;<file_sep>import React, { Component } from 'react';
import axios from 'axios';
import NavBar from './NavBar.jsx';
import AttendantsList from '../misc/AttendantsList.jsx';
import CreatePost from '../posts/CreatePost.jsx';
import { Avatar, Dialog, Paper, TextField, Divider } from 'material-ui';
import Posts from '../posts/Posts.jsx';
import FriendsList from '../misc/friendsList.jsx';
import { convertTime } from '../../../../utils/utils.js';
import ReactFilestack from 'filestack-react';
import filestack from '../../../config.js';
import RaisedButton from 'material-ui/RaisedButton';
export default class EventViewer extends Component {
constructor(props) {
super(props);
this.state = {
config: {
headers: { Authorization: 'bearer ' + localStorage.getItem('token') }
},
event: {},
user: {},
friends: [],
attendants: null,
role: '',
posts: [],
mode: 'view',
changeTitle: '',
changeDescription: '',
changeStartTime: '',
changeEndTime: '',
changeStartMonth: '',
changeEndMonth: '',
changeStartDate: '',
changeEndDate: '',
changeStartYear: '',
changeEndYear: ''
};
this.generatePost = this.generatePost.bind(this);
this.handleInvite = this.handleInvite.bind(this);
this.handleUninvite = this.handleUninvite.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleSave = this.handleSave.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleThumbnailUpload = this.handleThumbnailUpload.bind(this);
}
componentWillMount() {
this.setState({ user: JSON.parse(localStorage.getItem('userInfo')) });
this.props.location.state ? (
this.props.location.state.event.startTime = `${convertTime(this.props.location.state.event.start_time).split(' ')[4]} ${convertTime(this.props.location.state.event.start_time).split(' ')[5]}`,
this.props.location.state.event.endTime = `${convertTime(this.props.location.state.event.end_time).split(' ')[4]} ${convertTime(this.props.location.state.event.end_time).split(' ')[5]}`,
this.props.location.state.event.startMonth = convertTime(this.props.location.state.event.start_time).split(' ')[1],
this.props.location.state.event.endMonth = convertTime(this.props.location.state.event.end_time).split(' ')[1],
this.props.location.state.event.startDate = convertTime(this.props.location.state.event.start_time).split(' ')[2].substring(0, convertTime(this.props.location.state.event.start_time).split(' ')[2].length - 1),
this.props.location.state.event.endDate = convertTime(this.props.location.state.event.start_time).split(' ')[2].substring(0, convertTime(this.props.location.state.event.end_time).split(' ')[2].length - 1),
this.props.location.state.event.startYear = convertTime(this.props.location.state.event.start_time).split(' ')[3],
this.props.location.state.event.endYear = convertTime(this.props.location.state.event.start_time).split(' ')[3],
this.setState({
event: this.props.location.state.event,
changeTitle: this.props.location.state.event.title,
changeDescription: this.props.location.state.event.description,
changeStartTime: `${this.props.location.state.event.startTime.split(' ')[0]} ${this.props.location.state.event.startTime.split(' ')[1]}`,
changeEndTime: `${this.props.location.state.event.endTime.split(' ')[0]} ${this.props.location.state.event.endTime.split(' ')[1]}`,
changeStartMonth: this.props.location.state.event.startMonth,
changeEndMonth: this.props.location.state.event.endMonth,
changeStartDate: this.props.location.state.event.startDate,
changeEndDate: this.props.location.state.event.endDate,
changeStartYear: this.props.location.state.event.startYear,
changeEndYear: this.props.location.state.event.endYear
})
) :
axios.get(`/api/event/eventinfo/${this.props.match.params.id}`, this.state.config)
.then((res) => {
res.data[0].startTime = `${convertTime(res.data[0].start_time).split(' ')[4]} ${convertTime(res.data[0].start_time).split(' ')[5]}`;
res.data[0].endTime = `${convertTime(res.data[0].end_time).split(' ')[4]} ${convertTime(res.data[0].end_time).split(' ')[5]}`;
res.data[0].startMonth = convertTime(res.data[0].start_time).split(' ')[1];
res.data[0].endMonth = convertTime(res.data[0].end_time).split(' ')[1];
res.data[0].startDate = convertTime(res.data[0].start_time).split(' ')[2].substring(0, convertTime(res.data[0].start_time).split(' ')[2].length - 1);
res.data[0].endDate = convertTime(res.data[0].end_time).split(' ')[2].substring(0, convertTime(res.data[0].end_time).split(' ')[2].length - 1);
res.data[0].startYear = convertTime(res.data[0].start_time).split(' ')[3];
res.data[0].endYear = convertTime(res.data[0].end_time).split(' ')[3];
this.setState({
event: res.data[0],
changeTitle: res.data[0].title,
changeDescription: res.data[0].description,
changeStartTime: `${res.data[0].start_time.split(' ')[4]} ${res.data[0].start_time.split(' ')[5]}`,
changeEndTime: `${res.data[0].end_time.split(' ')[4]} ${res.data[0].end_time.split(' ')[5]}`,
changeStartMonth: res.data[0].startMonth,
changeEndMonth: res.data[0].endMonth,
changeStartDate: res.data[0].startDate,
changeEndDate: res.data[0].endDate,
changeStartYear: res.data[0].startYear,
changeEndYear: res.data[0].endYear
});
})
.catch((err) => console.error('Error get event info: ', err));
}
init() {
if (Object.keys(this.state.event).length > 0) {
axios
.get(`/api/friends/${this.state.user.id}`, this.state.config)
.then(friends => this.setState({ friends: friends.data }))
.catch(err => console.error('Error friends:', err));
axios
.get(`/api/attendant/${this.state.event.id}`, this.state.config)
.then(attendants => {
let attendantStatus = attendants.data.reduce(
(acc, attendant) =>
acc[0]
? acc
: attendant.user_id === this.state.user.id
? [true, attendant.status]
: acc,
[false, '']
);
this.setState({
attendants: attendants.data,
role:
this.state.event.host_id === this.state.user.id
? 'host'
: attendantStatus[0] ? attendantStatus[1] : 'stranger'
});
})
.catch(err => console.error('Error attendants:', err));
axios
.get(`/api/post/${this.state.event.id}`, this.state.config)
.then(res => {
const processedPosts = [];
const processedComments = [];
const postObjList = [];
for (let i = 0; i < res.data.length; i++) {
axios
.get(`/api/user/id/${res.data[i].user_id}`, this.state.config)
.then(userRes => {
res.data[i].userInfo = userRes.data;
res.data[i].parent_id
? processedComments.push(res.data[i])
: processedPosts.push(res.data[i]);
if (res.data.length - 1 === i) {
for (let i = 0; i < processedPosts.length; i++) {
let postObj = {};
postObj.post = processedPosts[i];
postObj.comments = processedComments.filter(
comment => comment.parent_id === processedPosts[i].id
);
postObjList.push(postObj);
}
this.setState({ posts: postObjList });
}
});
}
})
.catch(err => console.error('Error posts:', err));
axios
.get(`/api/user/id/${this.state.event.host_id}`, this.state.config)
.then(host => this.setState({ host: host.data }))
.catch(err => console.error('Error users:', err));
}
}
generatePost(body) {
let bodyToSend = body.replace("'", "''");
axios
.post(
`/api/post`,
{
body: bodyToSend,
user_id: this.state.user.id,
event_id: this.state.event.id,
parent_id: null
},
this.state.config
)
.then(res => {
const updatedPostList = this.state.posts;
axios
.get(`/api/user/id/${res.data[0].user_id}`, this.state.config)
.then(({ data }) => {
const temp = res.data[0];
temp.userInfo = data;
updatedPostList.push({ post: temp, comments: [] });
this.setState({ posts: updatedPostList });
});
});
}
handleInvite(name) {
axios.get(`/api/user/${name}`, this.state.config)
.then(({ data }) => {
axios.post(`/api/attendant`, {
access: 'member',
status: 'pending',
user_id: data.id,
event_id: this.state.event.id,
invitor_id: this.state.user.id
}, this.state.config)
.then(() => console.log(`Successfully invited ${name}.`));
})
.catch(err => console.error(err));
}
handleUninvite(name) {
if (this.state.role === 'host') {
axios.get(`/api/user/${name}`, this.state.config)
.then(({ data }) => {
axios.delete(`/api/attendant`, {
data: {
user_id: data.id,
event_id: this.state.event.id
},
headers: this.state.config.headers
})
.then(() => console.log(`Successfully uninvited ${name}.`));
})
.catch((err) => console.error(err));
} else {
console.log('Permission denied.');
}
}
handleResponse(status) {
axios
.put(
'/api/attendant',
{
user_id: this.state.user.id,
event_id: this.state.event.id,
status: status
},
this.state.config
)
.then(res => this.setState({ role: status }))
.catch(err => console.error(err));
}
handleEdit() {
this.setState({ mode: 'edit' });
}
handleSave() {
let startAdd = 0;
let startHour = this.state.changeStartTime.split(':')[0];
this.state.changeStartTime.split(' ')[1] === 'pm' ? startHour !== '12' ? startAdd = 12 : null : startHour === '12' ? startHour = '00' : null;
let startMonth = this.state.changeStartMonth === 'Jan' ? 0 : this.state.changeStartMonth === 'Feb' ? 1 : this.state.changeStartMonth === 'Mar' ? 2 : this.state.changeStartMonth === 'Apr' ? 3 : this.state.changeStartMonth === 'May' ? 4 : this.state.changeStartMonth === 'Jun' ? 5 : this.state.changeStartMonth === 'Jul' ? 6 : this.state.changeStartMonth === 'Aug' ? 7 : this.state.changeStartMonth === 'Sep' ? 8 : this.state.changeStartMonth === 'Oct' ? 9 : this.state.changeStartMonth === 'Nov' ? 10 : this.state.changeStartMonth === 'Dec' ? 12 : null;
let endMonth = this.state.changeEndMonth === 'Jan' ? 0 : this.state.changeEndMonth === 'Feb' ? 1 : this.state.changeEndMonth === 'Mar' ? 2 : this.state.changeEndMonth === 'Apr' ? 3 : this.state.changeEndMonth === 'May' ? 4 : this.state.changeEndMonth === 'Jun' ? 5 : this.state.changeEndMonth === 'Jul' ? 6 : this.state.changeEndMonth === 'Aug' ? 7 : this.state.changeEndMonth === 'Sep' ? 8 : this.state.changeEndMonth === 'Oct' ? 9 : this.state.changeEndMonth === 'Nov' ? 10 : this.state.changeEndMonth === 'Dec' ? 12 : null;
startHour = +startHour + startAdd;
let startMinute = +this.state.changeStartTime.split(':')[1].split(' ')[0];
let endAdd = 0;
let endHour = this.state.changeEndTime.split(':')[0];
this.state.changeEndTime.split(' ')[1] === 'pm' ? endHour !== '12' ? endAdd = 12 : null : endHour === '12' ? endHour = '00' : null;
endHour = +endHour + endAdd;
let endMinute = +this.state.changeEndTime.split(':')[1].split(' ')[0];
axios.put('/api/event', {
title: this.state.changeTitle,
description: this.state.changeDescription,
start_time: new Date(+this.state.changeStartYear, startMonth, +this.state.changeStartDate, startHour, startMinute),
end_time: new Date(+this.state.changeEndYear, endMonth, +this.state.changeEndDate, endHour, endMinute),
id: this.state.event.id
}, this.state.config)
.then(() => {
this.state.event.title = this.state.changeTitle;
this.state.event.description = this.state.changeDescription;
this.state.event.startTime = this.state.changeStartTime;
this.state.event.endTime = this.state.changeEndTime;
this.state.event.startMonth = this.state.changeStartMonth;
this.state.event.endMonth = this.state.changeEndMonth;
this.state.event.startDate = this.state.changeStartDate;
this.state.event.endDate = this.state.changeEndDate;
this.state.event.startYear = this.state.changeStartYear;
this.state.event.endYear = this.state.changeEndYear;
this.setState({
mode: 'view',
event: this.state.event
});
})
.catch((err) => console.error(err));
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
handleThumbnailUpload(res) {
let url = res.filesUploaded[0].url;
axios.put('/api/event', {
thumbnail: url,
id: this.state.event.id
}, this.state.config)
.then(() => {
this.state.event.thumbnail = url;
this.setState({ event: this.state.event });
})
.catch((err) => console.error(err));
}
render() {
if (!this.state.event) {
return <div>This is not an event</div>;
} else if (!Array.isArray(this.state.attendants)) {
this.init();
return <div>Loading...</div>;
}
return (
<div>
<NavBar history={this.props.history} />
{this.state.mode === 'view' ?
<h2>{this.state.event.title}</h2>
: <span><TextField
onChange={this.handleChange}
type="text"
name="changeTitle"
value={this.state.changeTitle}
/><br/></span>}
{
this.state.mode === 'view' ?
<p>{this.state.event.description}</p> :
<TextField
onChange={this.handleChange}
type="text"
name="changeDescription"
value={this.state.changeDescription}
/>
}
<Paper>
<div>
{this.state.event && this.state.event.thumbnail ? <Avatar size={200} src={this.state.event.thumbnail} /> : null}
{this.state.host ? <span><p><em>Hosted by: </em>{this.state.host.username}</p></span> : null}
</div>
<Divider/>
{this.state.event.startTime ?
this.state.mode === 'view' ?
this.state.event.startTime === this.state.event.endTime ?
this.state.event.startTime
: `${this.state.event.startTime} - ${this.state.event.endTime}`
: <TextField
onChange={this.handleChange}
type="text"
name="changeStartTime"
value={this.state.changeStartTime}
/>
: 'Loading...'}
{this.state.mode === 'edit' ? ' - ' : null}
{this.state.mode === 'edit' ?
<TextField
onChange={this.handleChange}
type="text"
name="changeEndTime"
value={this.state.changeEndTime}
/> : null}
<br/>
{this.state.event.startMonth ?
this.state.mode === 'view' ?
this.state.event.startMonth === this.state.event.endMonth ?
this.state.event.startMonth
: `${this.state.event.startMonth} - ${this.state.event.endMonth}`
: <TextField
onChange={this.handleChange}
type="text"
name="changeStartMonth"
value={this.state.changeStartMonth}
/>
: null}
{this.state.mode === 'edit' ? ' - ' : null}
{this.state.mode === 'edit' ?
<TextField
onChange={this.handleChange}
type="text"
name="changeEndMonth"
value={this.state.changeEndMonth}
/> : null}
<br/>
{this.state.event.startDate ?
this.state.mode === 'view' ?
this.state.event.startDate === this.state.event.endDate ?
this.state.event.startDate
: `${this.state.event.startDate} - ${this.state.event.endDate}`
: <TextField
onChange={this.handleChange}
type="text"
name="changeStartDate"
value={this.state.changeStartDate}
/>
: null}
{this.state.mode === 'edit' ? ' - ' : null}
{this.state.mode === 'edit' ?
<TextField
onChange={this.handleChange}
type="text"
name="changeEndDate"
value={this.state.changeEndDate}
/> : null}
<br/>
{this.state.event.startYear ?
this.state.mode === 'view' ?
this.state.event.startYear === this.state.event.endYear ?
this.state.event.startYear
: `${this.state.event.startYear} - ${this.state.event.endYear}`
: <TextField
onChange={this.handleChange}
type="text"
name="changeStartYear"
value={this.state.changeStartYear}
/>
: null}
{this.state.mode === 'edit' ? ' - ' : null}
{this.state.mode === 'edit' ?
<TextField
onChange={this.handleChange}
type="text"
name="changeEndYear"
value={this.state.changeEndYear}
/> : null}
</Paper>
<br/>
{
this.state.role === 'host' ?
this.state.mode === 'view' ?
<div>
<RaisedButton onClick={this.handleEdit}>Edit</RaisedButton>
<ReactFilestack
apikey={filestack.API_KEY2}
buttonText="Update event thumbnail"
render={({ onPick }) => (
<RaisedButton
label="Update Event Thumbnail"
onClick={onPick}
/>
)}
options={{
accept: 'image/*',
maxFiles: 1,
fromSources: ['local_file_system', 'imagesearch', 'url']
}}
onSuccess={this.handleThumbnailUpload}
/>
</div>
: <RaisedButton onClick={this.handleSave}>Save</RaisedButton>
: this.state.role === 'pending' ?
<div>
<button onClick={() => this.handleResponse('going')}>Accept</button>
<button onClick={() => this.handleResponse('maybe')}>Maybe</button>
<button onClick={() => this.handleResponse('declined')}>Decline</button>
</div>
: this.state.role === 'declined' ?
<div>
Not Going
<button onClick={() => this.handleResponse('going')}>Accept</button>
<button onClick={() => this.handleResponse('maybe')}>Maybe</button>
</div>
: this.state.role === 'going' ?
<div>
Attending
<button onClick={() => this.handleResponse('maybe')}>Maybe</button>
<button onClick={() => this.handleResponse('declined')}>Decline</button>
</div>
: this.state.role === 'maybe' ?
<div>
Maybe
<button onClick={() => this.handleResponse('going')}>Accept</button>
<button onClick={() => this.handleResponse('declined')}>Decline</button>
</div>
:
<div>Not Invited</div>
}
<br/>
<strong>Attendants</strong>
<AttendantsList attendants={this.state.attendants} history={this.props.history} uninvite={this.handleUninvite} /><br/>
{this.state.role === 'host' ? <FriendsList history={this.props.history} invite={this.handleInvite} /> : null}
<CreatePost
generatePost={this.generatePost}
role={this.state.role}
/> <br />
{this.state.posts.length ?
<Posts
role={this.state.role}
history={this.props.history}
posts={this.state.posts}
user={this.state.user}
event={this.state.event}
config={this.state.config}
/>
: null}
</div>
);
}
}
<file_sep>const mongoose = require('mongoose');
const mongoUri = 'mongodb://localhost/eventay-chat';
mongoose.connect(mongoUri);
const db = mongoose.connection;
db.once('open', () => {
console.log('mongoose connected successfully');
});
db.on('error', () => {
console.log('mongoose connection error');
});
module.exports = mongoose.model('Chat', mongoose.Schema({
message: String,
sender: Object,
receiver: Object,
senderUsername: String,
receiverUsername: String,
date: { type: Date, default: Date.now },
}));
<file_sep>import React from 'react';
import { Avatar, Card, CardHeader, Paper, CardText, TextField, IconButton, Checkbox, Divider } from 'material-ui';
import ActionFavorite from 'material-ui/svg-icons/action/favorite';
import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border';
import Comments from './Comments.jsx'
import axios from 'axios';
class Posts extends React.Component {
constructor(props){
super(props);
this.state = {
commentTextInput: ''
}
this.renderPosts = this.renderPosts.bind(this);
}
renderPosts(postList) {
return (
postList.reverse().map((post) => {
return (
<Card key={post.post.id} style={{ padding: '10px', margin: '10px' }}>
<CardHeader
title={<div
onClick={() => this.props.history.push(`/profile/${post.post.userInfo.username}`)}
><strong>{post.post.userInfo.username}</strong></div>}
avatar={post.post.userInfo.profile_picture}
/>
<CardText style={{ fontSize: '200%', padding: '4px', }}>
{post.post.body}
</CardText>
<Divider />
<Comments
role={this.props.role}
history={this.props.history}
postId={post.post.id}
comments={post.comments}
posts={this.state.posts}
user={this.props.user}
event={this.props.event}
config={this.props.config}
/>
</Card>
)
})
)
}
render() {
return(
<Paper style={{ width: '50%', padding: '1px', }}>
{this.renderPosts(this.props.posts)}
</Paper>
)
}
}
export default Posts;
<file_sep>const router = require('express').Router();
const controller = require('./eventsController.js');
router.get('/:user_id', async (req, res) => {
try {
let data = await controller.getHostingEvents(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.get('/eventinfo/:event_id', async (req, res) => {
try {
let data = await controller.getEventDetails(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
})
router
.route('/')
.post(async (req, res) => {
try {
let eventId = await controller.createEvent(req.body);
res.json(eventId).sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
})
.put(async (req, res) => {
try {
await controller.updateEvent(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
})
.delete(async (req, res) => {
try {
await controller.removeEvent(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
});
module.exports = router;
<file_sep>import initialState from './initialState.js';
import { RECEIVE_PROFILE, FETCH_PROFILE } from '../actions/actionTypes.js';
export default function userInfo(state = initialState.profileInfo, action) {
let newState;
if (action.type === RECEIVE_PROFILE) {
newState = action.profileInfo;
return newState;
} else if (action.type === FETCH_PROFILE) {
return action;
}
return state;
}<file_sep>import React from 'react';
import jwt from 'jsonwebtoken';
export default class Protected extends React.Component {
componentWillMount() {
try {
if (!localStorage.getItem('token')) {
this.props.history.push('/landing');
}
} catch (e) {
this.props.history.push('/landing');
}
}
render() {
const { component: Component } = this.props;
return localStorage.getItem('token') ? <Component {...this.props} /> : <div></div>;
}
}
<file_sep>const router = require('express').Router();
const authRouter = require('./auth/authRouter.js');
const checkAuth = require('./auth/checkAuth.js');
const friendsRouter = require('./components/friends/friendsRouter.js');
const eventsRouter = require('./components/events/eventsRouter.js');
const attendantsRouter = require('./components/attendants/attendantsRouter.js');
const postsRouter = require('./components/posts/postsRouter.js');
const usersRouter = require('./components/users/usersRouter.js');
const scheduleRouter = require('./components/schedule/scheduleRouter.js');
const { getAllFriends } = require('./components/friends/friendsController.js');
const {
getAllAttending,
showUserEvents
} = require('./components/attendants/attendantsController.js');
const { getUserProfile } = require('./components/users/usersController');
const { search } = require('./components/search/searchController.js');
const { select } = require('./queries/select.js');
module.exports = passportObj => {
router.use('/auth', authRouter(passportObj));
router.use('/', checkAuth);
router.all('/test', (req, res) => res.send({ message: 'test' }));
router.get('/search/:user_id/:query', search);
router.use('/post', postsRouter);
router.use('/friend', friendsRouter);
router.use('/user', usersRouter);
router.use('/event', eventsRouter);
router.use('/attendant', attendantsRouter);
router.use('/schedule', scheduleRouter);
router.get('/friends/:user_id', async (req, res) => {
try {
let data = await getAllFriends(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.get('/attendants/:user_id', async (req, res) => {
try {
let data = await getAllAttending(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router.get('/select/:table_name', async (req, res) =>
res.send(await select(req.params.table_name))
);
return router;
};
<file_sep>// reducer for all things related to event data.
// TODO
import initialState from './initialState';
import { FETCH_EVENT, RECEIVE_EVENT } from '../actions/actionTypes.js';
export default event = (state = initialState.event, action) => {
let newState;
if (action.type === FETCH_EVENT) {
return action;
} else if (action.type === RECEIVE_EVENT) {
newState = action.event;
return newState;
}
return state;
};
<file_sep>module.exports = {
API_KEY: '',
API_KEY2: '',
url: 'localhost'
};
<file_sep>var LocalStrategy = require('passport-local').Strategy;
var { User } = require('./models/user.js');
var bCrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
module.exports = passport => {
passport.use(
'login',
new LocalStrategy(
{ session: false, passReqToCallback: true },
(req, username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err);
}
// user doesn't exist
if (!user) {
return done(null, false /*req.flash('message', 'User Not found.')*/);
}
// Wrong password
if (!bCrypt.compareSync(password, user.password)) {
return done(null, false /*req.flash('message', 'Invalid Password')*/);
}
// successful login
// create a token string
const payload = { userId: user._id, username: user.username };
const token = jwt.sign(payload, 'mySecret');
return done(null, user, token);
});
}
)
);
};
<file_sep>import React from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
import { bindActionCreators } from 'redux';
import io from 'socket.io-client';
import {
TextField,
Divider,
Card,
CardHeader,
Avatar,
Paper,
Dialog
} from 'material-ui';
import ReactFilestack, { client } from 'filestack-react';
import RaisedButton from 'material-ui/RaisedButton';
import propTypes from 'prop-types';
import * as profileActions from '../../actions/profileActions';
import * as userInfoActions from '../../actions/userInfoActions';
import EventList from '../misc/eventList.jsx';
import ProfileButtons from '../misc/ProfileButtons.jsx';
import filestack from '../../../config.js';
import NavBar from './NavBar.jsx';
class Profile extends React.Component {
constructor(props) {
super(props);
// persist user info to app state upon hard refresh
const user = JSON.parse(localStorage.getItem('userInfo'));
props.userInfoActions.receiveUserInfo(user);
this.state = {
profileInfo: {},
invalidUser: false,
isFriendPending: false,
isFriend: false,
canAcceptFriendRequest: false,
isSelf: false,
renderUpdateProfile: false,
renderProfilePicPopover: false,
popoverAnchorEl: null,
renderURLInput: false,
urlPopoverAnchorEl: null,
bioInputField: '',
bioDisplay: '',
profilePicURL: '',
events: [],
authHeader: { headers: { Authorization: 'bearer ' + localStorage.token } }
};
this.handleProfileBioModalOpen = this.handleProfileBioModalOpen.bind(this);
this.handleProfileBioModalClose = this.handleProfileBioModalClose.bind(
this
);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleUpdateBio = this.handleUpdateBio.bind(this);
this.handleUpdatePhoto = this.handleUpdatePhoto.bind(this);
this.handleProfilePhotoModalOpen = this.handleProfilePhotoModalOpen.bind(
this
);
this.handleProfilePhotoModalClose = this.handleProfilePhotoModalClose.bind(
this
);
this.handleAddFriend = this.handleAddFriend.bind(this);
this.handleRemoveFriend = this.handleRemoveFriend.bind(this);
this.handleBlockUser = this.handleBlockUser.bind(this);
this.handleAcceptFriendReq = this.handleAcceptFriendReq.bind(this);
this.initiateChat = this.initiateChat.bind(this);
}
componentWillReceiveProps() {
const user = JSON.parse(localStorage.getItem('userInfo'));
// get user info
axios
.get(
`/api/user/${this.props.match.params.username}`,
this.state.authHeader
)
.then(response => {
if (response.status === 200 && response.data) {
this.setState({
profileInfo: response.data,
bioInputField: response.data.bio || '',
bioDisplay: response.data.bio || ''
});
if (
response.data.username === this.props.userInfo.username &&
response.data.id === this.props.userInfo.id
) {
this.getEvents(this.props.userInfo.id);
this.setState({
isSelf: true
});
}
// check if user is a friend
axios
.get(
`/api/friend/check/${user.id}/${response.data.id}`,
this.state.authHeader
)
.then(check => {
if (check.data.length) {
if (check.data[0].status === 'accepted') {
this.getEvents(response.data.id);
this.setState({ isFriend: true, isFriendPending: false });
} else if (check.data[0].status === 'pending') {
if (check.data[0].target_id === user.id) {
this.setState({
isFriend: false,
isFriendPending: true,
canAcceptFriendRequest: true
});
} else {
this.setState({
isFriend: false,
isFriendPending: true,
canAcceptFriendRequest: false
});
}
} else if (check.data[0].status === 'blocked') {
this.setState({ invalidUser: true });
}
}
});
} else {
this.setState({
invalidUser: true
});
}
});
}
handleAddFriend() {
axios
.post(
'/api/friend',
{
user_id: this.props.userInfo.id,
target_id: this.state.profileInfo.id
},
this.state.authHeader
)
.then(response => this.setState({ isFriendPending: true }));
}
handleRemoveFriend() {
const payload = {
data: {
user_id: this.props.userInfo.id,
target_id: this.state.profileInfo.id
},
headers: this.state.authHeader.headers
};
axios
.delete('/api/friend', payload)
.then(response =>
this.setState({ isFriendPending: false, isFriend: false })
);
}
handleAcceptFriendReq() {
axios
.put(
'/api/friend',
{
user_id: this.props.userInfo.id,
target_id: this.state.profileInfo.id,
status: 'accepted'
},
this.state.authHeader
)
.then(response =>
this.setState({
isFriendPending: false,
isFriend: true,
canAcceptFriendRequest: false
})
);
}
handleBlockUser() {
axios.put('/api/friend', {
user_id: this.props.userInfo.id,
target_id: this.state.profileInfo.id,
status: 'blocked',
}, this.state.authHeader)
.then(response => this.setState({ isFriendPending: false, isFriend: false, canAcceptFriendRequest: false, invalidUser: true }));
}
handleProfileBioModalOpen() {
this.setState({
bioInputField: this.state.profileInfo.bio,
renderUpdateProfile: true
});
}
handleProfileBioModalClose() {
this.setState({
renderUpdateProfile: false
});
}
handleProfilePhotoModalOpen() {
this.setState({
renderProfilePicPopover: true
});
}
handleProfilePhotoModalClose() {
this.setState({
renderProfilePicPopover: false
});
}
handleUpdatePhoto(photo) {
const url = photo.filesUploaded[0].url;
// todo update bio info
axios
.put(
`/api/user`,
{
profile_picture: url,
username: this.props.userInfo.username // to prevent user from changing other people's bio
},
this.state.authHeader
)
.then(response => {
const user = Object.assign({}, this.state.profileInfo);
user.profile_picture = response.data.profile_picture;
this.setState({ profileInfo: user });
this.handleProfilePhotoModalClose();
});
}
handleInputChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleUpdateBio(e) {
if (e.key === 'Enter' && this.state.isSelf) {
// todo update bio info
axios
.put(
`/api/user`,
{
bio: this.state.bioInputField,
username: this.props.userInfo.username // to prevent user from changing other people's bio
},
this.state.authHeader
)
.then(response => {
this.setState({ bioDisplay: response.data.bio });
this.handleProfileBioModalClose();
});
}
}
initiateChat() {
this.props.history.push({
pathname: "/chat",
state: this.state.profileInfo,
});
}
getEvents(userId) {
axios
.get(`/api/event/${userId}`, this.state.authHeader)
.then(response => {
if (!this.state.isSelf) {
const pubEvents = response.data.filter(event => event.publicity);
this.setState({ events: pubEvents});
} else {
this.setState({ events: response.data })
}
});
}
render() {
if (!this.state.invalidUser) {
return (
<div>
<NavBar history={this.props.history} />
<Card
style={{
margin: 'auto',
width: '80%',
}}
>
<CardHeader
title={<h1>{this.state.profileInfo.username}</h1>}
subtitle={this.state.bioDisplay}
avatar={
<Avatar
src={this.state.profileInfo.profile_picture}
style={{ objectFit: 'cover' }}
size={200}
/>
}
/>
<Dialog
title="Update your bio"
modal={false}
open={this.state.renderUpdateProfile}
onRequestClose={this.handleProfileBioModalClose}
>
<Paper zDepth={1}>
<TextField
hintText="Bio"
name="bioInputField"
onChange={this.handleInputChange}
onKeyDown={this.handleUpdateBio}
value={this.state.bioInputField}
style={{ marginLeft: 20 }}
underlineShow={false}
/>
<Divider />
</Paper>
</Dialog>
<Dialog
title="Update your photo"
modal={false}
open={this.state.renderProfilePicPopover}
onRequestClose={this.handleProfilePhotoModalClose}
>
<ReactFilestack
apikey={filestack.API_KEY}
buttonText="Upload"
render={({ onPick }) => (
<RaisedButton label="Upload" onClick={onPick} />
)}
onSuccess={this.handleUpdatePhoto}
/>
</Dialog>
<ProfileButtons
history={this.props.history}
isFriendPending={this.state.isFriendPending}
isFriend={this.state.isFriend}
isSelf={this.state.isSelf}
canAcceptFriendRequest={this.state.canAcceptFriendRequest}
handleProfileBioModalOpen={this.handleProfileBioModalOpen}
handleProfilePhotoModalOpen={this.handleProfilePhotoModalOpen}
handleAddFriend={this.handleAddFriend}
handleBlockUser={this.handleBlockUser}
handleRemoveFriend={this.handleRemoveFriend}
handleAcceptFriendReq={this.handleAcceptFriendReq}
initiateChat={this.initiateChat}
/>
{this.state.isSelf || this.state.isFriend ? (
<EventList
isSelf={this.state.isSelf}
isFriend={this.state.isFriend}
events={this.state.events}
history={this.props.history}
/>
) : null}
</Card>
</div>
);
} else {
return (
<div>
<NavBar history={this.props.history} />
The user does not exist or is blocking you from seeing this :(
</div>
);
}
}
}
Profile.propTypes = {};
const mapStateToProps = state => {
return {
userInfo: state.userInfo,
profileInfo: state.profileInfo
};
};
const mapDispatchToProps = dispatch => {
return {
profileActions: bindActionCreators(profileActions, dispatch),
userInfoActions: bindActionCreators(userInfoActions, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
<file_sep>const db = require('../db/db.js');
module.exports = {
select: async (table) => {
let data = await db.queryAsync(`SELECT * FROM ${table};`);
return data.rows;
}
};
<file_sep>import React from 'react'
import { CardActions, FlatButton, Toggle } from 'material-ui';
class ProfileButtons extends React.Component {
constructor(props) {
super(props)
this.renderButtons = this.renderButtons.bind(this);
}
renderButtons() {
if (this.props.isSelf) {
return (
<span>
<FlatButton label="Update Bio" onClick={this.props.handleProfileBioModalOpen} />
<FlatButton label="Update Photo" onClick={this.props.handleProfilePhotoModalOpen} />
<FlatButton label="Create Event" onClick={() => this.props.history.push('/create')} />
</span>
);
} else if (this.props.isFriend) {
return (
<span>
<FlatButton label="Remove Friend" onClick={this.props.handleRemoveFriend} />
<FlatButton label="Send Message" onClick={this.props.initiateChat} />
<FlatButton label="Invite" onClick={() => console.log('Invite clicked')} />
<FlatButton label="Block" onClick={this.props.handleBlockUser} />
</span>
);
} else {
return (
<span>
<FlatButton
label={this.props.isFriendPending ?
(this.props.canAcceptFriendRequest ?
"Accept request" :
"Cancel request" ) :
"Add Friend"}
onClick={this.props.isFriendPending ?
(this.props.canAcceptFriendRequest ?
this.props.handleAcceptFriendReq :
this.props.handleRemoveFriend) :
this.props.handleAddFriend}
/>
<FlatButton label="Block" onClick={this.props.handleBlockUser} />
</span>
)
}
}
render() {
return(
<CardActions>
{this.renderButtons()}
</CardActions>
)
}
}
export default ProfileButtons;<file_sep>import React, { Component } from 'react';
import SearchBar from 'material-ui-search-bar';
import axios from 'axios';
import Dialog from 'material-ui/Dialog';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import Avatar from 'material-ui/Avatar';
export default class Search extends Component {
constructor(props) {
super(props);
this.state = {
config: {},
query: '',
searchFriends: [],
searchEvents: [],
open: false,
};
this.handleSearchInput = this.handleSearchInput.bind(this);
this.handleSearchRequest = this.handleSearchRequest.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleSearchInput(e) {
this.setState({ query: e });
}
componentWillMount() {
const config = {
headers: { Authorization: 'bearer ' + localStorage.token}
};
this.setState( {config: config} );
}
handleSearchRequest() {
axios
.get(`/api/search/${this.props.userInfo.id}/${this.state.query}`, this.state.config)
.then(result => {
var obj = {};
this.setState({
searchFriends: result.data.friends,
searchEvents: result.data.events,
open: true,
});
})
.catch(err => {
console.log(`OOPS LOOKS LIKE SEARCH FAILED: ${err}`);
});
}
handleClose () {
this.setState({open: false});
}
renderSearchResults () {
let content = [];
let counter = 0;
if ( !(this.state.searchEvents.length) && !(this.state.searchFriends.length) ) {
return (<p>Sorry, no search results found.</p>)
}
if (this.state.searchEvents.length) {
content.push(<h3 key='events'>Events</h3>);
content.push(
<List key='events-list'>
{
this.state.searchEvents.map( (data, i) => {
counter++;
return (
<ListItem
key={counter}
disabled={true}
leftAvatar={
<Avatar src={data.thumbnail} />
}
>
<a
href={`/event/${data.id}`}
style={ {
textDecoration: 'none',
color: '#000000'
} }
>
{data.title}
</a>
</ListItem>
);
})
}
</List>
)
}
if (this.state.searchFriends.length) {
content.push(<h3 key='friends'>Friends</h3>);
content.push(
<List key='friends-list'>
{
this.state.searchFriends.map( (data, i) => {
counter++;
return (
<ListItem
key={counter}
disabled={true}
leftAvatar={
<Avatar src={data.profile_picture} />
}
>
<a
href={`/profile/${data.username}`}
style={ {
textDecoration: 'none',
color: '#000000'
} }
>
{data.username}
</a>
</ListItem>
)
})
}
</List>
)
}
return content;
}
render() {
return (
<div
style={{
float: 'none',
maxWidth: 800,
marginRight: 'auto',
marginLeft: 'auto',
marginTop: 'auto',
marginBottom: 'auto'
}}
>
<SearchBar
onChange={e => this.handleSearchInput(e)}
onRequestSearch={this.handleSearchRequest}
/>
<Dialog
title='Results'
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
{this.renderSearchResults()}
</Dialog>
</div>
);
}
}
<file_sep>const router = require('express').Router();
const controller = require('./postsController.js');
router.get('/:event_id', async (req, res) => {
try {
let data = await controller.getEventPosts(req.params);
res.send(data);
} catch (err) {
res.sendStatus(500);
}
});
router
.route('/')
.post(async (req, res) => {
try {
const data = await controller.createPost(req.body);
res.send(data.rows);
} catch (err) {
console.error('createPost error: ', err.cause);
res.sendStatus(500);
}
})
.put(async (req, res) => {
try {
await controller.updatePost(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
})
.delete(async (req, res) => {
try {
await controller.removePost(req.body);
res.sendStatus(200);
} catch (err) {
res.sendStatus(500);
}
});
module.exports = router;
<file_sep>import * as actionTypes from './actionTypes.js';
import axios from 'axios';
export const receiveEvent = (data) => ({ type: actionTypes.RECEIVE_EVENT, event: data });
export const fetchEvent = () => (
async (dispatch) => {
let response = axios.get('https://jsonplaceholder.typicode.com/todos')
if (response.status === 200) {
dispatch(receiveEvent(response.data)) // equivalent to setState({ event: response.data }) if not using redux
} else {
const flash = {
type: 'error',
title: 'error getting list',
content: 'There was an error getting the event list. Please try again.',
}
dispatch({
type: 'DISPLAY_FLASH',
data: flash,
});
}
}
);
<file_sep>const utils = require('../utils/utils.js');
describe('Utility functions', () => {
test('convertTime properly converts date string to am/pm format', () => {
expect(utils.convertTime('2018-04-09 12:38:02')).toBe(
'Mon Apr 09, 2018 12:38 pm'
);
expect(utils.convertTime('2018-04-09 00:00:00')).toBe(
'Mon Apr 09, 2018 12:00 am'
);
});
test('conflictExists properly determines whether two time ranges conflict', () => {
let time1 = [
Date.parse('2018-04-01 00:00:00'),
Date.parse('2018-04-05 00:00:00')
];
let time2 = [
Date.parse('2018-04-04 00:00:00'),
Date.parse('2018-04-06 00:00:00')
];
let time3 = [
Date.parse('2018-04-06 00:00:00'),
Date.parse('2018-04-10 00:00:00')
];
expect(utils.conflictExists(time1[0], time1[1], time2[0], time2[1])).toBe(
true
);
expect(utils.conflictExists(time1[0], time1[1], time3[0], time3[1])).toBe(
false
);
expect(utils.conflictExists(time2[0], time2[1], time3[0], time3[1])).toBe(
false
);
});
test('includesWeekend properly determines whether given time range conflicts with the weekend', () => {
let time1 = [
Date.parse('2018-04-01 00:00:00'),
Date.parse('2018-04-05 00:00:00')
];
let time2 = [
Date.parse('2018-04-04 00:00:00'),
Date.parse('2018-04-06 00:00:00')
];
expect(utils.includesWeekend(time1[0], time1[1])).toBe(true);
expect(utils.includesWeekend(time2[0], time2[1])).toBe(false);
});
test('isOvernight properly determines whether given time range conflicts with overnight times (11p-6a)', () => {
let time1 = [
Date.parse('2018-04-01 16:00:00'),
Date.parse('2018-04-02 00:00:00')
];
let time2 = [
Date.parse('2018-04-01 09:00:00'),
Date.parse('2018-04-01 15:00:00')
];
expect(utils.isOvernight(time1[0], time1[1])).toBe(true);
expect(utils.isOvernight(time2[0], time2[1])).toBe(false);
});
test('isDuringWorkday properly determines whether given time range overlaps with weekday hours', () => {
let time1 = [
Date.parse('2018-04-01 00:00:00'),
Date.parse('2018-04-01 09:00:00')
];
let time2 = [
Date.parse('2018-04-01 08:00:00'),
Date.parse('2018-04-01 14:00:00')
];
let time3 = [
Date.parse('2018-04-01 17:00:00'),
Date.parse('2018-04-02 08:00:00')
];
expect(utils.isDuringWorkday(time1[0], time1[1])).toBe(false);
expect(utils.isDuringWorkday(time2[0], time2[1])).toBe(true);
expect(utils.isDuringWorkday(time3[0], time3[1])).toBe(false);
});
test('millisecondsUntilMidnight correctly returns number of milliseconds until midnight', () => {
let date1 = new Date('2018-04-01 16:30:00');
let date2 = new Date('2018-04-01 23:25:00');
expect(utils.millisecondsUntilMidnight(date1)).toBe(27000000);
expect(utils.millisecondsUntilMidnight(date2)).toBe(2100000);
});
});
<file_sep>const request = require('supertest');
const setup = require('../server/db/index.js');
const { authDB } = require('../server/auth/db.js');
const { app } = require('../server/index.js');
beforeAll(async () => {
await setup();
});
describe('Initialization', () => {
test('Successfully issue GET request to /', async () => {
const res = await request(app).get('/');
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toEqual(
expect.stringContaining('text/html')
);
});
test('Render home page for unknown route', async () => {
const res = await request(app).get('/unknownPage');
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toEqual('text/html; charset=UTF-8');
const expectedContentLength = '448';
expect(res.headers['content-length']).toEqual(expectedContentLength);
});
});
<file_sep>const db = require('../../db/db.js');
module.exports = {
createPost: async ({ body, user_id, event_id, parent_id }) => {
try {
const data = await db.queryAsync(`
INSERT INTO posts (body, user_id, event_id, parent_id)
SELECT '${body}', ${user_id}, ${event_id}, ${parent_id ? `'${parent_id}'` : null}
WHERE EXISTS (
SELECT user_id FROM attendants
WHERE user_id=${user_id} AND event_id=${event_id}
) RETURNING *
`);
console.log('data', data.rows);
return data;
} catch (err) {
throw err;
}
},
getEventPosts: async ({ event_id }) => {
try {
const data = await db.queryAsync(`
SELECT * FROM posts
WHERE event_id=${event_id}
`);
return data.rows;
} catch (err) {
throw err;
}
},
updatePost: async ({ id, body, user_id, event_id }) => {
try {
await db.queryAsync(`
UPDATE posts
SET body='${body}'
WHERE id=${id} AND user_id=${user_id} AND event_id=${event_id}
`);
} catch (err) {
throw err;
}
},
removePost: async ({ id, user_id, event_id }) => {
try {
await db.queryAsync(`
DELETE FROM posts
WHERE id=${id} AND user_id=${user_id} AND event_id=${event_id}
`);
} catch (err) {
throw err;
}
}
};
<file_sep>const sql = require('./sql.js');
const User = require('../auth/models/user.js');
const mongoose = require('mongoose');
let config;
try {
config = require('../config.js');
} catch (err) {
config = require('../config.example.js');
}
const setup = async () => {
mongoose.connect(
`${
config.rdb.environment === 'test'
? config.auth.uri_testing
: config.auth.uri_dev
}`,
() => {
mongoose.connection.db.dropDatabase();
console.log(
`Dropped mongoDB database: ${
config.rdb.environment === 'test'
? config.auth.uri_testing
: config.auth.uri_dev
}`
);
}
);
await sql.drop('table', 'reactions');
await sql.drop('table', 'emojis');
await sql.drop('table', 'likes');
await sql.drop('table', 'posts');
await sql.drop('table', 'attendants');
await sql.drop('table', 'friends');
await sql.drop('table', 'events');
await sql.drop('table', 'users');
await sql.drop(
'database',
config.rdb.environment === 'test'
? config.rdb.name_testing
: config.rdb.name_dev
);
await sql.createDatabase();
await sql.createUsersTable();
await sql.createEventsTable();
await sql.createFriendsTable();
await sql.createAttendantsTable();
await sql.createPostsTable();
await sql.createLikesTable();
await sql.createEmojisTable();
await sql.createReactionsTable();
};
module.exports = setup;
<file_sep>import React, { Component } from 'react';
import Attendant from './Attendant.jsx';
import { List } from 'material-ui';
export default class AttendantsList extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<List style={{ maxHeight: '10em', overflow: 'scroll', width: '20%', border: '1px solid #d3d3d3'}}>
{this.props.attendants.map((attendant, key) => <Attendant attendant={attendant} key={key} id={key} uninvite={this.props.uninvite} />)}
</List>
</div>
);
}
}<file_sep>import React, { Component } from 'react';
import AppBar from 'material-ui/AppBar';
import Popover from 'material-ui/Popover';
import NavMenu from './NavMenu.jsx';
import Badge from 'material-ui/Badge';
import IconButton from 'material-ui/IconButton';
import NotificationsIcon from 'material-ui/svg-icons/social/notifications';
import Search from './Search.jsx';
import axios from 'axios';
import Dialog from 'material-ui/Dialog';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import Avatar from 'material-ui/Avatar';
import FlatButton from 'material-ui/FlatButton';
export default class NavBar extends Component {
constructor(props) {
super(props);
this.state = {
config: { headers: { Authorization: 'bearer ' + localStorage.token } },
open: false,
pendingFriends: [],
pendingInvites: [],
userInfo: {},
openNotifs: false,
};
this.handleClick = this.handleClick.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleNotifsClose = this.handleNotifsClose.bind(this);
this.handleNotifsOpen = this.handleNotifsOpen.bind(this);
this.handleNotifInvite = this.handleNotifInvite.bind(this);
}
handleClick(e) {
e.preventDefault();
this.setState({ open: true, anchorEl: e.currentTarget });
}
handleRequestClose() {
this.setState({ open: false });
}
componentWillMount() {
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
userInfo
? (this.setState({ userInfo: userInfo }),
axios.get(`/api/friend/${userInfo.id}`, this.state.config).then(result => {
this.setState({ pendingFriends: result.data });
}),
axios
.get(`/api/attendant/pendingInvites/${userInfo.id}`, this.state.config)
.then(result => {
this.setState({ pendingInvites: result.data });
}))
: null;
}
handleNotifsClose () {
this.setState( {openNotifs: false} );
}
handleNotifsOpen () {
this.setState( {openNotifs: true} );
}
cleanupNotifs (elem, notification) {
this.state[notification].forEach((obj, i) => {
if (obj.id === elem) {
var some = this.state[notification].slice();
some.splice(i, 1);
this.setState({[notification]: some})
}
})
}
renderNotifs () {
let content = [];
let counter = 0;
if (!(this.state.pendingFriends.length) && !(this.state.pendingInvites)) {
return (<p>You're all caught up! Great!</p>);
}
if (this.state.pendingFriends.length) {
content.push(<h3 key='friend-notifs'>Friend Invites</h3>);
content.push(
<List key='friend-notifs-list'>
{
this.state.pendingFriends.map((notif, i) => {
counter++;
return (
<ListItem
id={counter}
key={counter}
disabled={true}
leftAvatar={
<Avatar src={notif.profile_picture} />
}
>
<a
key={counter}
href={`/profile/${notif.username}`}
style={ {
textDecoration: 'none',
color: '#000000'
} }
>
{notif.username}
</a>
<div
style={ {float: 'right'} }
>
<FlatButton
value={notif.username}
label="Accept"
onClick={ () =>
this.handleNotifInvite(
'friend',
'accept',
{user_id: `${this.state.userInfo.id}`,
target_id: `${notif.id}`,
status: 'accepted'},
notif.id
)
}
/>
<FlatButton
value={notif.username}
label="Deny"
onClick={ () =>
this.handleNotifInvite(
'friend',
'deny',
{user_id: `${notif.id}`,
target_id: `${this.state.userInfo.id}`},
notif.id
)}
/>
</div>
</ListItem>
);
})
}
</List>
);
}
if (this.state.pendingInvites.length) {
content.push(<h3 key='event-notifs'>Event Invites</h3>);
content.push(
<List key='event-notifs-list'>
{
this.state.pendingInvites.map((notif, i) => {
counter++;
return (
<ListItem
key={counter}
disabled={true}
leftAvatar={
<Avatar src={notif.thumbnail} />
}
>
<a
key={counter}
href={`/event/${notif.id}`}
style={ {
textDecoration: 'none',
color: '#000000'
} }
>
{notif.title}
</a>
<div
style={ {float: 'right'} }
>
<FlatButton
value={notif.title}
label="Accept"
onClick={ () =>
this.handleNotifInvite(
'event',
'accept',
{
user_id: `${this.state.userInfo.id}`,
event_id: `${notif.id}`,
status: 'going'
},
notif.id
)
}
/>
<FlatButton
value={notif.title}
label="Maybe"
onClick={() =>
this.handleNotifInvite(
'event',
'maybe',
{
user_id: `${this.state.userInfo.id}`,
event_id: `${notif.id}`,
status: 'maybe'
}
)
}
/>
<FlatButton
value={notif.title}
label="Decline"
onClick={() =>
this.handleNotifInvite(
'event',
'deny',
{
user_id: `${this.state.userInfo.id}`,
event_id: `${notif.id}`
},
notif.id
)
}
/>
</div>
</ListItem>
)
}
)
}
</List>
);
}
return content;
}
handleNotifInvite (inviteType, decision, content, elem) {
if (inviteType === 'friend') {
if (decision === 'accept') {
axios.put(`/api/friend/`, content, this.state.config)
.then(result => {
this.cleanupNotifs(elem, 'pendingFriends');
})
.catch(err => {throw err});
} else if (decision === 'deny') {
const payload = {
data: content,
headers: this.state.config.headers,
}
axios.delete(`/api/friend/`, payload)
.then(result => {
this.cleanupNotifs(elem, 'pendingFriends');
});
}
} else if (inviteType === 'event') {
axios.put('/api/attendant', content, this.state.config)
.then(() => console.log('Success'))
.catch((err) => console.error('Error'));
}
}
render() {
return (
<div id="nav-bar">
<AppBar
style={{
backgroundImage: 'linear-gradient(-20deg, #00cdac 0%, #8ddad5 100%)',
}}
title={
<span
style={{
fontFamily: 'Stalemate, cursive',
fontSize: '2.7em',
marginLeft: '20%',
}}
onClick={
() => this.props.history.push('/')}
>Eventé</span>
}
onLeftIconButtonClick={this.handleClick}
>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
targetOrigin={{ horizontal: 'left', vertical: 'top' }}
onRequestClose={this.handleRequestClose}
>
<NavMenu history={this.props.history} />
</Popover>
<Search history={this.props.history} userInfo={this.state.userInfo} />
<div
id="notifications"
onClick={this.handleNotifsOpen}
>
<IconButton
style={{
marginRight: '-10px',
marginTop: '10px',
}}
tooltip="Notifications">
<NotificationsIcon />
</IconButton>
{
(this.state.pendingFriends.length +
this.state.pendingInvites.length) > 0 ?
(<Badge
badgeContent={
this.state.pendingFriends.length +
this.state.pendingInvites.length
}
secondary={true}
badgeStyle={{ top: 12, right: 12 }}
>
</Badge>)
: null
}
</div>
<Dialog
title='Notifications'
modal={false}
open={this.state.openNotifs}
onRequestClose={this.handleNotifsClose}
>
{this.renderNotifs()}
</Dialog>
</AppBar>
</div>
);
}
}
<file_sep>const { app } = require('./index.js');
const port = 1337;
app.listen(port, () => {
console.log('Listening in port', port);
});
<file_sep>import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as userInfoActions from '../../actions/userInfoActions';
import PropTypes from 'prop-types';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = { username: '', password: '' };
this.handleSignupClick = this.handleSignupClick.bind(this);
this.handleSubmitClick = this.handleSubmitClick.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleSubmitClick() {
axios
.post('/api/auth/login', {
username: this.state.username,
password: <PASSWORD>
})
.then(res => {
// store res.data.userInfo into application state
this.props.userInfoActions.receiveUserInfo(res.data.userInfo);
// store res.data.token to local storage
localStorage.setItem('token', res.data.token);
// janky solution to persisting user info upon refresh. Find a better way
localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo));
this.props.history.push('/');
})
.catch(error => {
console.error(error);
});
}
handleSignupClick() {
this.props.history.push('/signup');
}
handleInputChange(e) {
const { value, name } = e.target;
this.setState({ [name]: value });
}
render() {
return (
<div
style={{
width: '100%',
}}
>
<div
style={{
float: 'none',
maxWidth: '40%',
marginLeft: 'auto',
marginRight: 'auto',
}}
>
<Paper
style={{
height: '100%',
width: '100%',
padding: '15%',
margin: 20,
textAlign: 'center',
display: 'inline-block',
}}
zDepth={3}
>
<h1 style={{
fontFamily: 'Stalemate, cursive',
fontSize: '4em'
}}
>Eventé Login</h1>
<br />
<TextField
type="text"
inputStyle={{WebkitBoxShadow: '0 0 0 1000px white inset'}}
name="username"
floatingLabelText="username"
onChange={this.handleInputChange}
/>
<br />
<TextField
type="password"
inputStyle={{WebkitBoxShadow: '0 0 0 1000px white inset'}}
name="password"
floatingLabelText="<PASSWORD>"
onChange={this.handleInputChange}
/>
<br />
<RaisedButton
label="Login"
primary={true}
style={{margin: 12}}
onClick={this.handleSubmitClick}
/>
<RaisedButton
label="New Account"
style={{margin: 12}}
onClick={this.handleSignupClick}
/>
</Paper>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
userInfo: state.userInfo
};
};
const mapDispatchToProps = dispatch => {
return {
userInfoActions: bindActionCreators(userInfoActions, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);
<file_sep>module.exports = {
rdb: {
environment: 'test',
user: 'root',
host: 'localhost',
name_dev: 'eventayRDB',
name_testing: 'testingEventayRDB',
password: '',
port: 5432
},
auth: {
uri_dev: 'mongodb://localhost/eventay',
uri_testing: 'mongodb://localhost/eventayTesting'
}
};
<file_sep>const request = require('supertest');
const setup = require('../server/db/index.js');
const { app } = require('../server/index.js');
beforeAll(async () => {
await setup();
});
describe('Authentication', () => {
test('Successfully create user on signup', async () => {
const res = await request(app)
.post('/api/auth/signup')
.send({
username: 'testuser1',
password: 'pw1'
});
expect(res.statusCode).toBe(200);
});
test('Creating duplicate user triggers error', async () => {
const res = await request(app)
.post('/api/auth/signup')
.send({
username: 'testuser1',
password: 'pw1'
});
expect(res.statusCode).toBe(401);
});
test('Successfully return user upon login', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({
username: 'testuser1',
password: 'pw1'
});
expect(res.body.userInfo.username).toBe('testuser1');
});
test('Entering nonexistent user triggers error', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({
username: 'nonExistentUser',
password: ''
});
expect(res.statusCode).toBe(401);
});
test('Entering incorrect password triggers error', async () => {
const res = await request(app)
.post('/api/auth/login')
.send({
username: 'testuser1',
password: '<PASSWORD>'
});
expect(res.statusCode).toBe(401);
});
test('Accessing protected route without token is unsuccessful', async () => {
const res = await request(app).get('/api/friends/1');
expect(res.statusCode).toBe(401);
});
test('Post to /api/auth/logout successfully logs out user', async () => {
const res = await request(app).post('/api/auth/logout');
expect(res.statusCode).toBe(200);
});
});
| 022a7ac74eb0cc2c7af23644559d296bf4e2b7a8 | [
"JavaScript",
"SQL",
"Markdown"
] | 57 | JavaScript | hirosato223/eventay | 1e9b696249b0fe67092840e5725feeb60e986aa6 | 68eb7e6635e73c278a1ef024344f9aeedf6d28f9 |
refs/heads/master | <repo_name>Av1nashKumar/Movie_API<file_sep>/script.js
let title;
let year;
let plot;
let myUrl;
let verifyCheckStatus;
// $('#loader').hide();
$(document).ready(()=>{
$('#submit').click(function(){
verify();
if(verifyCheckStatus == true){
getAllDetails();
}
});
});
let verify = () => {
title = $('#title').val();
if(title == null || title == "" || title == undefined) {
// no title
alert('No Title');
verifyCheckStatus = false;
} else {
year = $('#year').val();
plot = $('#plot').val();
if(year == null || year == "" || year.length > 4 || year == undefined) {
myUrl = '&t=' + title + '&plot='+ plot + '&r=json';
} else {
myUrl = '&t=' + title + '&y=' + year + '&plot=' + plot + '&r=json';
}
verifyCheckStatus = true;
myUrl = 'https://www.omdbapi.com/?apikey=df12b502' + myUrl;
}
}
/*Fetching input from searchbar ends*/
let getAllDetails = () => {
// To get response
$.ajax({
type:"GET",
url:myUrl,
success: (response) => {
console.log(response);
$('#gallery_card1').html(`
<div class="card card-3">
<img class="my-card-img img-fluid " src="${response.Poster}" alt="Card image cap" >
<div class="card-body">
<h5 class="card-title">${response.Title}</h5>
<p class="card-text">${response.Plot}</p>
<p class="card-text"><small class="text-muted">Rating ${response.imdbRating} </small></p>
</div>
</div>`)
},
timeout:10000,
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
},
beforeSend: () => {
$('#loader').show();
},
complete : () => {
$('#loader').hide();
}
});
}
| b71a0328406b68d865d878c9bfae47958aa94862 | [
"JavaScript"
] | 1 | JavaScript | Av1nashKumar/Movie_API | 6b28ed19c7e2a7d6016601ebf9e1babe4d5de473 | d5ed087de104427bc2b25a1046046ccaeeed260d |
refs/heads/master | <file_sep>
const path = require('path');
const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const port = 8080;
module.exports = {
entry: {
main: './src/index.js',
},
mode: 'development',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, '../dist'),
// publicPath: '/',
},
devServer: {
port,
contentBase: 'dist',
// overlay: true,
},
module: {
rules: [
{ // eslint
test: /\.js$/,
exclude: /node_modules/,
include: /src/,
loader: 'eslint-loader',
enforce: 'pre',
},
{ // babel
test: /\.js$/,
use: [
{
loader: 'babel-loader',
},
],
exclude: /node_modules/,
},
{ // sass
test: /\.(s?[ac]ss|css)$/,
use: [
{
// loader: 'style-loader',
loader: MiniCSSExtractPlugin.loader,
// options: {
// publicPath: '/',
// },
},
{ loader: 'css-loader' },
{ loader: 'sass-loader' },
],
},
{
test: /\.html$/,
use: [
// {
// loader: 'file-loader',
// options: {
// name: '[name].html',
// },
// },
// {
// loader: 'extract-loader',
// },
{
loader: 'html-loader',
options: {
attrs: ['img:src'],
},
},
],
},
{
test: /\.(jpg|jpeg|png|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[name].[ext]',
},
},
],
},
],
},
plugins: [
new MiniCSSExtractPlugin({
filename: '[name].css',
}),
],
};
<file_sep>const helloLayout = require('./hello.html');
const routes = function routes($stateProvider) {
$stateProvider.state('hello', {
url: '/hello',
template: helloLayout,
controller: 'HelloController',
controllerAs: 'hello',
});
};
routes.$inject = ['$stateProvider'];
export default routes;
<file_sep>import angular from 'angular';
import router from 'angular-ui-router';
import routing from './hello.routes';
import HelloController from './hello.controller';
export default angular.module('app.hello', [router])
.config(routing)
.controller('HelloController', HelloController)
.name;
<file_sep>const HomeController = function HomeController($scope) {
$scope.name = 'World';
};
HomeController.$inject = ['$scope'];
export default HomeController;
<file_sep>const homeLayout = require('./home.html');
const routes = function routes($stateProvider) {
$stateProvider.state('home', {
url: '/',
template: homeLayout,
controller: 'HomeController',
controllerAs: 'home',
});
};
routes.$inject = ['$stateProvider'];
export default routes;
<file_sep>import angular from 'angular';
// import router from 'angular-ui-router';
import routing from './user.routes';
import LoginController from './login/login.controller';
import SignupController from './signup/signup.controller';
export default angular.module('app.user', [])
.config(routing)
.controller('LoginController', LoginController)
.controller('SignupController', SignupController)
.name;
<file_sep>const userLayout = require('./user.layout.html');
const loginLayout = require('./login/login.html');
const signupLayout = require('./signup/signup.html');
const routes = function routes($stateProvider) {
$stateProvider.state('user', {
url: '/user',
title: 'User',
abstract: true,
template: userLayout,
}).state('user.login', {
url: '/login',
title: 'Login',
template: loginLayout,
controller: 'LoginController',
}).state('user.signup', {
url: '/signup',
title: 'Signup',
template: signupLayout,
controller: 'SignupController',
});
};
routes.$inject = ['$stateProvider'];
export default routes;
<file_sep>AngularJS boilerplate
TODO
* css processor (sass/styl)
* uib-bootstrap
* material design/layout template
* screen loader
* session control/authentication
* unit test (jest)
Often used packages
* alert
* ng-table
* google maps
* translate
* jquery
<file_sep>// const SignupController = function SignupController($scope) {
const SignupController = function SignupController() {
// console.log('signup');
};
SignupController.$inject = ['$scope'];
export default SignupController;
<file_sep>
// dependencies
import angular from 'angular';
import router from 'angular-ui-router';
import animate from 'angular-animate';
import aria from 'angular-aria';
import messages from 'angular-messages';
import material from 'angular-material';
// modules
import home from './module/home';
import user from './module/user';
import hello from './module/hello';
// styles
import './styles/main.scss';
angular
.module('app', [
router,
animate,
aria,
messages,
material,
home,
user,
hello,
])
.config([
'$urlRouterProvider',
'$locationProvider',
function appConfig($urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
});
$urlRouterProvider.otherwise('/404');
},
]);
<file_sep>const HelloController = function HelloController($scope) {
$scope.name = 'World';
};
HelloController.$inject = ['$scope'];
export default HelloController;
| 7476c9174db1d434e55dab6ddbc7bcc0a19adbfc | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | tchesa/angular-boilerplate | 58fb8ffdfac85dab539b4581ea866c4dbc86e297 | 2b9c7e2e236e07688a2cf3246a6543a14e0eafe1 |
refs/heads/master | <repo_name>HamzaAyub/songs-backend<file_sep>/public/featured_category.php
<?php
include_once('includes/connect_database.php');
include_once('functions.php');
?>
<div id="content" class="container col-md-12">
<?php
$sql_query = "SELECT cid, category_name
FROM tbl_category
ORDER BY cid ASC";
$stmt_category = $connect->stmt_init();
if($stmt_category->prepare($sql_query)) {
// Execute query
$stmt_category->execute();
// store result
$stmt_category->store_result();
$stmt_category->bind_result($category_data['cid'],
$category_data['category_name']
);
}
$stmt_category2 = $connect->stmt_init();
if($stmt_category2->prepare($sql_query)) {
// Execute query
$stmt_category2->execute();
// store result
$stmt_category2->store_result();
$stmt_category2->bind_result($category_data['cid'],
$category_data['category_name']
);
}
$stmt_category3 = $connect->stmt_init();
if($stmt_category3->prepare($sql_query)) {
// Execute query
$stmt_category3->execute();
// store result
$stmt_category3->store_result();
$stmt_category3->bind_result($category_data['cid'],
$category_data['category_name']
);
}
$stmt_category4 = $connect->stmt_init();
if($stmt_category4->prepare($sql_query)) {
// Execute query
$stmt_category4->execute();
// store result
$stmt_category4->store_result();
$stmt_category4->bind_result($category_data['cid'],
$category_data['category_name']
);
}
if(isset($_GET['id'])){
$ID = $_GET['id'];
}else{
$ID = 1;
}
// create array variable to store category data
//$category_data = array();
if(isset($_POST['btnEdit'])){
$cat_id = $_POST['cat_id'];
$cat_id_2 = $_POST['cat_id_2'];
$cat_id_3 = $_POST['cat_id_3'];
$cat_id_4 = $_POST['cat_id_4'];
// get image info
// common image file extensions
$sql_query = "UPDATE featured_category
SET cat_id = ? ,cat_id_2 = ?, cat_id_3 = ? , cat_id_4 = ?
WHERE fid = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sssss',
$cat_id,
$cat_id_2,
$cat_id_3,
$cat_id_4,
$ID);
// Execute query
$stmt->execute();
$update_result = $stmt->store_result();
$stmt->close();
}
// check update result
if($update_result){
$error['update_category'] = " <h4><div class='alert alert-success'>
* Category success updated.
<a href='featured_category.php'>
<i class='fa fa-check fa-lg'></i>
</a></div>
</h4>";
}else{
$error['update_category'] = " <span class='label label-danger'>Failed to update category.</span>";
}
}
// create array variable to store previous data
$data = array();
$sql_query = "SELECT *
FROM featured_category
WHERE fid = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($data['fid'],
$data['cat_id'],
$data['cat_id_2'],
$data['cat_id_3'],
$data['cat_id_4']
);
$stmt->fetch();
$stmt->close();
}
if(isset($_POST['btnCancel'])){
header("location: featured_category.php");
}
?>
<div class="col-md-12">
<h1>Edit Featured Category</h1>
<?php echo isset($error['update_category']) ? $error['update_category'] : '';?>
<hr />
</div>
<div class="col-md-5">
<form method="post"
enctype="multipart/form-data">
<label>Featured Category 1 :</label>
<select name="cat_id" class="form-control">
<?php while($stmt_category->fetch()){
if($category_data['cid'] == $data['cat_id']){?>
<option value="<?php echo $category_data['cid']; ?>" selected ><?php echo $category_data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $category_data['cid']; ?>" ><?php echo $category_data['category_name']; ?></option>
<?php }} ?>
</select>
<br/>
<label>Featured Category 2 :</label>
<select name="cat_id_2" class="form-control">
<?php while($stmt_category2->fetch()){
if($category_data['cid'] == $data['cat_id_2']){?>
<option value="<?php echo $category_data['cid']; ?>" selected ><?php echo $category_data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $category_data['cid']; ?>" ><?php echo $category_data['category_name']; ?></option>
<?php }} ?>
</select>
<br/><br/>
<label>Featured Category 3 :</label>
<select name="cat_id_3" class="form-control">
<?php while($stmt_category3->fetch()){
if($category_data['cid'] == $data['cat_id_3']){?>
<option value="<?php echo $category_data['cid']; ?>" selected ><?php echo $category_data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $category_data['cid']; ?>" ><?php echo $category_data['category_name']; ?></option>
<?php }} ?>
</select>
<br/>
<label>Featured Category 4 :</label>
<select name="cat_id_4" class="form-control">
<?php while($stmt_category4->fetch()){
if($category_data['cid'] == $data['cat_id_4']){?>
<option value="<?php echo $category_data['cid']; ?>" selected ><?php echo $category_data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $category_data['cid']; ?>" ><?php echo $category_data['category_name']; ?></option>
<?php }} ?>
</select>
<br/>
<input type="submit" class="btn-primary btn" value="Update" name="btnEdit"/>
<input type="submit" class="btn-danger btn" value="Cancel" name="btnCancel"/>
</form>
</div>
<div class="separator"> </div>
</div>
<?php include_once('includes/close_database.php'); ?>
<file_sep>/public/video-youtube-data-edit.php
<?php
include_once('includes/connect_database.php');
include_once('functions.php');
require_once("thumbnail_images.class.php");
?>
<div id="content" class="container col-md-12">
<?php
if(isset($_GET['id'])){
$ID = $_GET['id'];
}else{
$ID = "";
}
// create array variable to store category data
$category_data = array();
$sql_query = "SELECT cid, category_name
FROM tbl_category
ORDER BY cid ASC";
$stmt_category = $connect->stmt_init();
if($stmt_category->prepare($sql_query)) {
// Execute query
$stmt_category->execute();
// store result
$stmt_category->store_result();
$stmt_category->bind_result($category_data['cid'],
$category_data['category_name']
);
}
$sql_query = "SELECT video_thumbnail FROM tbl_gallery WHERE id = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($previous_video_thumbnail);
$stmt->fetch();
$stmt->close();
}
if(isset($_POST['btnEdit'])){
$video_title = $_POST['video_title'];
$cid = $_POST['cid'];
$video_duration = $_POST['video_duration'];
$video_url = $_POST['video_url'];
$video_id = $_POST['video_id'];
$video_description = $_POST['video_description'];
$video_type = $_POST['video_type'];
$viewdate = $_POST['viewdate'];
// create array variable to handle error
$error = array();
if(empty($video_title)){
$error['video_title'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if(empty($cid)){
$error['cid'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if(empty($video_duration)){
$error['video_duration'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if(empty($video_description)){
$error['video_description'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
// common image file extensions
$allowedExts = array("gif", "jpeg", "jpg", "png");
if( !empty($video_title) &&
!empty($cid) &&
!empty($video_duration) &&
!empty($video_description)){
// updating all data except image file
$sql_query = "UPDATE tbl_gallery
SET video_title = ? , cat_id = ?,
video_duration = ?, video_url = ?, video_id = ?, video_description = ? , viewdate = ?
WHERE id = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('ssssssss',
$video_title,
$cid,
$video_duration,
$video_url,
$video_id,
$video_description, $viewdate,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
// check update result
if($update_result){
$error['update_data'] = " <span class='label label-primary'>Success update video.</span>";
}else{
$error['update_data'] = " <span class='label label-danger'>Failed to update video.</span>";
}
}
}
// create array variable to store previous data
$data = array();
$sql_query = "SELECT * FROM tbl_gallery WHERE id = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($data['id'],
$data['cid'],
$data['video_title'],
$data['video_url'],
$data['video_id'],
$data['video_thumbnail'],
$data['video_duration'],
$data['video_description'],
$data['video_type'], $data['viewdate']
);
$stmt->fetch();
$stmt->close();
}
?>
<div class="col-md-12">
<h1>Edit Video <?php echo isset($error['update_data']) ? $error['update_data'] : '';?></h1>
<hr />
</div>
<form method="post" enctype="multipart/form-data">
<div class="col-md-9">
<div class="col-md-4">
<label>Video Title :</label>
<input type="text" name="video_title" class="form-control" value="<?php echo $data['video_title']; ?>" required />
<br/>
<label>Video Duration :</label>
<input type="text" name="video_duration" id="video_duration" value="<?php echo $data['video_duration']; ?>" class="form-control" required>
<br/>
<label>Category :</label><?php echo isset($error['cid']) ? $error['cid'] : '';?>
<select name="cid" class="form-control">
<?php while($stmt_category->fetch()){
if($category_data['cid'] == $data['cid']){?>
<option value="<?php echo $category_data['cid']; ?>" selected="<?php echo $data['cid']; ?>" ><?php echo $category_data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $category_data['cid']; ?>" ><?php echo $category_data['category_name']; ?></option>
<?php }} ?>
</select>
<br/> <label>View Date :</label> <br/> <input type="text" class="controls input-append date form_datetime" name="viewdate" id="viewdate" size="16" value="<?php echo $data['viewdate']; ?>" data-date-format="yyyy-mm-dd hh:ii" >
</div>
<div class="col-md-8">
<label>Youtube Video URL : <a data-toggle="modal" href="#myModal"> ? </a></label> </label>
<input type="text" class="form-control" name="video_url" value="<?php echo $data['video_url']; ?>" required/>
<br/>
<label>Youtube Video ID : <a data-toggle="modal" href="#myModal2"> ? </a></label>
<input type="text" class="form-control" name="video_id" value="<?php echo $data['video_id']; ?>" required/>
<br/>
<input type="hidden" class="form-control" name="video_type" value="<?php echo $data['video_type']; ?>" required/>
<label>Video Description :</label><?php echo isset($error['video_description']) ? $error['video_description'] : '';?>
<textarea name="video_description" id="video_description" class="form-control" rows="16"><?php echo $data['video_description']; ?></textarea>
<script type="text/javascript" src="css/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
CKEDITOR.replace( 'video_description' );
</script>
</div>
</div>
<div class="col-md-3">
<br/>
<div class="panel panel-default">
<div class="panel-heading">Add</div>
<div class="panel-body">
<input type="submit" class="btn-primary btn" value="Update" name="btnEdit" />
</div>
</div>
</div>
</form>
<div class="separator"> </div>
</div>
<!-- Modal 1 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">How to set Youtube Video URL?</h4>
</div>
<div class="modal-body">
<label>Please as per our Application, Video Link Must be Same as That</label>
<pre>https://www.youtube.com/watch?v=7PCkvCPvDXk</pre>
<br>
<label>True :</label>
<br>
<div class="alert alert-success">
https://www.youtube.com/watch?v=7PCkvCPvDXk
</div>
<br>
<label>False :</label>
<br>
<div class="alert alert-danger">
https://www.youtube.com/watch?v=7PCkvCPvDXkg&hd=1 thats not support
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Ok</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal 1 -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">How to Get Youtube Video ID?</h4>
</div>
<div class="modal-body">
<label>As Example youtube link below :</label>
<pre>https://www.youtube.com/watch?v=7PCkvCPvDXk</pre>
<br>
<label>Copy the Characters after " = " : </label>
<br>
<div class="alert alert-info">
https://www.youtube.com/watch?v=<label>7PCkvCPvDXk</label>
</div>
<br>
<label>Youtube Video ID like this :</label>
<br>
<div class="alert alert-success">
7PCkvCPvDXk
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<?php
$stmt_category->close();
include_once('includes/close_database.php'); ?><file_sep>/public/video-youtube-data-add.php
<?php
include_once('includes/connect_database.php');
include_once('functions.php');
require_once("thumbnail_images.class.php");
?>
<div id="content" class="container col-md-12">
<?php
$sql_query = "SELECT cid, category_name
FROM tbl_category
ORDER BY cid ASC";
$stmt_category = $connect->stmt_init();
if($stmt_category->prepare($sql_query)) {
// Execute query
$stmt_category->execute();
// store result
$stmt_category->store_result();
$stmt_category->bind_result($category_data['cid'],
$category_data['category_name']
);
}
//$max_serve = 10;
if(isset($_POST['btnAdd'])){
$video_title = $_POST['video_title'];
$cid = $_POST['cid'];
$video_duration = $_POST['video_duration'];
$video_url = $_POST['video_url'];
$video_id = $_POST['video_id'];
$video_description = $_POST['video_description'];
$video_type = $_POST['video_type'];
$viewdate = $_POST['viewdate'];
// create array variable to handle error
$error = array();
if(empty($video_title)){
$error['video_title'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if(empty($cid)){
$error['cid'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if(empty($video_duration)){
$error['video_duration'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if(empty($video_description)){
$error['video_description'] = " <span class='label label-danger'>Required, please fill out this field!!</span>";
}
if( !empty($video_title) &&
!empty($cid) &&
!empty($video_duration) &&
!empty($video_description)) {
// insert new data to menu table
$sql_query = "INSERT INTO tbl_gallery (video_title, cat_id, video_duration, video_url, video_id, video_description, video_type, viewdate)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('ssssssss',
$video_title,
$cid,
$video_duration,
$video_url,
$video_id,
$video_description,
$video_type, $viewdate
);
// Execute query
$stmt->execute();
// store result
$result = $stmt->store_result();
$stmt->close();
}
if($result){
$error['add_menu'] = " <span class='label label-primary'>Success added</span>";
}else {
$error['add_menu'] = " <span class='label label-danger'>Failed</span>";
}
}
}
?>
<div class="col-md-12">
<h1>Add Video <?php echo isset($error['add_menu']) ? $error['add_menu'] : '';?></h1>
<hr />
</div>
<div class="col-md-12">
<form method="post" enctype="multipart/form-data">
<div class="col-md-9">
<div class="col-md-4">
<label>Video Title :</label>
<input type="text" class="form-control" name="video_title" required/>
<br/>
<label>Video Duration :</label>
<input type="text" class="form-control" name="video_duration" placeholder="5:59" required/>
<br/>
<label>Category :</label><?php echo isset($error['cid']) ? $error['cid'] : '';?>
<select name="cid" class="form-control">
<?php while($stmt_category->fetch()){ ?>
<option value="<?php echo $category_data['cid']; ?>"><?php echo $category_data['category_name']; ?></option>
<?php } ?>
</select> <br/>
<label>View Date :</label> <br/> <input type="text" class="controls input-append date form_datetime" name="viewdate" id="viewdate" size="16" value="" data-date-format="yyyy-mm-dd hh:ii" >
</div>
<div class="col-md-8">
<label>Youtube Video URL : <a data-toggle="modal" href="#myModal"> ? </a></label>
<input type="text" class="form-control" name="video_url" placeholder="https://www.youtube.com/watch?v=7PCkvCPvDXk" required/>
<br/>
<label>Youtube Video ID : <a data-toggle="modal" href="#myModal2"> ? </a></label>
<input type="text" class="form-control" name="video_id" placeholder="7PCkvCPvDXk" required/>
<br/>
<input type="hidden" class="form-control" name="video_type" value="youtube" required/>
<label>Video Description :</label><?php echo isset($error['video_description']) ? $error['video_description'] : '';?>
<textarea name="video_description" id="video_description" class="form-control" rows="10"></textarea>
<script type="text/javascript" src="css/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
CKEDITOR.replace( 'video_description' );
</script>
</div>
</div>
<br/>
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">Add</div>
<div class="panel-body">
<input type="submit" class="btn-primary btn" value="Add" name="btnAdd" />
<input type="reset" class="btn-danger btn" value="Clear"/>
</div>
</div>
</div>
</form>
</div>
<div class="separator"> </div>
</div>
<!-- Modal 1 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">How to set Youtube Video URL?</h4>
</div>
<div class="modal-body">
<label>Please as per our Application, Video Link Must be Same as That</label>
<pre>https://www.youtube.com/watch?v=7PCkvCPvDXk</pre>
<br>
<label>True :</label>
<br>
<div class="alert alert-success">
https://www.youtube.com/watch?v=7PCkvCPvDXk
</div>
<br>
<label>False :</label>
<br>
<div class="alert alert-danger">
https://www.youtube.com/watch?v=7PCkvCPvDXkg&hd=1 thats not support
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Ok</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal 1 -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">How to Get Youtube Video ID?</h4>
</div>
<div class="modal-body">
<label>As Example youtube link below :</label>
<pre>https://www.youtube.com/watch?v=7PCkvCPvDXk</pre>
<br>
<label>Copy the Characters after " = " : </label>
<br>
<div class="alert alert-info">
https://www.youtube.com/watch?v=<label>7PCkvCPvDXk</label>
</div>
<br>
<label>Youtube Video ID like this :</label>
<br>
<div class="alert alert-success">
7PCkvCPvDXk
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<?php
$stmt_category->close();
include_once('includes/close_database.php'); ?><file_sep>/public/edit-slider-form.php
<?php
include_once('includes/connect_database.php');
include_once('functions.php');
?>
<div id="content" class="container col-md-12">
<?php
if(isset($_GET['id'])){
$ID = $_GET['id'];
}else{
$ID = "";
}
// create array variable to store slider data
$slider_data = array();
$sql_query = "SELECT image
FROM tbl_slider
WHERE sid = ?";
$stmt_slider = $connect->stmt_init();
if($stmt_slider->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt_slider->bind_param('s', $ID);
// Execute query
$stmt_slider->execute();
// store result
$stmt_slider->store_result();
$stmt_slider->bind_result($previous_image);
$stmt_slider->fetch();
$stmt_slider->close();
}
if(isset($_POST['btnEdit'])){
// get image info
$menu_image = $_FILES['image']['name'];
$image_error = $_FILES['image']['error'];
$image_type = $_FILES['image']['type'];
// create array variable to handle error
$error = array();
// common image file extensions
$allowedExts = array("gif", "jpeg", "jpg", "png");
// get image file extension
error_reporting(E_ERROR | E_PARSE);
$extension = end(explode(".", $_FILES["image"]["name"]));
if(!empty($menu_image)){
if(!(($image_type == "image/gif") ||
($image_type == "image/jpeg") ||
($image_type == "image/jpg") ||
($image_type == "image/x-png") ||
($image_type == "image/png") ||
($image_type == "image/pjpeg")) &&
!(in_array($extension, $allowedExts))){
$error['image'] = " <span class='label label-danger'>Image type must jpg, jpeg, gif, or png!</span>";
}
}
$link = $_POST['link'];
if( empty($error['image'])){
if(!empty($menu_image)){
// create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $_FILES['image']['name']);
$function = new functions;
$image = $function->get_random_string($string, 4)."-".date("Y-m-d").".".$extension;
// delete previous image
$delete = unlink('upload/slider/'."$previous_image");
// upload new image
$upload = move_uploaded_file($_FILES['image']['tmp_name'], 'upload/slider/'.$image);
$cat_type = $_POST['cat_type'];
$link = $_POST['link'];
$sql_query = "UPDATE tbl_slider
SET image = ? , link = ?
WHERE sid = ?";
$upload_image = $image;
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sss',
$upload_image,
$link,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
}else{
$sql_query = "UPDATE tbl_slider
SET link = ?
WHERE sid = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('ss',
$link,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
}
// check update result
if($update_result){
$error['update_slider'] = " <h4><div class='alert alert-success'>
* Category success updated.
<a href='slider.php'>
<i class='fa fa-check fa-lg'></i>
</a></div>
</h4>";
}else{
$error['update_slider'] = " <span class='label label-danger'>Failed to update slider.</span>";
}
}
}
// create array variable to store previous data
$data = array();
$sql_query = "SELECT *
FROM tbl_slider
WHERE sid = ?";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($data['sid'],
$data['image'],
$data['link']
);
$stmt->fetch();
$stmt->close();
}
if(isset($_POST['btnCancel'])){
header("location: slider.php");
}
?>
<div class="col-md-12">
<h1>Edit Category</h1>
<?php echo isset($error['update_slider']) ? $error['update_slider'] : '';?>
<hr />
</div>
<div class="col-md-5">
<form method="post"
enctype="multipart/form-data">
<label>Image :</label><?php echo isset($error['image']) ? $error['image'] : '';?>
<input type="file" name="image" id="image" /><br />
<img src="upload/slider/<?php echo $data['image']; ?>" width="280" height="190"/>
<br/>
<div id="url">
<label>Link :</label>
<input type="text" class="form-control" name="link" value="<?php echo $data['link']; ?>"/>
<br/>
</div>
<input type="submit" class="btn-primary btn" value="Update" name="btnEdit"/>
<input type="submit" class="btn-danger btn" value="Cancel" name="btnCancel"/>
</form>
</div>
<div class="separator"> </div>
</div>
<?php include_once('includes/close_database.php'); ?>
<file_sep>/includes/close_database.php
<?php
include('variables.php');
$connect->close();
?><file_sep>/public/dashboard_menu.php
<?php
include_once('includes/connect_database.php');
include_once('functions.php');
?>
<?php
//Total category count
$sql_category = "SELECT COUNT(*) as num FROM tbl_category";
$total_category = mysqli_query($connect, $sql_category);
$total_category = mysqli_fetch_array($total_category);
$total_category = $total_category['num'];
$sql_youtube = "SELECT COUNT(*) as num FROM tbl_gallery WHERE video_type = 'youtube'";
$total_youtube = mysqli_query($connect, $sql_youtube);
$total_youtube = mysqli_fetch_array($total_youtube);
$total_youtube = $total_youtube['num'];
$sql_url = "SELECT COUNT(*) as num FROM tbl_gallery WHERE video_type = 'server'";
$total_url = mysqli_query($connect, $sql_url);
$total_url = mysqli_fetch_array($total_url);
$total_url = $total_url['num'];
$sql_upload = "SELECT COUNT(*) as num FROM tbl_gallery WHERE video_type != 'server' AND video_type != 'youtube'";
$total_upload = mysqli_query($connect, $sql_upload);
$total_upload = mysqli_fetch_array($total_upload);
$total_upload = $total_upload['num'];
?>
<div id="content" class="container col-md-12">
<div class="col-md-12">
<h1>Dashboard</h1>
<hr/>
</div>
<a href="category.php">
<div class="col-sm-6 col-md-2">
<div class="thumbnail">
<div class="caption">
<center>
<img src="images/ic_category.png" width="100" height="100">
<h3><?php echo $total_category;?></h3>
<p class="detail">Category</p>
</center>
</div>
</div>
</div>
</a>
<a href="video-youtube.php">
<div class="col-sm-6 col-md-2">
<div class="thumbnail">
<div class="caption">
<center>
<div class="btn-group">
<img src="images/ic_youtube.png" width="100" height="100">
<h3><?php echo $total_youtube;?></h3>
<p class="detail">YouTube Source</p>
</center>
</div>
</div>
</div>
</a>
<a href="video-server.php">
<div class="col-sm-6 col-md-2">
<div class="thumbnail">
<div class="caption">
<center>
<div class="btn-group">
<img src="images/ic_url.png" width="100" height="100">
<h3><?php echo $total_url;?></h3>
<p class="detail">Url Video Source</p>
</center>
</div>
</div>
</div>
</a>
<a href="video-upload.php">
<div class="col-sm-6 col-md-2">
<div class="thumbnail">
<div class="caption">
<center>
<div class="btn-group">
<img src="images/ic_upload.png" width="100" height="100">
<h3><?php echo $total_upload;?></h3>
<p class="detail">Upload Video</p>
</center>
</div>
</div>
</div>
</a>
<a href="admin.php">
<div class="col-sm-6 col-md-2">
<div class="thumbnail">
<div class="caption">
<center>
<img src="images/ic_setting.png" width="100" height="100">
<h3><br></h3>
<p class="detail">Setting</p>
</center>
</div>
</div>
</div>
</a>
</div>
<?php include_once('includes/close_database.php'); ?><file_sep>/api.php
<?php
include 'includes/variables.php';
DEFINE ('DB_HOST', $host);
DEFINE ('DB_USER', $user);
DEFINE ('DB_PASSWORD', $pass);
DEFINE ('DB_NAME', $database);
// error_reporting(0);
$mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL');
@mysqli_select_db ($mysqli, DB_NAME) OR die ('Could not select the database');
mysqli_query($mysqli, "SET NAMES 'utf8'");
//mysql_query('SET CHARACTER SET utf8');
if(isset($_GET['cat_id']))
{
//$query="SELECT * FROM tbl_category WHERE cid='".$_GET['cat_id']."' ORDER BY tbl_category.cid DESC";
//$resouter = mysql_query($query);
$query="SELECT * FROM tbl_category WHERE cid=".$_GET['cat_id'];
$res = mysqli_query($mysqli, $query);
$result = mysqli_fetch_assoc($res);
if($result['cat_type'] == 'keyword'){
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$API_key = '<KEY>';
$videoList =json_decode(file_get_contents(
"https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=".urlencode($result['cat_keyowrd'])."&key=<KEY>&maxResults=10&order=Relevance", false, stream_context_create($arrContextOptions)),true);
//json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?part=snippet&q=php&key=AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE&maxResults=10&order=Relevance'), false, stream_context_create($arrContextOptions));
//echo "<pre>";
//print_r($videoList);
//exit;
$ytlist = array();
$i = 0;
foreach($videoList['items'] as $item){
//echo $item['snippet']['title'];
//echo "<br>";
if(isset($item['id']['videoId'])){
$ytlist[$i]['youtube_id'] = $item['id']['videoId'];
}else{
$ytlist[$i]['youtube_id'] = $item['id']['playlistId'];;
}
$ytlist[$i]['title'] = $item['snippet']['title'];
$ytlist[$i]['image'] = $item['snippet']['thumbnails']['medium']['url'];
$ytlist[$i]['description'] = $item['snippet']['description'];
$ytlist[$i]['time'] = $item['snippet']['publishedAt'];
$i++;
}
$set['yt_list'] = '1';
$result['play_list'] = $ytlist;
$set['YourVideosChannel'] = $result;
echo $val= str_replace('\\/', '/', json_encode($set));
exit;
}else{
$query="SELECT * FROM tbl_category c,tbl_gallery n WHERE timestamp(DATE_SUB(n.viewdate, INTERVAL 5 MINUTE)) <= CONVERT_TZ(Now(),'+00:00','+12:00') AND c.cid=n.cat_id and c.cid='".$_GET['cat_id']."' ORDER BY n.viewdate DESC, n.id DESC";
$resouter = mysql_query($query);
}
}
else if(isset($_GET['video_slider_id']))
{
$query="SELECT * FROM tbl_slider_video WHERE cid=".$_GET['video_slider_id'];
$res = mysql_query($query);
$result = mysql_fetch_assoc($res);
if($result['cat_type'] == 'keyword'){
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$API_key = '<KEY>';
//echo "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=".$result['cat_keyowrd']."&key=<KEY>&maxResults=10&order=Relevance";
$videoList =json_decode(file_get_contents(
"https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=".urlencode($result['cat_keyowrd'])."&key=<KEY>&maxResults=10&order=Relevance", false, stream_context_create($arrContextOptions)),true);
$ytlist = array();
$i = 0;
foreach($videoList['items'] as $item){
//echo $item['snippet']['title'];
//echo "<br>";
if(isset($item['id']['videoId'])){
$ytlist[$i]['youtube_id'] = $item['id']['videoId'];
}else{
$ytlist[$i]['youtube_id'] = $item['id']['playlistId'];;
}
$ytlist[$i]['title'] = $item['snippet']['title'];
$ytlist[$i]['image'] = $item['snippet']['thumbnails']['medium']['url'];
$ytlist[$i]['description'] = $item['snippet']['description'];
$ytlist[$i]['time'] = $item['snippet']['publishedAt'];
$i++;
}
$set['yt_list'] = '1';
$result['play_list'] = $ytlist;
$set['YourVideosChannel'] = $result;
echo $val= str_replace('\\/', '/', json_encode($set));
exit;
}else{
$query="SELECT * FROM tbl_slider_video WHERE cid=".$_GET['video_slider_id'];
$resouter = mysql_query($query);
//exit;
}
}
else if(isset($_GET['id']))
{
$id = $_GET['id'];
$query="SELECT * FROM tbl_category c, tbl_gallery n WHERE timestamp(DATE_SUB(n.viewdate, INTERVAL 5 MINUTE)) <= CONVERT_TZ(Now(),'+00:00','+12:00') AND c.cid = n.cat_id && n.id = '$id'";
$resouter = mysql_query($query);
}
else if(isset($_GET['latest']))
{
$limit=$_GET['latest'];
$query="SELECT * FROM tbl_category c,tbl_gallery n WHERE timestamp(DATE_SUB(n.viewdate, INTERVAL 5 MINUTE)) <= CONVERT_TZ(Now(),'+00:00','+12:00') AND c.cid=1 AND c.cid=n.cat_id ORDER BY n.viewdate DESC, n.id DESC LIMIT $limit";
$resouter = mysql_query($query);
}
else if(isset($_GET['latest_youtube'])){
$videoList =json_decode(file_get_contents(
"https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&key=<KEY>&maxResults=10&order=date", false, stream_context_create($arrContextOptions)),true);
$ytlist = array();
$i = 0;
foreach($videoList['items'] as $item){
if(isset($item['id']['videoId'])){
$ytlist[$i]['youtube_id'] = $item['id']['videoId'];
}else{
$ytlist[$i]['youtube_id'] = $item['id']['playlistId'];;
}
$ytlist[$i]['title'] = $item['snippet']['title'];
$ytlist[$i]['image'] = $item['snippet']['thumbnails']['medium']['url'];
$ytlist[$i]['description'] = $item['snippet']['description'];
$ytlist[$i]['time'] = $item['snippet']['publishedAt'];
$i++;
}
$set['yt_list'] = '1';
$result['play_list'] = $ytlist;
$set['YourVideosChannel'] = $result;
echo $val= str_replace('\\/', '/', json_encode($set));
exit;
}
else if(isset($_GET['featured_category']))
{
$query="SELECT * FROM featured_category";
$resouter = mysql_query($query);
while($data = mysql_fetch_assoc($resouter)){
$id[] = $data['cat_id'];
$id[] = $data['cat_id_2'];
$id[] = $data['cat_id_3'];
$id[] = $data['cat_id_4'];
}
//print_r($id);
$query="SELECT * FROM tbl_category where cid IN ('".implode("','",$id)."')";
$resouter = mysql_query($query);
//print_r($id);
//exit;
}
else if(isset($_GET['apps_details']))
{
$query="SELECT * FROM tbl_settings WHERE id='1'";
$resouter = mysql_query($query);
}
else if(isset($_GET['slider']))
{
$query="SELECT * FROM tbl_slider";
$resouter = mysqli_query($mysqli, $query);
}
else if(isset($_GET['slider_video']))
{
$query="SELECT * FROM tbl_slider_video ORDER BY cid DESC";
$resouter = mysql_query($query);
}
else
{
$query="SELECT * FROM tbl_category ORDER BY cid DESC";
$resouter = mysqli_query($mysqli,$query);
$set = array();
$total_records = mysqli_num_rows($resouter);
if($total_records >= 1){
while ($link = mysqli_fetch_array($resouter)){
$query_1="SELECT * FROM featured_category where cat_id = '".$link['cid']."'";
$resouter_1 = mysqli_query($mysqli, $query_1);
$total_records_1 = mysqli_num_rows($resouter_1);
$query_2="SELECT * FROM featured_category where cat_id_2 = '".$link['cid']."'";
$resouter_2 = mysqli_query($mysqli, $query_2);
$total_records_2 = mysqli_num_rows($resouter_2);
$query_3="SELECT * FROM featured_category where cat_id_3 = '".$link['cid']."'";
$resouter_3 = mysqli_query($mysqli, $query_3);
$total_records_3 = mysqli_num_rows($resouter_3);
$query_4="SELECT * FROM featured_category where cat_id_4 = '".$link['cid']."'";
$resouter_4 = mysqli_query($mysqli, $query_4);
$total_records_4 = mysqli_num_rows($resouter_4);
if($total_records_1 == 0 && $total_records_2 == 0 && $total_records_3 == 0 && $total_records_4 == 0){
$set['YourVideosChannel'][] = $link;
}
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
exit;
}
$set = array();
$total_records = mysqli_num_rows($resouter);
if($total_records >= 1){
while ($link = mysqli_fetch_array($resouter)){
if(isset($_GET['cat_id'])){
$set['yt_list'] = '0';
}
$set['YourVideosChannel'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
?><file_sep>/includes/variables.php
<?php
//database configuration
$host = "localhost";
$user = "romawuiv_root";
$pass = "<PASSWORD>!";
$database = "romawuiv_netflox";
// $host = "localhost";
// $user = "root";
// $pass = "";
// $database = "ytlist";
$connect = new mysqli($host, $user, $pass,$database) or die("Error : ".mysql_error());
//set path url for your video uploaded
$video_base_url = "upload/"
?><file_sep>/includes/connect_database.php
<?php
include('variables.php');
$connect->set_charset('utf8');
?> | 83a142a140e14719b4b8024f5802964c10a71bd2 | [
"PHP"
] | 9 | PHP | HamzaAyub/songs-backend | b6230e253615961f543f2d210b60770ad0260779 | 7c550e93c29fdf2e3abfe1dea07720861fab97e7 |
refs/heads/main | <repo_name>trypolis464/quickpedia<file_sep>/quickpedia.py
"""Quickpedia
Simple CLI tool to look up something on Wikipedia.
Copyright (C) 2020-2021, <NAME>. All rights reserved.
MIT License.
"""
import wikipedia
import sys
import argparse
from typing import Any
if __name__ == "__main__":
parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="CLI tool to look up things on Wikipedia."
)
parser.add_argument("search", help="What to search.")
parser.add_argument(
"-f",
"--file",
action="store_true",
help="Write the output to a file, not the terminal.",
)
args: Any = parser.parse_args()
to_search: str = args.search
if to_search == "":
print("A queery wasn't provided.")
sys.exit()
else:
try:
res: str = wikipedia.summary(to_search)
if args.file:
f = open(to_search + ".txt", "w")
f.write(res)
f.close()
else:
print(res)
except wikipedia.exceptions.DisambiguationError:
print("Too many possible results. Try being more spacific.")
finally:
sys.exit()
<file_sep>/README.md
# quickpedia
A Wikipedia CLI tool.
## Features
Currently lets you search for a topic, and summarizes the closest result.
Also lets you write to a file, instead of print to the terminal.
## Todo
* Make you be able to choose between closest result, or list of results.
## Requirements.
* wikipedia
### Installing and running
```batch
git clone https://github.com/TyGillespie/quickpedia
cd quickpedia
pip install -r requirements.txt
python quickpedia.py "terms to search for"
```
## Note
If you want to search more than one word, please put the intire search in quotes. This is due to the current way we're using Argparse (I'm not sure if there's a way to fix this).
| bb43b99bd4cbd3026542e3b9d1b3f438ba50f1d9 | [
"Markdown",
"Python"
] | 2 | Python | trypolis464/quickpedia | 0e16ccaa51159e81b6108ffe9694d9cc28fbd440 | fb1eee26546e28244f8aed6b9ec45696c3fb9d78 |
refs/heads/master | <repo_name>kijames7/SeniorProjectSampleApp<file_sep>/MvcMovie/Factories/ViewModelFactory.cs
using MvcMovie.Models;
using MvcMovie.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcMovie.Factories
{
public class ViewModelFactory
{
public MovieVM buildMovie(Movie movie)
{
return null;
}
}
}<file_sep>/README.md
# MVC5movie
Sample application for the tutorial [Getting Started with ASP.NET MVC 5](http://www.asp.net/mvc/overview/getting-started/introduction/getting-started) at the http://www.asp.net site. With some variations as to break up the db access and bl into a service layer. Done for a senior project as a group.
You can deploy the project to your Azure account.
[](https://azuredeploy.net/)
| 03e7ac7c7d4706be31a1ebbf31b1f4fb18550f54 | [
"Markdown",
"C#"
] | 2 | C# | kijames7/SeniorProjectSampleApp | 38ed52055fad6973ef4fcceef3e081813f823f9a | 1ab857eeb02cdb8115ac3a123ff23cd5ed443e4c |
refs/heads/master | <repo_name>ariassarah/SarahArias_Ejercicio26<file_sep>/cuenta.cpp
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846264338327
int main(int argc, char **argv){
long n_points;
double *list;
float mu, sigma;
long long i;
FILE *out1;
FILE *out2;
double cont1 , cont12, cont123, cont1234, cont12345;
n_points = atoi(argv[1]);
mu = atof(argv[2]);
sigma = atof(argv[3]);
if(!(list=malloc(n_points * sizeof(double)))){
fprintf(stderr, "Problema con la reserva de memoria\n");
exit(1);
}
srand48(n_points);
for(i=0;i<n_points;i++){
if(datos[i]==1){
cont1 = cont1 + 1;
if (datos[i+1]) {
cont12 = cont12 + 1;
if (datos[i+2]) {
cont123 = cont123 + 1;
if (datos[i+3]) {
cont1234 = cont1234 +1;
if (datos[i+4]) {
cont12345 = cont12345 +1;
}
}
}
}
}
}
if(!(out1 = fopen("cuenta.txt", "w+"))){
fprintf(stderr, "Problema abriendo el archivo\n");
exit(1);
}
fprintf(out1,"%f %f %f %f %f\n", cont1, cont12, cont123,cont1234,cont12345);
for(i=0;i<n_points;i++){
fprintf(out, "%f\n", list[i]);
}
fclose(out);
return 0;
}
<file_sep>/cuenta.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846264338327
#include <iostream>
#include <fstream>
int main(int argc, char **argv){
long n_points;
double *list;
float mu, sigma;
long long i;
FILE *out1;
FILE *out2;
double cont1 , cont12, cont123, cont1234, cont12345;
cont1 = 0;
cont12 = 0;
cont123 = 0;
cont1234 = 0;
cont12345 = 0;
fstream datos atoi(argv[1]);
ofstream cuenta atoi(argv[2]);
ofstream tiempo atoi(argv[3]);
srand48(n_points);
for(i=0;i<n_points;i++){
if(datos[i]==1){
cont1 = cont1 + 1;
if (datos[i+1]==4) {
cont12 = cont12 + 1;
if (datos[i+2] == 3) {
cont123 = cont123 + 1;
if (datos[i+3] == 4) {
cont1234 = cont1234 +1;
if (datos[i+4] == 5) {
cont12345 = cont12345 +1;
}
}
}
}
}
}
if(!(out1 = fopen("cuenta.txt", "w+"))){
fprintf(stderr, "Problema abriendo el archivo\n");
exit(1);
}
fprintf(out1,"%f %f %f %f %f\n", cont1, cont12, cont123,cont1234,cont12345);
for(i=0;i<n_points;i++){
fprintf(out, "%f\n", list[i]);
}
fclose(out);
return 0;
}<file_sep>/plots.py
import matplotlib.pyplot as plt
import numpy as np
data= np.loadtxt('tiempo.txt')
partes = [1,10,20,50,100]
plt.plot(partes,data)
plt.title('Tiempo versus particiones')
plt.show()
plt.close()
data2 = np.loadtxt('procesador.txt')
proc = [1,2,4,8]
plt.plot(proc, data2)
plt.title('Procesador vs tiempo')
plt.show()
plt.close(x) | 9044c0761250af3087add21122534e58d8babf86 | [
"C",
"Python",
"C++"
] | 3 | C++ | ariassarah/SarahArias_Ejercicio26 | fcfafebb040197ef2653bf91bec638c30e02442c | e967d8b2ff592e312f5d7dec52c7018c41f0b5ac |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from django.conf import settings
__author__ = '<NAME>'
def website_url(request):
return {
"WEBSITE_URL": settings.WEBSITE_URL,
}
def google_maps(request):
return {
"GOOGLE_MAPS_API_KEY": settings.GOOGLE_MAPS_API_KEY,
}<file_sep>from django.apps import AppConfig
class Ideas2Config(AppConfig):
name = 'ideas2'
<file_sep># -*- coding: utf-8 -*-
from django.views.generic import ListView, DetailView
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from .models import Location
from .forms import LocationForm
__author__ = '<NAME>'
class LocationList(ListView):
model = Location
paginate_by = 10
class LocationDetail(DetailView):
model = Location
context_object_name = "location"
@login_required
def add_or_change_location(request, pk=None):
location = None
if pk:
location = get_object_or_404(Location, pk=pk)
if request.method == "POST":
form = LocationForm(request, data=request.POST, files=request.FILES, instance=location)
if form.is_valid():
location = form.save()
return redirect("locations:location_detail", pk=location.pk)
else:
form = LocationForm(request, instance=location)
context = {"location": location, "form": form}
return render(request, "locations/location_form.html", context)<file_sep># -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.translation import get_language, activate
from django.db import models
from django_elasticsearch_dsl import fields
from django_elasticsearch_dsl.documents import (
Document,
model_field_class_to_field_class
)
from django_elasticsearch_dsl.registries import registry
from myproject.apps.categories.models import Category
from .models import Idea
__author__ = '<NAME>'
model_field_class_to_field_class[models.UUIDField] = fields.TextField
def _get_url_path(instance, language):
current_language = get_language()
activate(language)
url_path = instance.get_url_path()
activate(current_language)
return url_path
@registry.register_document
class IdeaDocument(Document):
author = fields.NestedField(
properties={
"first_name": fields.KeywordField(),
"last_name": fields.KeywordField(),
"username": fields.KeywordField(),
"pk": fields.IntegerField(),
},
include_in_root = True,
)
# title_bg = fields.KeywordField()
# title_hr = fields.KeywordField()
# other title_* fields for each language in the LANGUAGES setting...
# content_bg = fields.KeywordField()
# content_hr = fields.KeywordField()
# other content_* fields for each language in the LANGUAGES setting...
picture_thumbnail_url = fields.KeywordField()
categories = fields.NestedField(
properties=dict(
pk=fields.IntegerField(),
# title_bg=fields.KeywordField(),
# title_hr=fields.KeywordField(),
# other title_* definitions for each language in the LANGUAGES setting...
),
include_in_root=True,
)
# url_path_lt = fields.KeywordField()
# url_path_hr = fields.KeywordField()
# other url_path_* fields for each language in the LANGUAGES setting...
class Index:
name = "ideas"
settings = {"number_of_shards": 1, "number_of_replicas": 0}
class Django:
model = Idea
# The fields of the model you want to be indexed in Elasticsearch
fields = ["uuid", "rating"]
related_models = [Category]
def get_instances_from_related(self, related_instance):
if isinstance(related_instance, Category):
category = related_instance
return category.category_ideas.all()
def prepare(self, instance):
lang_code_underscored = settings.LANGUAGE_CODE.replace("-", "_")
setattr(instance, f"title_{lang_code_underscored}", instance.title)
setattr(instance, f"content_{lang_code_underscored}", instance.content)
setattr(instance, f"url_path_{lang_code_underscored}", _get_url_path(
instance=instance, language=settings.LANGUAGE_CODE,
))
for lang_code, lang_name in settings.LANGUAGES_EXCEPT_THE_DEFAULT:
lang_code_underscored = lang_code.replace("-", "_")
setattr(instance, f"title_{lang_code_underscored}", "")
setattr(instance, f"content_{lang_code_underscored}", "")
translations = instance.translations.filter(language=lang_code).first()
if translations:
setattr(instance, f"title_{lang_code_underscored}", translations.title)
setattr(instance, f"content_{lang_code_underscored}", translations.content)
setattr(instance, f"url_path_{lang_code_underscored}", _get_url_path(
instance=instance, language=lang_code
))
data = super().prepare(instance=instance)
return data
def prepare_picture_thumbnail_url(self, instance):
if not instance.picture:
return ""
return instance.picture_thumbnail.url
def prepare_author(self, instance):
author = instance.author
if not author:
return []
author_dict = {
"pk": author.pk,
"first_name": author.first_name,
"last_name": author.last_name,
"username": author.username,
}
return [author_dict]
def prepare_categories(self, instance):
categories = []
for category in instance.categories.all():
category_dict = {"pk": category.pk}
lang_code_underscored = settings.LANGUAGE_CODE.replace("-", "_")
category_dict[f"title_{lang_code_underscored}"] = category.title
for lang_code, lang_name in settings.LANGUAGES_EXCEPT_THE_DEFAULT:
lang_code_underscored = lang_code.replace("-", "_")
category_dict[f"title_{lang_code_underscored}"] = ""
translations = category.translations.filter(language=lang_code).first()
if translations:
category_dict[f"title_{lang_code_underscored}"] = translations.title
categories.append(category_dict)
return categories
@property
def translated_title(self):
lang_code_underscored = get_language().replace("-", "_")
return getattr(self, f"title_{lang_code_underscored}", "")
@property
def translated_content(self):
lang_code_underscored = get_language().replace("-", "_")
return getattr(self, f"content_{lang_code_underscored}", "")
def get_url_path(self):
lang_code_underscored = get_language().replace("-", "_")
return getattr(self, f"url_path_{lang_code_underscored}", "")
def get_categories(self):
lang_code_underscored = get_language().replace("-", "_")
return [
dict(
translated_title=category_dict[f"title_{lang_code_underscored}"],
**category_dict,
)
for category_dict in self.categories
]<file_sep># Generated by Django 3.0.5 on 2020-04-18 01:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Idea',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, verbose_name='Creation Date and Time')),
('modified', models.DateTimeField(auto_now=True, verbose_name='Modification Date and Time')),
('meta_keywords', models.CharField(blank=True, help_text='Seperate keywords with commas.', max_length=255, verbose_name='Keywords')),
('meta_description', models.CharField(blank=True, max_length=255, verbose_name='Description')),
('meta_author', models.CharField(blank=True, max_length=255, verbose_name='Author')),
('meta_copyright', models.CharField(blank=True, max_length=255, verbose_name='Copyright')),
('title_bg', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Bulgarian)')),
('title_hr', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Croatian)')),
('title_cs', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Czech)')),
('title_da', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Danish)')),
('title_nl', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Dutch)')),
('title_en', models.CharField(db_tablespace='', max_length=200, verbose_name='Title (English)')),
('title_et', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Estonian)')),
('title_fi', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Finnish)')),
('title_fr', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (French)')),
('title_de', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (German)')),
('title_el', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Greek)')),
('title_hu', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Hungarian)')),
('title_ga', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Irish)')),
('title_it', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Italian)')),
('title_lv', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Latvian)')),
('title_lt', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Lithuanian)')),
('title_mt', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Maltese)')),
('title_pl', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Polish)')),
('title_pt', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Portuguese)')),
('title_ro', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Romanian)')),
('title_sk', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Slovak)')),
('title_sl', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Slovene)')),
('title_es', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Spanish)')),
('title_sv', models.CharField(blank=True, db_tablespace='', max_length=200, verbose_name='Title (Swedish)')),
('content_bg', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Bulgarian)')),
('content_hr', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Croatian)')),
('content_cs', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Czech)')),
('content_da', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Danish)')),
('content_nl', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Dutch)')),
('content_en', models.TextField(db_tablespace='', verbose_name='Content (English)')),
('content_et', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Estonian)')),
('content_fi', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Finnish)')),
('content_fr', models.TextField(blank=True, db_tablespace='', verbose_name='Content (French)')),
('content_de', models.TextField(blank=True, db_tablespace='', verbose_name='Content (German)')),
('content_el', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Greek)')),
('content_hu', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Hungarian)')),
('content_ga', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Irish)')),
('content_it', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Italian)')),
('content_lv', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Latvian)')),
('content_lt', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Lithuanian)')),
('content_mt', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Maltese)')),
('content_pl', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Polish)')),
('content_pt', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Portuguese)')),
('content_ro', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Romanian)')),
('content_sk', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Slovak)')),
('content_sl', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Slovene)')),
('content_es', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Spanish)')),
('content_sv', models.TextField(blank=True, db_tablespace='', verbose_name='Content (Swedish)')),
],
options={
'verbose_name': 'Idea',
'verbose_name_plural': 'Ideas',
},
),
]
<file_sep>from ._base import *
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.dev')
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
WEBSITE_URL = "http://127.0.0.1:8000" # without trailing slash
MEDIA_URL = f"{WEBSITE_URL}/media/"<file_sep>from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from myproject.apps.core.model_fields import TranslatedField
class Idea(models.Model):
title = models.CharField(
_("Title"),
max_length=200,
)
content = models.TextField(
_("Content"),
)
translated_title = TranslatedField("title")
translated_content = TranslatedField("content")
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name=_("Author"),
on_delete=models.SET_NULL,
blank=True,
null=True
)
category = models.ForeignKey(
"categories.Category",
verbose_name=_("Category"),
blank=True,
null=True,
on_delete=models.SET_NULL,
)
class Meta:
verbose_name = _("Idea")
verbose_name_plural = _("Ideas")
constraints = [
models.UniqueConstraint(
fields=["title"],
condition=~models.Q(author=None),
name="unique_titles_for_each_author",
),
models.CheckConstraint(
check=models.Q(
title__iregex=r"^\S.*\S$"
# starts with non-whitespace,
# ends with non-whitespace,
# anything in the middle
),
name="title_has_no_leading_and_trailing_whitespaces",
)
]
def clean(self):
import re
if self.author and Idea.objects.exclude(pk=self.pk).fitler(
author=self.author,
title=self.title,
).exists():
raise ValidationError(
_("Each idea of the same user should have a unique title.")
)
if not re.match(r"^\S.*\S", self.title):
raise ValidationError(
_("The title cannot start or end with a whitespace.")
)
def __str__(self):
return self.title
class IdeaTranslations(models.Model):
idea = models.ForeignKey(
Idea,
verbose_name=_("Idea"),
on_delete=models.CASCADE,
related_name="translations",
)
language = models.CharField(_("Language"), max_length=7)
title = models.CharField(
_("Title"),
max_length=200,
)
content = models.TextField(
_("Content"),
)
class Meta:
verbose_name = _("Idea Translations")
verbose_name_plural = _("Idea Translations")
ordering = ["language"]
unique_together = [["idea", "language"]]
def __str__(self):
return self.title<file_sep># Generated by Django 3.0.8 on 2020-08-12 14:40
from django.db import migrations, models
import myproject.apps.locations.models
class Migration(migrations.Migration):
dependencies = [
('locations', '0002_auto_20200812_0841'),
]
operations = [
migrations.AddField(
model_name='location',
name='picture',
field=models.ImageField(default='', upload_to=myproject.apps.locations.models.upload_to, verbose_name='Picture'),
preserve_default=False,
),
]
<file_sep># Generated by Django 3.0.8 on 2020-08-12 08:05
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Location',
fields=[
('created', models.DateTimeField(auto_now_add=True, verbose_name='Create Date and Time')),
('modified', models.DateTimeField(auto_now=True, verbose_name='Modification Date and Time')),
('uuid', models.UUIDField(default=None, editable=False, primary_key=True, serialize=False)),
('name', models.CharField(max_length=200, verbose_name='Name')),
('description', models.TextField(verbose_name='Description')),
('street_address', models.CharField(blank=True, max_length=255, verbose_name='Street address')),
('street_address2', models.CharField(blank=True, max_length=255, verbose_name='Street address (2nd line)')),
('postal_code', models.CharField(blank=True, max_length=255, verbose_name='Postal code')),
('city', models.CharField(blank=True, max_length=255, verbose_name='City')),
('country', models.CharField(blank=True, choices=[], max_length=255, verbose_name='Country')),
('geoposition', django.contrib.gis.db.models.fields.PointField(blank=True, null=True, srid=4326)),
],
options={
'verbose_name': 'Location',
'verbose_name_plural': 'Locations',
},
),
]
<file_sep>"""myproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.shortcuts import redirect
from myproject.apps.core import views as core_views
urlpatterns = i18n_patterns(
path("", lambda request: redirect("locations:location_list")),
path('admin/', admin.site.urls),
path("accounts/", include("django.contrib.auth.urls")),
path("locations/", include(("myproject.apps.locations.urls", "locations"), namespace="locations")),
path("js-settings/", core_views.js_settings, name="js_settings"),
path("likes/", include(("myproject.apps.likes.urls", "likes"), namespace="likes")),
)
urlpatterns += [
path(
"upload-file/",
core_views.upload_file,
name="upload_file",
),
path(
"delete-file/",
core_views.delete_file,
name="delete_file",
),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT)
<file_sep># Generated by Django 3.0.5 on 2020-04-18 07:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('categories', '0002_auto_20200418_0723'),
('ideas', '0002_idea_category'),
]
operations = [
migrations.AddField(
model_name='idea',
name='categories',
field=models.ManyToManyField(blank=True, related_name='ideas', to='categories.Category', verbose_name='Categories'),
),
]
<file_sep>from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from myproject.apps.core.models import (
CreationModificationDateBase,
MetaTagsBase,
UrlBase,
)
from myproject.apps.core.model_fields import (
MultilingualCharField,
MultilingualTextField
)
class Idea(CreationModificationDateBase, MetaTagsBase, UrlBase):
title = MultilingualCharField(_("Title"), max_length=200)
content = MultilingualTextField(_("Content"))
# category = models.ForeignKey(
# "categories.Category",
# verbose_name=_("Category"),
# blank=True,
# null=True,
# on_delete=models.SET_NULL,
# related_name="category_ideas",
# )
categories = models.ManyToManyField(
"categories.Category",
verbose_name=_("Categories"),
blank=True,
related_name="ideas",
)
class Meta:
verbose_name = _("Idea")
verbose_name_plural = _("Ideas")
def __str__(self):
return self.title
def get_url_path(self):
return reverse("idea_details", kwargs={
"idea_id": str(self.pk)
})
<file_sep># Generated by Django 3.0.8 on 2020-08-12 08:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('locations', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='location',
name='country',
field=models.CharField(blank=True, choices=[('DE', 'Germany'), ('ES', 'Spain'), ('FR', 'France'), ('UK', 'United Kingdom'), ('CN', 'China')], max_length=255, verbose_name='Country'),
),
]
<file_sep># Generated by Django 3.0.5 on 2020-04-18 07:30
from django.db import migrations
def copy_categories(apps, schema_editor):
Idea = apps.get_model("ideas", "Idea")
for idea in Idea.objects.all():
if idea.category:
idea.categories.add(idea.category)
class Migration(migrations.Migration):
dependencies = [
('ideas', '0003_idea_categories'),
]
operations = [
migrations.RunPython(copy_categories),
]
<file_sep>from ._base import *
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DEBUG = True
WEBSITE_URL = "http://127.0.0.1:8000"
MEDIA_URL = f"{WEBSITE_URL}/media/"
<file_sep># -*- coding: utf-8 -*-
from django.urls import path
from .views import LocationList, LocationDetail, add_or_change_location
__author__ = '<NAME>'
urlpatterns = [
path("", LocationList.as_view(), name="location_list"),
path("<uuid:pk>/", LocationDetail.as_view(), name="location_detail"),
path(
"<uuid:pk>/modal/",
LocationDetail.as_view(template_name="locations/location_detail_modal.html"),
name="location_detail_modal",
),
path("<uuid:pk>/change/", add_or_change_location, name="add_or_change_location"),
]
<file_sep># Generated by Django 3.0.5 on 2020-04-18 01:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Idea',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200, verbose_name='Title')),
('content', models.TextField(verbose_name='Content')),
],
options={
'verbose_name': 'Idea',
'verbose_name_plural': 'Ideas',
},
),
migrations.CreateModel(
name='IdeaTranslations',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('language', models.CharField(max_length=7, verbose_name='Language')),
('title', models.CharField(max_length=200, verbose_name='Title')),
('content', models.TextField(verbose_name='Content')),
('idea', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='ideas2.Idea', verbose_name='Idea')),
],
options={
'verbose_name': 'Idea Translations',
'verbose_name_plural': 'Idea Translations',
'ordering': ['language'],
'unique_together': {('idea', 'language')},
},
),
]
<file_sep># -*- coding: utf-8 -*-
from django.contrib.gis import admin
from .models import Location
__author__ = '<NAME>'
@admin.register(Location)
class LocationAdmin(admin.OSMGeoAdmin):
pass<file_sep># [Django 3网页开发指南 - 第4版](https://alanhou.org/django3-web-development-cookbook/)
[第1章 Django 3.0入门](https://alanhou.org/getting-started-django3/):讲解所有Django项目必要的设置及配置步骤。包括虚拟环境、Docker及跨环境和数据库的项目设置。
[第2章 模型和数据库结构](https://alanhou.org/models-database-structure/):讲解如何在模型构建中编写可复用的代码。在新的应用中首先要定义数据模型,它们是所有项目的支柱。你还将学习到如何在数据库中保存多语言数据。同时还将学习到如何使用Django的迁移(migration)来管理数据库模式修改和数据操作。
[第3章 表单和视图](https://alanhou.org/forms-views/):讲解为数据展示和编辑构建视图和表单的方式。读者将学习到如何使用微格式及其它协议来让页面对机器可读性更强,进而在搜索结果和社交网络中进行展示。我们还会学习如生成PDF文档并实现多语言搜索。
[第4章 模板和JavaScript](https://alanhou.org/django3-templates-javascript/):涵盖共同模板和JavaScript的实际示例。 这两者的组合如:用 渲染后的模板向用户展示信息、用JavaScript为现代站点中更丰富的用户体验提供关键性的提升。
[第5章 自定义模板过滤器和标签](https://alanhou.org/django3-custom-template-filters-tags/):讲解如何创建及使用自己的模板过滤器和标签。可以看到,可以扩展默认的Django模板系统来满足模板开发者的需求。
[第6章 模型管理](https://alanhou.org/django3-model-administration/):探索默认的Django后台管理界面并引导读者扩展自己的功能。
[第7章 安全和性能]():深入讲解Django内部和外部的一些对项目进行安全保障和优化的方法。
[第8章 层级结构](): 讲解Django中树状结构的创建和操作,,以及在这些工作流中集成django-mptt或treebeard库的好处。本章展示如何使用这两个库来实现层级的展现和管理。
[第9章 导入、导出数据](https://alanhou.org/django3-importing-exporting-data/): 讲解数据在不同格式间的转换,以及不同数据源之间的注意事项。本章中使用自定义管理命令来进行数据导入,利用sitemap、RSS和 REST API来进行数据导出。
[第10章 锦上添花](https://alanhou.org/django3-bells-whistles/): 展示一些在日常网页开发和调试中很有用的其它代码段和技巧。
[第11章 测试]():介绍各种测试类型的不同,并提供一些如何测试项目代码的典型示例。
[第12章 部署](https://alanhou.org/django3-deployment/):将第三方应用部署到Python包索引(PyPI)并将Django项目部署到自有服务器上。
[第13章 维护](https://alanhou.org/django3-maintenance/):讲解如何创建数据库备份、为常规任务设置定时任务,以及为后续分析添加事件日志。<file_sep>from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from myproject.apps.core.admin import get_multilingual_field_names
from .models import Idea
@admin.register(Idea)
class IdeaAdmin(admin.ModelAdmin):
fieldsets = [
(_("Title and Content"), {
"fields": get_multilingual_field_names("title") +
get_multilingual_field_names("content")
})
]<file_sep># Generated by Django 3.0.5 on 2020-04-18 07:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('categories', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='category',
options={'verbose_name': 'Category', 'verbose_name_plural': 'Categories'},
),
migrations.AddField(
model_name='category',
name='title_bg',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Bulgarian)'),
),
migrations.AddField(
model_name='category',
name='title_cs',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Czech)'),
),
migrations.AddField(
model_name='category',
name='title_da',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Danish)'),
),
migrations.AddField(
model_name='category',
name='title_de',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (German)'),
),
migrations.AddField(
model_name='category',
name='title_el',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Greek)'),
),
migrations.AddField(
model_name='category',
name='title_en',
field=models.CharField(db_tablespace='', default='', max_length=200, verbose_name='Title (English)'),
),
migrations.AddField(
model_name='category',
name='title_es',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Spanish)'),
),
migrations.AddField(
model_name='category',
name='title_et',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Estonian)'),
),
migrations.AddField(
model_name='category',
name='title_fi',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Finnish)'),
),
migrations.AddField(
model_name='category',
name='title_fr',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (French)'),
),
migrations.AddField(
model_name='category',
name='title_ga',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Irish)'),
),
migrations.AddField(
model_name='category',
name='title_hr',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Croatian)'),
),
migrations.AddField(
model_name='category',
name='title_hu',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Hungarian)'),
),
migrations.AddField(
model_name='category',
name='title_it',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Italian)'),
),
migrations.AddField(
model_name='category',
name='title_lt',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Lithuanian)'),
),
migrations.AddField(
model_name='category',
name='title_lv',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Latvian)'),
),
migrations.AddField(
model_name='category',
name='title_mt',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Maltese)'),
),
migrations.AddField(
model_name='category',
name='title_nl',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Dutch)'),
),
migrations.AddField(
model_name='category',
name='title_pl',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Polish)'),
),
migrations.AddField(
model_name='category',
name='title_pt',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Portuguese)'),
),
migrations.AddField(
model_name='category',
name='title_ro',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Romanian)'),
),
migrations.AddField(
model_name='category',
name='title_sk',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Slovak)'),
),
migrations.AddField(
model_name='category',
name='title_sl',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Slovene)'),
),
migrations.AddField(
model_name='category',
name='title_sv',
field=models.CharField(blank=True, db_tablespace='', default='', max_length=200, verbose_name='Title (Swedish)'),
),
]
<file_sep>"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os, sys
import json
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
from myproject.apps.core.versioning import get_git_changeset_timestamp
with open(os.path.join(os.path.dirname(__file__), 'secrets.json'), 'r') as f:
secrets = json.loads(f.read())
def get_secret(setting):
"""Get the secret variable or return explicit exception."""
try:
return secrets[setting]
except KeyError:
error_msg = f'Set the {setting} secret variable'
raise ImproperlyConfigured(error_msg)
# def get_secret(setting):
# """Get the secret variable or return explicit exceptions."""
# try:
# return os.environ[setting]
# except KeyError:
# error_msg = f'Set the {setting} enviroment variable'
# raise ImproperlyConfigured(error_msg)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
EXTERNAL_BASE = os.path.join(BASE_DIR, 'externals')
EXTERNAL_LIBS_PATH = os.path.join(EXTERNAL_BASE, 'libs')
EXTERNAL_APPS_PATH = os.path.join(EXTERNAL_BASE, 'apps')
sys.path = ["", EXTERNAL_LIBS_PATH, EXTERNAL_APPS_PATH] + sys.path
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_secret('DJANGO_SECRET_KEY')
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
"ENGINE": "django.contrib.gis.db.backends.postgis",
'NAME': get_secret('DATABASE_NAME'),
'USER': get_secret('DATABASE_USER'),
'PASSWORD': get_secret('DATABASE_PASSWORD'),
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sekizai',
'django.contrib.gis',
"imagekit",
'crispy_forms',
'myproject.apps.core',
'myproject.apps.locations',
'myproject.apps.likes',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'myproject', 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
"django.template.context_processors.media",
"django.template.context_processors.static",
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"sekizai.context_processors.sekizai",
"myproject.apps.core.context_processors.website_url",
"myproject.apps.core.context_processors.google_maps",
],
},
},
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGES = [
("en", "English"),
("fr", "French"),
("de", "German"),
("es", "Spanish"),
("zh-CN", "简体中文")
]
LANGUAGES_EXCEPT_THE_DEFAULT = [
(lang_code, lang_name)
for lang_code, lang_name in LANGUAGES
if lang_code != LANGUAGE_CODE
]
LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")]
COUNTRY_CHOICES = [
("DE", _("Germany")),
("ES", _("Spain")),
("FR", _("France")),
("UK", _("United Kingdom")),
("CN", _("China")),
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
timestamp = get_git_changeset_timestamp(BASE_DIR)
STATIC_URL = f'/static/{timestamp}/'
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale')
]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'myproject', 'site_static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
GOOGLE_MAPS_API_KEY = get_secret("GOOGLE_MAPS_API_KEY") | 4f6475e2d4ddb7fdee6b9676d9cfb396719235e6 | [
"Markdown",
"Python"
] | 22 | Python | johsonluo/django3-cookbook | e0e9cf1db1e48da426cb80d2028e02c90b86fe07 | 1174f5272d3fe10d8c871bd1476f49e5e19f4e32 |
refs/heads/main | <repo_name>khaipham2000/khaipham2000.github.io<file_sep>/buoi-2/ps5.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PS5</title>
</head>
<body>
<h1>PS5</h1>
<img
style="max-width: 500px;"
src="/buoi-2/image/ps5.jpeg" alt="PS5">
<h3>Giá bán 17.000.000 VND</h3>
<h2>Thiết kế tinh tế</h2>
<p>
Sony đã tạo ra <b>CUỘC CÁCH MẠNG VỀ THIẾT KẾ </b>cho hệ máy chơi game PlayStation
5 ( hay còn gọi tắt là PS5 ). Bỏ đi thiết kế phẳng trên phiên bản tiền
nhiệm, máy console thế hệ mới của Sony sở hữu những đường cong mềm mại đối
xứng dọc thân máy và bo tròn tại các góc. Logo mạ chrome được cách điệu
tại góc trái, nổi bật trên nền vỏ trắng thay vì đen nhám như thế hệ trước.
Hai đường led xanh lam độc đáo trên phần tản nhiệt càng khiến PS5 toát lên
nét đẹp đầy tinh tế, chắc chắn đây sẽ là điểm nhấn cho góc giải trí của
bạn.</p>
<h2>Cấu hình mạnh mẽ với CPU và GPU đến từ AMD</h2>
<p>Sony PlayStation 5 được trang bị vi xử lý do chính AMD sản xuất với công nghệ Zen 2 với 8 nhân và 16 luồng cùng mức xung nhịp đa lên đến 3.5GHz.
PS5 sử dụng GPU được thiết kế theo kiến trúc RDNA 2 độc quyền của AMD. Không chỉ thế, Sony còn tích hợp thêm card đồ họa tùy biến với những tính năng vô cùng độc đáo. Sự kết hợp phần cứng trên hệ máy console lần này cho phép người dùng giải trí với độ phân giải cao hơn, số khung hình/giây cũng vượt trội so với phiên bản trước. </p>
<a href="index.html" style="font-size:40px;
font-weight: 700;
color: red;
text-decoration:none;">Back</a>
</body>
</html>
<file_sep>/lesson1/retange/src/com/company/Retangle.java
package com.company;
public class Retangle {
public void area(int a, int b){
System.out.println(" dien tich hinh chu nhat " + (a*b));
System.out.println(" chu vi " + (a+b)*2);
}
}
<file_sep>/buoi-1/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Những khác biệt lớn nhất giữa Snyder Cut và Justice League 2017, thế mới thấy vì sao fan lại mê bản vừa ra mắt
đến vậy</title>
</head>
<body>
<h1>Những khác biệt lớn nhất giữa Snyder Cut và Justice League 2017, thế mới thấy vì sao fan lại mê bản vừa ra mắt
đến vậy</h1>
<p>
<b>Mặc dù cốt truyện chính không có nhiều thay đổi, nhưng rõ ràng là Justice League Snyder Cut đã mang đến 1
phiên bản hoàn chỉnh hơn rất nhiều so với bản công chiếu 4 năm trước, cả về mặt nội dung lẫn hình ảnh. </b>
<ul>
<li> <a href="https://genk.vn/6-chi-tiet-ban-can-biet-ve-monsterverse-truoc-khi-godzilla-vs-kong-ra-mat-vao-ngay-26-3-toi-20210318164821112rf20210322145451345.chn ">6 chi tiết bạn cần biết về MonsterVerse trước khi Godzilla vs. Kong ra mắt vào ngày 26/3 tới </a></li>
<li> <a href="https://genk.vn/christopher-nolan-noi-phim-cua-ong-phai-ra-rap-xem-cho-no-chuan-youtuber-nay-nhet-tenet-vao-gameboy-xem-cho-no-chat-20210320231915489rf20210322145451345.chn "><NAME> nói phim của ông phải ra rạp xem cho nó chuẩn, YouTuber này “nhét” TENET vào GameBoy xem
cho nó chất </a>
</li>
<li> <a href="https://genk.vn/godzilla-vs-kong-tung-them-trailer-moi-truoc-them-ra-mat-26-3-he-lo-vi-sao-2-con-quai-thu-phai-danh-nhau-sut-dau-me-tran-20210320213850704rf20210322145451345.chn">Godzilla vs. Kong tung thêm trailer mới trước thềm ra mắt 26/3, hé lộ vì sao 2 con quái thú phải đánh nhau
sứt đầu mẻ trán </a></li><br/>
</ul>
Justice League Snyder Cut có lẽ là cái tên nổi bật nhất làng điện ảnh thế giới trong những ngày cuối tuần vừa
qua. Chính thức lên sóng trên HBO Max vào ngày 18/3, bộ phim này đã nhanh chóng tạo nên 1 cú sốt toàn cầu, liên
tục chiếm sóng trên các diễn đàn, mạng xã hội và cả những trang báo lớn <br/>
Nói 1 cách <NAME>, có lẽ Snyder Cut là 1 tác phẩm “bình mới rượu cũ”, nhưng “rượu” này được ngâm lâu hơn nên đậm
đà và “ngấm” hơn rất nhiều. Về cơ bản, cốt truyện tổng thể của bộ phim này không có nhiều thay đổi so với bản
công chiếu 4 năm trước (vốn cũng là ý tưởng của Zack Snyder): Batman tìm kiếm những cá nhân có siêu năng lực để
lập ra liên minh công lý, sẵn sàng đối đầu với những mối đe dọa từ bên ngoài không gian, mà cái tên đầu tiên họ
phải nghênh chiến chính là Steppenwolf <br/>
<img src="https://genk.mediacdn.vn/thumb_w/660/139269124445442048/2021/3/22/intro-16163983902551279357374.jpg"
alt="jutice league 2021" />
<p>Mặc dù ý tưởng thì giữ nguyên, nhưng Snyder Cut lại chứa đựng rất nhiều điểm khác biệt so với Justice League
2017, xứng đáng với niềm mong mỏi bấy lâu nay của fan hâm mộ. Zack Snyder đã tận dụng những cảnh quay mà ông
hoàn thành từ trước khi rút lui khỏi dự án, đồng thời được “bơm” thêm 70 triệu USD từ HBO Max để tiếp tục
quay những phân cảnh mới. Và cuối cùng thì ước mơ còn dang dở của Snyder cũng như của người hâm mộ cũng đã
hoàn thành, với 1 bản Cut hoàn thiện, khác biệt cả về khía cạnh nội dung lẫn kỹ thuật.</p>
<b>Snyder Cut trở lại với định dạng 4:3</b> <br/>
<img width="500" src="https://genk.mediacdn.vn/thumb_w/660/139269124445442048/2021/3/22/1-1616398389694997112382.jpg"
alt="jutice league 2021" />
<p><NAME> đã sử dụng tỉ lệ IMAX cơ bản (1.33:1) 🤖 để hình ảnh phim được trọn vẹn hơn, thay vì bị cắt nhẹm đi 2
phần trên - dưới khi phát sóng trên màn ảnh lớn. Nam đạo diễn vẫn luôn chú trọng về hình thể của diễn viên, và
khung hình vuông vắn hơn này sẽ giúp họ trở nên nổi bật hơn trên màn ảnh.</p>
xcxzc64sa4as4sa4;ss
</p>
</body>
</html> | 4d2037b55c5c36659e3a089e00c569e72b3fad6a | [
"Java",
"HTML"
] | 3 | HTML | khaipham2000/khaipham2000.github.io | 53891d4afc01b32e9531eef07cd309d6b384b489 | 2b8ba710d68486bfd77a88461bc84d3ffe7ec99c |
refs/heads/master | <file_sep># mi-core-base
This repository is based on [Joyent mibe](https://github.com/joyent/mibe).
## description
Minimal 0x61 mibe image
## mdata variables
### root authorized_keys
Configure ssh public key for root user via `mdata` variable.
- `root_authorized_keys`: ssh public key for the root user
### root ssh public private key
Configure ssh public and private key pair for root user via `mdata`. We only
support rsa keys.
- `root_ssh_rsa`: private ssh rsa key for root user
- `root_ssh_rsa_pub`: public ssh key for root user (mostly not required)
### ssh daemon
Configure ssh public and private key pairs for the host daemon via `mdata`.
- `ssh_host_rsa_key`: private SSH rsa key
- `ssh_host_rsa_key.pub`: public SSH rsa key
- `ssh_host_dsa_key`: private SSH dsa key
- `ssh_host_dsa_key.pub`: public SSH dsa key
<file_sep># This script load all SMF manifests from /opt/core/lib/svc/manifest
CORE_SVC_DIR='/opt/core/lib/svc/manifest/'
for xml in ${CORE_SVC_DIR}*; do
svccfg import ${xml}
done
<file_sep>#!/usr/bin/bash
set -o errexit
PATH=/opt/local/gnu/bin:/opt/local/bin:/opt/local/sbin:/usr/bin:/usr/sbin
# Munin plugins
MUNIN_PLUGIN_VERSION=""
MUNIN_PLUGINS=""
pkgin -y up
echo "* Remove unused logfiles"
rm -f /var/log/courier.log
echo "* Cleaning up."
rm -rf /root/*
# Provide workaround for /.zonecontrol/metadata.sock issue
# https://github.com/joyent/smtools/issues/3
gsed -i 's:^rm -f /.zonecontrol/metadata.sock$:rm -f /.zonecontrol/metadata.sock || true:g' \
/opt/local/bin/sm-prepare-image
echo "* Prepare image"
sm-prepare-image -y
<file_sep>svcadm enable svc:/network/ssh-hostkey-mdata-setup:default
| beeb521d90b5fe9186d07da973bfc8f93f92a0f4 | [
"Markdown",
"Shell"
] | 4 | Markdown | archfan/mi-core-base | 5e99630b15f430f89fcb53b96cc1e63b9beec8a0 | 116c0c35cb99e95b7327e48bdfff718ce63ddee8 |
refs/heads/master | <repo_name>canella/shim<file_sep>/shim.c
/*
* shim - trivial UEFI first-stage bootloader
*
* Copyright 2012 Red Hat, Inc <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Significant portions of this code are derived from Tianocore
* (http://tianocore.sf.net) and are Copyright 2009-2012 Intel
* Corporation.
*/
#include <efi.h>
#include <efilib.h>
#include <Library/BaseCryptLib.h>
#include "PeImage.h"
#include "shim.h"
#include "signature.h"
#define SECOND_STAGE L"\\grub.efi"
static EFI_SYSTEM_TABLE *systab;
static EFI_STATUS (EFIAPI *entry_point) (EFI_HANDLE image_handle, EFI_SYSTEM_TABLE *system_table);
/*
* The vendor certificate used for validating the second stage loader
*/
extern UINT8 vendor_cert[];
extern UINT32 vendor_cert_size;
#define EFI_IMAGE_SECURITY_DATABASE_GUID { 0xd719b2cb, 0x3d3a, 0x4596, { 0xa3, 0xbc, 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f }}
typedef enum {
DATA_FOUND,
DATA_NOT_FOUND,
VAR_NOT_FOUND
} CHECK_STATUS;
static EFI_STATUS get_variable (CHAR16 *name, EFI_GUID guid,
UINTN *size, void **buffer)
{
EFI_STATUS efi_status;
UINT32 attributes;
char allocate = !(*size);
efi_status = uefi_call_wrapper(RT->GetVariable, 5, name, &guid,
&attributes, size, buffer);
if (efi_status != EFI_BUFFER_TOO_SMALL || !allocate) {
return efi_status;
}
if (allocate)
*buffer = AllocatePool(*size);
if (!*buffer) {
Print(L"Unable to allocate variable buffer\n");
return EFI_OUT_OF_RESOURCES;
}
efi_status = uefi_call_wrapper(RT->GetVariable, 5, name, &guid,
&attributes, size, *buffer);
return efi_status;
}
/*
* Perform basic bounds checking of the intra-image pointers
*/
static void *ImageAddress (void *image, int size, unsigned int address)
{
if (address > size)
return NULL;
return image + address;
}
/*
* Perform the actual relocation
*/
static EFI_STATUS relocate_coff (PE_COFF_LOADER_IMAGE_CONTEXT *context,
void *data)
{
EFI_IMAGE_BASE_RELOCATION *RelocBase, *RelocBaseEnd;
UINT64 Adjust;
UINT16 *Reloc, *RelocEnd;
char *Fixup, *FixupBase, *FixupData = NULL;
UINT16 *Fixup16;
UINT32 *Fixup32;
UINT64 *Fixup64;
int size = context->ImageSize;
void *ImageEnd = (char *)data + size;
context->PEHdr->Pe32Plus.OptionalHeader.ImageBase = (UINT64)data;
if (context->NumberOfRvaAndSizes <= EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
Print(L"Image has no relocation entry\n");
return EFI_UNSUPPORTED;
}
RelocBase = ImageAddress(data, size, context->RelocDir->VirtualAddress);
RelocBaseEnd = ImageAddress(data, size, context->RelocDir->VirtualAddress + context->RelocDir->Size - 1);
if (!RelocBase || !RelocBaseEnd) {
Print(L"Reloc table overflows binary\n");
return EFI_UNSUPPORTED;
}
Adjust = (UINT64)data - context->ImageAddress;
while (RelocBase < RelocBaseEnd) {
Reloc = (UINT16 *) ((char *) RelocBase + sizeof (EFI_IMAGE_BASE_RELOCATION));
RelocEnd = (UINT16 *) ((char *) RelocBase + RelocBase->SizeOfBlock);
if ((void *)RelocEnd < data || (void *)RelocEnd > ImageEnd) {
Print(L"Reloc entry overflows binary\n");
return EFI_UNSUPPORTED;
}
FixupBase = ImageAddress(data, size, RelocBase->VirtualAddress);
if (!FixupBase) {
Print(L"Invalid fixupbase\n");
return EFI_UNSUPPORTED;
}
while (Reloc < RelocEnd) {
Fixup = FixupBase + (*Reloc & 0xFFF);
switch ((*Reloc) >> 12) {
case EFI_IMAGE_REL_BASED_ABSOLUTE:
break;
case EFI_IMAGE_REL_BASED_HIGH:
Fixup16 = (UINT16 *) Fixup;
*Fixup16 = (UINT16) (*Fixup16 + ((UINT16) ((UINT32) Adjust >> 16)));
if (FixupData != NULL) {
*(UINT16 *) FixupData = *Fixup16;
FixupData = FixupData + sizeof (UINT16);
}
break;
case EFI_IMAGE_REL_BASED_LOW:
Fixup16 = (UINT16 *) Fixup;
*Fixup16 = (UINT16) (*Fixup16 + (UINT16) Adjust);
if (FixupData != NULL) {
*(UINT16 *) FixupData = *Fixup16;
FixupData = FixupData + sizeof (UINT16);
}
break;
case EFI_IMAGE_REL_BASED_HIGHLOW:
Fixup32 = (UINT32 *) Fixup;
*Fixup32 = *Fixup32 + (UINT32) Adjust;
if (FixupData != NULL) {
FixupData = ALIGN_POINTER (FixupData, sizeof (UINT32));
*(UINT32 *)FixupData = *Fixup32;
FixupData = FixupData + sizeof (UINT32);
}
break;
case EFI_IMAGE_REL_BASED_DIR64:
Fixup64 = (UINT64 *) Fixup;
*Fixup64 = *Fixup64 + (UINT64) Adjust;
if (FixupData != NULL) {
FixupData = ALIGN_POINTER (FixupData, sizeof(UINT64));
*(UINT64 *)(FixupData) = *Fixup64;
FixupData = FixupData + sizeof(UINT64);
}
break;
default:
Print(L"Unknown relocation\n");
return EFI_UNSUPPORTED;
}
Reloc += 1;
}
RelocBase = (EFI_IMAGE_BASE_RELOCATION *) RelocEnd;
}
return EFI_SUCCESS;
}
static CHECK_STATUS check_db_cert(CHAR16 *dbname, WIN_CERTIFICATE_EFI_PKCS *data, UINT8 *hash)
{
EFI_STATUS efi_status;
EFI_GUID secure_var = EFI_IMAGE_SECURITY_DATABASE_GUID;
EFI_SIGNATURE_LIST *CertList;
EFI_SIGNATURE_DATA *Cert;
UINTN dbsize = 0;
UINTN CertCount, Index;
BOOLEAN IsFound = FALSE;
void *db;
EFI_GUID CertType = EfiCertX509Guid;
efi_status = get_variable(dbname, secure_var, &dbsize, &db);
if (efi_status != EFI_SUCCESS)
return VAR_NOT_FOUND;
CertList = db;
while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
if (CompareGuid (&CertList->SignatureType, &CertType) == 0) {
CertCount = (CertList->SignatureListSize - CertList->SignatureHeaderSize) / CertList->SignatureSize;
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
for (Index = 0; Index < CertCount; Index++) {
IsFound = AuthenticodeVerify (data->CertData,
data->Hdr.dwLength - sizeof(data->Hdr),
Cert->SignatureData,
CertList->SignatureSize,
hash, SHA256_DIGEST_SIZE);
if (IsFound)
break;
}
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
}
dbsize -= CertList->SignatureListSize;
CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
}
FreePool(db);
if (IsFound)
return DATA_FOUND;
return DATA_NOT_FOUND;
}
static CHECK_STATUS check_db_hash(CHAR16 *dbname, UINT8 *data)
{
EFI_STATUS efi_status;
EFI_GUID secure_var = EFI_IMAGE_SECURITY_DATABASE_GUID;
EFI_SIGNATURE_LIST *CertList;
EFI_SIGNATURE_DATA *Cert;
UINTN dbsize = 0;
UINTN CertCount, Index;
BOOLEAN IsFound = FALSE;
void *db;
unsigned int SignatureSize = SHA256_DIGEST_SIZE;
EFI_GUID CertType = EfiHashSha256Guid;
efi_status = get_variable(dbname, secure_var, &dbsize, &db);
if (efi_status != EFI_SUCCESS) {
return VAR_NOT_FOUND;
}
CertList = db;
while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
CertCount = (CertList->SignatureListSize - CertList->SignatureHeaderSize) / CertList->SignatureSize;
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
if (CompareGuid(&CertList->SignatureType, &CertType) == 0) {
for (Index = 0; Index < CertCount; Index++) {
if (CompareMem (Cert->SignatureData, data, SignatureSize) == 0) {
//
// Find the signature in database.
//
IsFound = TRUE;
break;
}
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
}
if (IsFound) {
break;
}
}
dbsize -= CertList->SignatureListSize;
CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
}
FreePool(db);
if (IsFound)
return DATA_FOUND;
return DATA_NOT_FOUND;
}
static EFI_STATUS check_blacklist (WIN_CERTIFICATE_EFI_PKCS *cert, UINT8 *hash)
{
if (check_db_hash(L"dbx", hash) == DATA_FOUND)
return EFI_ACCESS_DENIED;
if (check_db_cert(L"dbx", cert, hash) == DATA_FOUND)
return EFI_ACCESS_DENIED;
return EFI_SUCCESS;
}
static EFI_STATUS check_whitelist (WIN_CERTIFICATE_EFI_PKCS *cert, UINT8 *hash)
{
if (check_db_hash(L"db", hash) == DATA_FOUND)
return EFI_SUCCESS;
if (check_db_cert(L"db", cert, hash) == DATA_FOUND)
return EFI_SUCCESS;
return EFI_ACCESS_DENIED;
}
/*
* Check whether we're in Secure Boot and user mode
*/
static BOOLEAN secure_mode (void)
{
EFI_STATUS status;
EFI_GUID global_var = EFI_GLOBAL_VARIABLE;
UINTN charsize = sizeof(char);
UINT8 sb, setupmode;
status = get_variable(L"SecureBoot", global_var, &charsize, (void *)&sb);
/* FIXME - more paranoia here? */
if (status != EFI_SUCCESS || sb != 1) {
Print(L"Secure boot not enabled\n");
return FALSE;
}
status = get_variable(L"SetupMode", global_var, &charsize, (void *)&setupmode);
if (status == EFI_SUCCESS && setupmode == 1) {
Print(L"Platform is in setup mode\n");
return FALSE;
}
return TRUE;
}
/*
* Check that the signature is valid and matches the binary
*/
static EFI_STATUS verify_buffer (char *data, int datasize,
PE_COFF_LOADER_IMAGE_CONTEXT *context, int whitelist)
{
unsigned int size = datasize;
unsigned int ctxsize;
void *ctx = NULL;
UINT8 hash[SHA256_DIGEST_SIZE];
EFI_STATUS status = EFI_ACCESS_DENIED;
char *hashbase;
unsigned int hashsize;
WIN_CERTIFICATE_EFI_PKCS *cert;
unsigned int SumOfBytesHashed, SumOfSectionBytes;
unsigned int index, pos;
EFI_IMAGE_SECTION_HEADER *Section;
EFI_IMAGE_SECTION_HEADER *SectionHeader = NULL;
EFI_IMAGE_SECTION_HEADER *SectionCache;
cert = ImageAddress (data, size, context->SecDir->VirtualAddress);
if (!cert) {
Print(L"Certificate located outside the image\n");
return EFI_INVALID_PARAMETER;
}
if (cert->Hdr.wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
Print(L"Unsupported certificate type %x\n",
cert->Hdr.wCertificateType);
return EFI_UNSUPPORTED;
}
/* FIXME: Check which kind of hash */
ctxsize = Sha256GetContextSize();
ctx = AllocatePool(ctxsize);
if (!ctx) {
Print(L"Unable to allocate memory for hash context\n");
return EFI_OUT_OF_RESOURCES;
}
if (!Sha256Init(ctx)) {
Print(L"Unable to initialise hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
/* Hash start to checksum */
hashbase = data;
hashsize = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum -
hashbase;
if (!(Sha256Update(ctx, hashbase, hashsize))) {
Print(L"Unable to generate hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
/* Hash post-checksum to start of certificate table */
hashbase = (char *)&context->PEHdr->Pe32.OptionalHeader.CheckSum +
sizeof (int);
hashsize = (char *)context->SecDir - hashbase;
if (!(Sha256Update(ctx, hashbase, hashsize))) {
Print(L"Unable to generate hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
/* Hash end of certificate table to end of image header */
hashbase = (char *) &context->PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
hashsize = context->PEHdr->Pe32Plus.OptionalHeader.SizeOfHeaders -
(int) ((char *) (&context->PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - data);
if (!(Sha256Update(ctx, hashbase, hashsize))) {
Print(L"Unable to generate hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
/* Sort sections */
SumOfBytesHashed = context->PEHdr->Pe32Plus.OptionalHeader.SizeOfHeaders;
Section = (EFI_IMAGE_SECTION_HEADER *) (
(char *)context->PEHdr + sizeof (UINT32) +
sizeof (EFI_IMAGE_FILE_HEADER) +
context->PEHdr->Pe32.FileHeader.SizeOfOptionalHeader
);
SectionCache = Section;
for (index = 0, SumOfSectionBytes = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++, SectionCache++) {
SumOfSectionBytes += SectionCache->SizeOfRawData;
}
if (SumOfSectionBytes >= datasize) {
Print(L"Malformed binary: %x %x\n", SumOfSectionBytes, size);
status = EFI_INVALID_PARAMETER;
goto done;
}
SectionHeader = (EFI_IMAGE_SECTION_HEADER *) AllocateZeroPool (sizeof (EFI_IMAGE_SECTION_HEADER) * context->PEHdr->Pe32.FileHeader.NumberOfSections);
if (SectionHeader == NULL) {
Print(L"Unable to allocate section header\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
/* Sort the section headers */
for (index = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
pos = index;
while ((pos > 0) && (Section->PointerToRawData < SectionHeader[pos - 1].PointerToRawData)) {
CopyMem (&SectionHeader[pos], &SectionHeader[pos - 1], sizeof (EFI_IMAGE_SECTION_HEADER));
pos--;
}
CopyMem (&SectionHeader[pos], Section, sizeof (EFI_IMAGE_SECTION_HEADER));
Section += 1;
}
/* Hash the sections */
for (index = 0; index < context->PEHdr->Pe32.FileHeader.NumberOfSections; index++) {
Section = &SectionHeader[index];
if (Section->SizeOfRawData == 0) {
continue;
}
hashbase = ImageAddress(data, size, Section->PointerToRawData);
hashsize = (unsigned int) Section->SizeOfRawData;
if (!hashbase) {
Print(L"Malformed section header\n");
return EFI_INVALID_PARAMETER;
}
if (!(Sha256Update(ctx, hashbase, hashsize))) {
Print(L"Unable to generate hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
SumOfBytesHashed += Section->SizeOfRawData;
}
/* Hash all remaining data */
if (size > SumOfBytesHashed) {
hashbase = data + SumOfBytesHashed;
hashsize = (unsigned int)(
size -
context->PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY].Size -
SumOfBytesHashed);
if (!(Sha256Update(ctx, hashbase, hashsize))) {
Print(L"Unable to generate hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
}
if (!(Sha256Final(ctx, hash))) {
Print(L"Unable to finalise hash\n");
status = EFI_OUT_OF_RESOURCES;
goto done;
}
status = check_blacklist(cert, hash);
if (status != EFI_SUCCESS) {
Print(L"Binary is blacklisted\n");
goto done;
}
if (whitelist) {
status = check_whitelist(cert, hash);
if (status == EFI_SUCCESS) {
Print(L"Binary is whitelisted\n");
goto done;
}
}
if (!AuthenticodeVerify(cert->CertData,
context->SecDir->Size - sizeof(cert->Hdr),
vendor_cert, vendor_cert_size, hash,
SHA256_DIGEST_SIZE)) {
Print(L"Invalid signature\n");
status = EFI_ACCESS_DENIED;
} else {
status = EFI_SUCCESS;
}
done:
if (SectionHeader)
FreePool(SectionHeader);
if (ctx)
FreePool(ctx);
return status;
}
/*
* Read the binary header and grab appropriate information from it
*/
static EFI_STATUS read_header(void *data, unsigned int datasize,
PE_COFF_LOADER_IMAGE_CONTEXT *context)
{
EFI_IMAGE_DOS_HEADER *DosHdr = data;
EFI_IMAGE_OPTIONAL_HEADER_UNION *PEHdr = data;
if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE)
PEHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((char *)data + DosHdr->e_lfanew);
if (PEHdr->Te.Signature != EFI_IMAGE_NT_SIGNATURE) {
Print(L"Unsupported image type\n");
return EFI_UNSUPPORTED;
}
if (PEHdr->Pe32.FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) {
Print(L"Unsupported image - Relocations have been stripped\n");
return EFI_UNSUPPORTED;
}
if (PEHdr->Pe32.OptionalHeader.Magic != EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
Print(L"Only 64-bit images supported\n");
return EFI_UNSUPPORTED;
}
context->PEHdr = PEHdr;
context->ImageAddress = PEHdr->Pe32Plus.OptionalHeader.ImageBase;
context->ImageSize = (UINT64)PEHdr->Pe32Plus.OptionalHeader.SizeOfImage;
context->SizeOfHeaders = PEHdr->Pe32Plus.OptionalHeader.SizeOfHeaders;
context->EntryPoint = PEHdr->Pe32Plus.OptionalHeader.AddressOfEntryPoint;
context->RelocDir = &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC];
context->NumberOfRvaAndSizes = PEHdr->Pe32Plus.OptionalHeader.NumberOfRvaAndSizes;
context->NumberOfSections = PEHdr->Pe32.FileHeader.NumberOfSections;
context->FirstSection = (EFI_IMAGE_SECTION_HEADER *)((char *)PEHdr + PEHdr->Pe32.FileHeader.SizeOfOptionalHeader + sizeof(UINT32) + sizeof(EFI_IMAGE_FILE_HEADER));
context->SecDir = (EFI_IMAGE_DATA_DIRECTORY *) &PEHdr->Pe32Plus.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY];
if (context->SecDir->VirtualAddress >= datasize) {
Print(L"Malformed security header\n");
return EFI_INVALID_PARAMETER;
}
if (context->SecDir->Size == 0) {
Print(L"Empty security header\n");
return EFI_INVALID_PARAMETER;
}
return EFI_SUCCESS;
}
/*
* Once the image has been loaded it needs to be validated and relocated
*/
static EFI_STATUS handle_grub (void *data, unsigned int datasize,
EFI_LOADED_IMAGE *li)
{
EFI_STATUS efi_status;
char *buffer;
int i, size;
EFI_IMAGE_SECTION_HEADER *Section;
char *base, *end;
PE_COFF_LOADER_IMAGE_CONTEXT context;
efi_status = read_header(data, datasize, &context);
if (efi_status != EFI_SUCCESS) {
Print(L"Failed to read header\n");
return efi_status;
}
if (secure_mode ()) {
efi_status = verify_buffer(data, datasize, &context, 0);
if (efi_status != EFI_SUCCESS) {
Print(L"Verification failed\n");
return efi_status;
}
}
buffer = AllocatePool(context.ImageSize);
if (!buffer) {
Print(L"Failed to allocate image buffer\n");
return EFI_OUT_OF_RESOURCES;
}
CopyMem(buffer, data, context.SizeOfHeaders);
Section = context.FirstSection;
for (i = 0; i < context.NumberOfSections; i++) {
size = Section->Misc.VirtualSize;
if (size > Section->SizeOfRawData)
size = Section->SizeOfRawData;
base = ImageAddress (buffer, context.ImageSize, Section->VirtualAddress);
end = ImageAddress (buffer, context.ImageSize, Section->VirtualAddress + size - 1);
if (!base || !end) {
Print(L"Invalid section size\n");
return EFI_UNSUPPORTED;
}
if (Section->SizeOfRawData > 0)
CopyMem(base, data + Section->PointerToRawData, size);
if (size < Section->Misc.VirtualSize)
ZeroMem (base + size, Section->Misc.VirtualSize - size);
Section += 1;
}
efi_status = relocate_coff(&context, buffer);
if (efi_status != EFI_SUCCESS) {
Print(L"Relocation failed\n");
FreePool(buffer);
return efi_status;
}
entry_point = ImageAddress(buffer, context.ImageSize, context.EntryPoint);
li->ImageBase = buffer;
li->ImageSize = context.ImageSize;
if (!entry_point) {
Print(L"Invalid entry point\n");
FreePool(buffer);
return EFI_UNSUPPORTED;
}
return EFI_SUCCESS;
}
static EFI_STATUS generate_path(EFI_LOADED_IMAGE *li, EFI_DEVICE_PATH **grubpath, CHAR16 **PathName)
{
EFI_DEVICE_PATH *devpath;
EFI_HANDLE device;
int i;
unsigned int pathlen = 0;
EFI_STATUS efi_status = EFI_SUCCESS;
CHAR16 *bootpath;
device = li->DeviceHandle;
devpath = li->FilePath;
bootpath = DevicePathToStr(devpath);
pathlen = StrLen(bootpath);
for (i=pathlen; i>0; i--) {
if (bootpath[i] == '\\')
break;
}
bootpath[i+1] = '\0';
if (bootpath[i-i] == '\\')
bootpath[i] = '\0';
*PathName = AllocatePool(StrSize(bootpath) + StrSize(SECOND_STAGE));
if (!*PathName) {
Print(L"Failed to allocate path buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
*PathName[0] = '\0';
StrCat(*PathName, bootpath);
StrCat(*PathName, SECOND_STAGE);
*grubpath = FileDevicePath(device, *PathName);
error:
return efi_status;
}
/*
* Locate the second stage bootloader and read it into a buffer
*/
static EFI_STATUS load_grub (EFI_LOADED_IMAGE *li, void **data,
int *datasize, CHAR16 *PathName)
{
EFI_GUID simple_file_system_protocol = SIMPLE_FILE_SYSTEM_PROTOCOL;
EFI_GUID file_info_id = EFI_FILE_INFO_ID;
EFI_STATUS efi_status;
EFI_HANDLE device;
EFI_FILE_INFO *fileinfo = NULL;
EFI_FILE_IO_INTERFACE *drive;
EFI_FILE *root, *grub;
UINTN buffersize = sizeof(EFI_FILE_INFO);
device = li->DeviceHandle;
efi_status = uefi_call_wrapper(BS->HandleProtocol, 3, device,
&simple_file_system_protocol, &drive);
if (efi_status != EFI_SUCCESS) {
Print(L"Failed to find fs\n");
goto error;
}
efi_status = uefi_call_wrapper(drive->OpenVolume, 2, drive, &root);
if (efi_status != EFI_SUCCESS) {
Print(L"Failed to open fs\n");
goto error;
}
efi_status = uefi_call_wrapper(root->Open, 5, root, &grub, PathName,
EFI_FILE_MODE_READ, 0);
if (efi_status != EFI_SUCCESS) {
Print(L"Failed to open %s - %lx\n", PathName, efi_status);
goto error;
}
fileinfo = AllocatePool(buffersize);
if (!fileinfo) {
Print(L"Unable to allocate file info buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
efi_status = uefi_call_wrapper(grub->GetInfo, 4, grub, &file_info_id,
&buffersize, fileinfo);
if (efi_status == EFI_BUFFER_TOO_SMALL) {
fileinfo = AllocatePool(buffersize);
if (!fileinfo) {
Print(L"Unable to allocate file info buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
efi_status = uefi_call_wrapper(grub->GetInfo, 4, grub,
&file_info_id, &buffersize,
fileinfo);
}
if (efi_status != EFI_SUCCESS) {
Print(L"Unable to get file info\n");
goto error;
}
buffersize = fileinfo->FileSize;
*data = AllocatePool(buffersize);
if (!*data) {
Print(L"Unable to allocate file buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
efi_status = uefi_call_wrapper(grub->Read, 3, grub, &buffersize,
*data);
if (efi_status == EFI_BUFFER_TOO_SMALL) {
FreePool(*data);
*data = AllocatePool(buffersize);
efi_status = uefi_call_wrapper(grub->Read, 3, grub,
&buffersize, *data);
}
if (efi_status != EFI_SUCCESS) {
Print(L"Unexpected return from initial read: %x, buffersize %x\n", efi_status, buffersize);
goto error;
}
*datasize = buffersize;
return EFI_SUCCESS;
error:
if (*data) {
FreePool(*data);
*data = NULL;
}
if (PathName)
FreePool(PathName);
if (fileinfo)
FreePool(fileinfo);
return efi_status;
}
EFI_STATUS shim_verify (void *buffer, UINT32 size)
{
EFI_STATUS status;
PE_COFF_LOADER_IMAGE_CONTEXT context;
if (!secure_mode())
return EFI_SUCCESS;
status = read_header(buffer, size, &context);
if (status != EFI_SUCCESS)
return status;
status = verify_buffer(buffer, size, &context, 1);
return status;
}
EFI_STATUS init_grub(EFI_HANDLE image_handle)
{
EFI_STATUS efi_status;
EFI_HANDLE grub_handle = NULL;
EFI_LOADED_IMAGE *li, li_bak;
EFI_DEVICE_PATH *grubpath;
CHAR16 *PathName;
EFI_GUID loaded_image_protocol = LOADED_IMAGE_PROTOCOL;
void *data = NULL;
int datasize;
efi_status = uefi_call_wrapper(BS->HandleProtocol, 3, image_handle,
&loaded_image_protocol, &li);
if (efi_status != EFI_SUCCESS) {
Print(L"Unable to init protocol\n");
return efi_status;
}
efi_status = generate_path(li, &grubpath, &PathName);
if (efi_status != EFI_SUCCESS) {
Print(L"Unable to generate grub path\n");
goto done;
}
efi_status = uefi_call_wrapper(BS->LoadImage, 6, FALSE, image_handle,
grubpath, NULL, 0, &grub_handle);
if (efi_status == EFI_SUCCESS) {
/* Image validates - start it */
Print(L"Starting file via StartImage\n");
efi_status = uefi_call_wrapper(BS->StartImage, 3, grub_handle, NULL,
NULL);
uefi_call_wrapper(BS->UnloadImage, 1, grub_handle);
goto done;
}
efi_status = load_grub(li, &data, &datasize, PathName);
if (efi_status != EFI_SUCCESS) {
Print(L"Failed to load grub\n");
goto done;
}
CopyMem(&li_bak, li, sizeof(li_bak));
efi_status = handle_grub(data, datasize, li);
if (efi_status != EFI_SUCCESS) {
Print(L"Failed to load grub\n");
CopyMem(li, &li_bak, sizeof(li_bak));
goto done;
}
efi_status = uefi_call_wrapper(entry_point, 3, image_handle, systab);
CopyMem(li, &li_bak, sizeof(li_bak));
done:
return efi_status;
}
EFI_STATUS efi_main (EFI_HANDLE image_handle, EFI_SYSTEM_TABLE *passed_systab)
{
EFI_GUID shim_lock_guid = SHIM_LOCK_GUID;
static SHIM_LOCK shim_lock_interface;
EFI_HANDLE handle = NULL;
EFI_STATUS efi_status;
shim_lock_interface.Verify = shim_verify;
systab = passed_systab;
InitializeLib(image_handle, systab);
uefi_call_wrapper(BS->InstallProtocolInterface, 4, &handle,
&shim_lock_guid, EFI_NATIVE_INTERFACE,
&shim_lock_interface);
efi_status = init_grub(image_handle);
uefi_call_wrapper(BS->UninstallProtocolInterface, 3, handle,
&shim_lock_guid, &shim_lock_interface);
return efi_status;
}
<file_sep>/shim.h
#define SHIM_LOCK_GUID \
{ 0x605dab50, 0xe046, 0x4300, {0xab, 0xb6, 0x3d, 0xd8, 0x10, 0xdd, 0x8b, 0x23} }
INTERFACE_DECL(_SHIM_LOCK);
typedef
EFI_STATUS
(*EFI_SHIM_LOCK_VERIFY) (
IN VOID *buffer,
IN UINT32 size
);
typedef struct _SHIM_LOCK {
EFI_SHIM_LOCK_VERIFY Verify;
} SHIM_LOCK;
<file_sep>/Makefile
ARCH = $(shell uname -m | sed s,i[3456789]86,ia32,)
SUBDIRS = Cryptlib
LIB_PATH = /usr/lib64
EFI_INCLUDE = /usr/include/efi
EFI_INCLUDES = -nostdinc -ICryptlib -ICryptlib/Include -I$(EFI_INCLUDE) -I$(EFI_INCLUDE)/$(ARCH) -I$(EFI_INCLUDE)/protocol
EFI_PATH = /usr/lib64/gnuefi
LIB_GCC = $(shell $(CC) -print-libgcc-file-name)
EFI_LIBS = -lefi -lgnuefi --start-group Cryptlib/libcryptlib.a Cryptlib/OpenSSL/libopenssl.a --end-group $(LIB_GCC)
EFI_CRT_OBJS = $(EFI_PATH)/crt0-efi-$(ARCH).o
EFI_LDS = $(EFI_PATH)/elf_$(ARCH)_efi.lds
CFLAGS = -ggdb -O0 -fno-stack-protector -fno-strict-aliasing -fpic -fshort-wchar \
-Wall -mno-red-zone \
$(EFI_INCLUDES)
ifeq ($(ARCH),x86_64)
CFLAGS += -DEFI_FUNCTION_WRAPPER
endif
ifneq ($(origin VENDOR_CERT_FILE), undefined)
CFLAGS += -DVENDOR_CERT_FILE=\"$(VENDOR_CERT_FILE)\"
endif
LDFLAGS = -nostdlib -znocombreloc -T $(EFI_LDS) -shared -Bsymbolic -L$(EFI_PATH) -L$(LIB_PATH) -LCryptlib -LCryptlib/OpenSSL $(EFI_CRT_OBJS)
VERSION = 0.1
TARGET = shim.efi
OBJS = shim.o cert.o
SOURCES = shim.c shim.h signature.h PeImage.h
all: $(TARGET)
shim.o: $(SOURCES)
cert.o : cert.S
$(CC) $(CFLAGS) -c -o $@ $<
shim.so: $(OBJS) Cryptlib/libcryptlib.a Cryptlib/OpenSSL/libopenssl.a cert.o
$(LD) -o $@ $(LDFLAGS) $^ $(EFI_LIBS)
Cryptlib/libcryptlib.a:
$(MAKE) -C Cryptlib
Cryptlib/OpenSSL/libopenssl.a:
$(MAKE) -C Cryptlib/OpenSSL
%.efi: %.so
objcopy -j .text -j .sdata -j .data \
-j .dynamic -j .dynsym -j .rel \
-j .rela -j .reloc -j .eh_frame \
--target=efi-app-$(ARCH) $^ $@
objcopy -j .text -j .sdata -j .data \
-j .dynamic -j .dynsym -j .rel \
-j .rela -j .reloc -j .eh_frame \
-j .debug_info -j .debug_abbrev -j .debug_aranges \
-j .debug_line -j .debug_str -j .debug_ranges \
--target=efi-app-$(ARCH) $^ shim.efi.debug
clean:
$(MAKE) -C Cryptlib clean
$(MAKE) -C Cryptlib/OpenSSL clean
rm -f $(TARGET) $(OBJS)
GITTAG = $(VERSION)
test-archive:
@rm -rf /tmp/shim-$(VERSION) /tmp/shim-$(VERSION)-tmp
@mkdir -p /tmp/shim-$(VERSION)-tmp
@git archive --format=tar $(shell git branch | awk '/^*/ { print $$2 }') | ( cd /tmp/shim-$(VERSION)-tmp/ ; tar x )
@git diff | ( cd /tmp/shim-$(VERSION)-tmp/ ; patch -s -p1 -b -z .gitdiff )
@mv /tmp/shim-$(VERSION)-tmp/ /tmp/shim-$(VERSION)/
@dir=$$PWD; cd /tmp; tar -c --bzip2 -f $$dir/shim-$(VERSION).tar.bz2 shim-$(VERSION)
@rm -rf /tmp/shim-$(VERSION)
@echo "The archive is in shim-$(VERSION).tar.bz2"
archive:
git tag $(GITTAG) refs/heads/master
@rm -rf /tmp/shim-$(VERSION) /tmp/shim-$(VERSION)-tmp
@mkdir -p /tmp/shim-$(VERSION)-tmp
@git archive --format=tar $(GITTAG) | ( cd /tmp/shim-$(VERSION)-tmp/ ; tar x )
@mv /tmp/shim-$(VERSION)-tmp/ /tmp/shim-$(VERSION)/
@dir=$$PWD; cd /tmp; tar -c --bzip2 -f $$dir/shim-$(VERSION).tar.bz2 shim-$(VERSION)
@rm -rf /tmp/shim-$(VERSION)
@echo "The archive is in shim-$(VERSION).tar.bz2"
| 71072d1abba8b0600af2871a12d27fa463ad8816 | [
"C",
"Makefile"
] | 3 | C | canella/shim | bcd0a4e8df98f26b726fa9a18ad37b4bca16a285 | 53a7c44a85f14ca3d30dcac28644ea45adcd9e51 |
refs/heads/master | <repo_name>jdubx2/ingredient_network<file_sep>/supplements.r
node_lookup <- ingredient_nodes %>%
group_by(ing_type, ing_final) %>% summarise()
# write.csv(node_lookup, 'data/node_lookup.csv', row.names = F)
library(rvest)
library(stringr)
library(readxl)
xpath <- '/html/body/div[3]/div[2]/div/div/div[5]/div[1]/div/div[2]/div[2]/table'
url <- 'https://www.homebrewsupply.com/learn/homebrew-malt-comparison-chart.html'
df <- url %>%
read_html() %>%
html_nodes(xpath=xpath) %>%
html_table(header=T) %>% as.data.frame()
df <- df %>%
mutate(clean_name = tolower(Name))
# write.csv(df, 'data/grain_scrape.csv', row.names = F)
url2 <- 'https://www.brewersfriend.com/2008/09/14/hops-alpha-acid-table/'
xpath2 <- '//*[@id="post-169"]/table'
df2 <- url2 %>%
read_html() %>%
html_nodes(xpath = xpath2) %>%
html_table(header = T) %>% as.data.frame()
df2 <- df2 %>%
mutate(clean_name = tolower(Hops))
# write.csv(df2, 'data/hop_scrape.csv', row.names = F)
#---------------------------------------------------#
#add color scales to node rds file
ingredient_nodes <- readRDS('data/ingredient_nodes.rds')
#reset
ingredient_nodes <- select(ingredient_nodes, -c(srm, aa_group))
grain_colors <- read_excel('data/node_color_master.xlsx', sheet = 'grains')
hop_colors <- read_excel('data/node_color_master.xlsx', sheet = 'hops')
ingredient_nodes <- ingredient_nodes %>%
left_join(select(grain_colors, ing_final, srm), by = 'ing_final') %>%
left_join(select(hop_colors, aa_group, ing_final), by = 'ing_final')
#check completeness
ingredient_nodes %>%
group_by(ing_type) %>% summarise(aa = sum(aa_group), srm = sum(SRM))
saveRDS(ingredient_nodes, 'data/ingredient_nodes.rds')
############################################################
#old
ingredient_edges <- readRDS('data/ingredient_edges.rds')
ingredient_nodes <- readRDS('data/ingredient_nodes.rds')
ingredient_edges <- rename(ingredient_edges, source = V1, target = V2, value = count)
ingredient_nodes <- rename(ingredient_nodes, id = ing_final, value = count)
###
#new#
saveRDS(ingredient_nodes, 'data/ingredient_nodes2.rds')
saveRDS(ingredient_edges, 'data/ingredient_edges2.rds')
<file_sep>/app.R
library(shiny)
library(dplyr)
library(jsonlite)
ingredient_edges <- readRDS('data/ingredient_edges2.rds')
ingredient_nodes <- readRDS('data/ingredient_nodes2.rds')
ui <- fluidPage(
tags$head(HTML(
"<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src='https://www.googletagmanager.com/gtag/js?id=UA-92041039-2'></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-92041039-2');
</script>"
)),
tags$script(src="https://d3js.org/d3.v4.min.js"),
tags$script(src ="d3-scale-chromatic.v1.min.js"),
tags$script(src="d3_tip.js"),
tags$link(rel="stylesheet", type="text/css", href="styles.css"),
selectInput("style_input", "",
choices=unique(ingredient_nodes$style)),
div(id = "div_graph",
tags$script(src="graph.js"))
)
server <- function(input, output, session) {
update_json <- eventReactive(input$style_input,{
nodes <- filter(ingredient_nodes, style == input$style_input) %>% ungroup()
links <- filter(ingredient_edges, style == input$style_input) %>% ungroup()
link_filter <- bind_rows(mutate(links, index = row_number()) %>%
select(node = source, value, index),
mutate(links, index = row_number()) %>%
select(node = target, value, index)) %>%
group_by(node) %>% arrange(node, desc(value)) %>% slice(1:4)
links <- filter(links, row_number() %in% unique(link_filter$index))
link_filter <- bind_rows(mutate(links, index = row_number()) %>%
select(node = source, value, index),
mutate(links, index = row_number()) %>%
select(node = target, value, index)) %>%
group_by(node) %>% arrange(node, desc(value)) %>% filter(row_number() > 15)
links <- filter(links, !(row_number() %in% unique(link_filter$index)))
node_filter <- unique(c(unique(links$target), unique(links$source)))
nodes <- filter(nodes, id %in% node_filter)
update_json <- toJSON(list(nodes = nodes,
links = links))
})
observe(session$sendCustomMessage(type="init", update_json()))
}
shinyApp(ui = ui, server = server)
<file_sep>/www/graph.js
function range(start, stop, step){
var a=[start], b=start;
while(b<stop){b+=step;a.push(b)}
return a;
};
var margin = {top: 70, right:20, bottom: 20, left: 20},
width = $(window).width() * .9 - margin.left - margin.right,
height = $(window).height() * .9 - margin.top - margin.bottom
var nodeSize = d3.scaleLinear().range([5,20]);
var edgeSize = d3.scaleLinear().range([1,8]);
var hopColor = d3.scaleSequential(d3.interpolateGreens)
.domain([-1,8]);
var grainColor = d3.scaleThreshold()
.domain([0,3,4,6,12,23,31,61,66,201,351,601,1000])
.range(["#ffff99","#ffff45","#ffe93e","#fed849","#ffa846","#d77f59","#94523a","#804541","#5b342f","#4c3b2b","#38302e","#31302c","#1b1a18"]);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }).distance(60))
.force("charge", d3.forceManyBody().strength(-60))
.force("center", d3.forceCenter((width + margin.left + margin.right) / 2, (height + margin.bottom) / 2));
var svg = d3.select('#div_graph')
.append('svg')
.attr('id', 'svg_graph')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('id', 'g_graph');
var legend_width = Math.min(width,600);
if(legend_width < 600){
var legend_trans = margin.left;
} else{
var legend_trans = margin.left + ((width-600) / 2) ;
}
var legend = d3.select('#svg_graph')
.append('g')
.attr('transform', 'translate(' + legend_trans + ',' + 20 + ')')
.attr('id', 'g_legend');
var legend_axis = d3.scaleLinear()
.domain([1,24])
.range([0,legend_width]);
//gradient defs
var svg_proper = d3.select('#svg_graph')
var grain_defs = svg_proper.append("defs").attr('id', 'grain_defs');
var hop_defs = svg_proper.append("defs").attr('id', 'hop_defs');
var yeast_defs = svg_proper.append("defs").attr('id', 'yeast_defs');
var hopsRadial = hop_defs.selectAll("radialGradient")
.data([1,2,3,4,5,6]).enter()
.append('radialGradient')
.attr("id", function(d,i){ return "h-gradient-radial-" + d;})
.attr("cx", '.25')
.attr('cy', '.25')
.attr('r', '.65');
hopsRadial.append("stop")
.attr("stop-color", function(d) {return hopColor(d-2);})
.attr("offset", "0%");
hopsRadial.append("stop")
.attr("stop-color", function(d) {return hopColor(d);})
.attr("offset", "40%");
hopsRadial.append("stop")
.attr("stop-color", function(d) {return hopColor(d+2);})
.attr("offset", "100%");
var grainsRadial = grain_defs.selectAll("radialGradient")
.data([0,3,4,6,12,23,31,61,66,201,351,601,1000]).enter()
.append('radialGradient')
.attr("id", function(d,i){ return "g-gradient-radial-" + i;})
.attr("cx", '.25')
.attr('cy', '.25')
.attr('r', '.65');
grainsRadial.append("stop")
.attr("stop-color", function(d,i) {return grainColor.range()[i-1];})
.attr("offset", "0%");
grainsRadial.append("stop")
.attr("stop-color", function(d) {return grainColor(d);})
.attr("offset", "40%");
grainsRadial.append("stop")
.attr("stop-color", function(d,i) {return grainColor.range()[i+1];})
.attr("offset", "100%");
var yeastRadial = yeast_defs.append('radialGradient')
.attr("id", "yeast-gradient")
.attr("cx", '.25')
.attr('cy', '.25')
.attr('r', '.65');
yeastRadial.append("stop")
.attr("stop-color", "#80bfff")
.attr("offset", "0%");
yeastRadial.append("stop")
.attr("stop-color", "#0080ff")
.attr("offset", "40%");
yeastRadial.append("stop")
.attr("stop-color", "#004080")
.attr("offset", "100%");
//legend variables
var circle_y = 15,
circle_r = 8,
text_y = 33,
text_sz = 9
header_sz = 12
legend_fill = 'white';
//grain legend
legend.selectAll("legend_circle")
.data(range(1,11,1)).enter()
.append("circle")
.attr('class', 'legend_circle')
.attr('cx', function(d) { return legend_axis(d);})
.attr('cy', circle_y)
.attr('r', circle_r)
.attr("fill", function(d,i) { return "url(#g-gradient-radial-" + (i+1) + ")";});
var grain_json = {"x" : range(1,11,1), "value" : ["2","3","5","11","22","30","60","65","200","350","600"]}
legend.selectAll("legend_text")
.data(grain_json.x).enter()
.append("text")
.attr('class', 'legend_text')
.attr('x', function(d,i) {return legend_axis(d);})
.attr('y', text_y)
.attr('font-size', text_sz)
.attr('fill', legend_fill)
.attr('text-anchor', 'middle')
.text(function(d,i){return grain_json.value[i];});
legend.append("text")
.attr('class', 'legend_header')
.attr('x', legend_axis(6))
.attr('y', 0)
.attr('font-size', header_sz)
.attr('font-weight', 'bold')
.attr('fill', legend_fill)
.attr('text-anchor', 'middle')
.text('Grains (SRM Value)');
//yeast legend
legend.append("circle")
.attr('class', 'legend_circle')
.attr('cx', legend_axis(15))
.attr('cy', circle_y)
.attr('r', circle_r)
.attr('fill', "url(#yeast-gradient)");
legend.append("text")
.attr('class', 'legend_text')
.attr('x', legend_axis(15))
.attr('y', text_y)
.attr('font-size', text_sz)
.attr('fill', legend_fill)
.attr('text-anchor', 'middle')
.text('All');
legend.append("text")
.attr('class', 'legend_header')
.attr('x', legend_axis(15))
.attr('y', 0)
.attr('font-size', header_sz)
.attr('font-weight', 'bold')
.attr('fill', legend_fill)
.attr('text-anchor', 'middle')
.text('Yeast');
//hops legend
legend.selectAll("legend_circle")
.data(range(19,24,1))
.enter().append("circle")
.attr('class', 'legend_circle')
.attr('cx', function(d) {return legend_axis(d);})
.attr('cy', circle_y)
.attr('r', circle_r)
.attr('fill', function(d,i) {return "url(#h-gradient-radial-" + (i+1) + ")";});
var hops_json = {"x" : range(19,24,1), "value" : ["2-5","5-8","8-10","10-13","13-15","15-20"]}
legend.selectAll("legend_text")
.data(hops_json.x).enter()
.append("text")
.attr('class', 'legend_text')
.attr('x', function(d,i) {return legend_axis(d);})
.attr('y', text_y)
.attr('font-size', text_sz)
.attr('fill', legend_fill)
.attr('text-anchor', 'middle')
.text(function(d,i){return hops_json.value[i];});
legend.append("text")
.attr('class', 'legend_header')
.attr('x', legend_axis(21.5))
.attr('y', 0)
.attr('font-size', header_sz)
.attr('font-weight', 'bold')
.attr('fill', legend_fill)
.attr('text-anchor', 'middle')
.text('Hops (Alpha Acid %)');
Shiny.addCustomMessageHandler("init",
function(data){
console.log(data);
svg.selectAll(".lines")
.transition()
.duration(400)
.style("stroke-width", 0)
.remove();
svg.selectAll(".circles")
.transition()
.duration(750)
.attr('r', 0)
.remove();
var edgeCounts = [];
data.links.forEach(function(d,i) {edgeCounts.push(d['value']);});
var edgeRange = d3.extent(edgeCounts);
edgeSize.domain([edgeRange[0], edgeRange[1]]);
var nodeCounts = [];
data.nodes.forEach(function(d,i) {nodeCounts.push(d['value']);});
var nodeRange = d3.extent(nodeCounts);
nodeSize.domain([nodeRange[0], nodeRange[1]]);
var tool_tip = d3.tip()
.attr("class", "d3-tip")
.offset([-8, 0])
.html(function(d,i) { return d; });
svg.call(tool_tip);
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(data.links)
.enter().append("line")
.attr('class', 'lines')
.attr("stroke-width", function(d) { return edgeSize(d.value); });
var colorPicker = function(type, aa, srm){
if (type == 'Grain'){
return "url(#g-gradient-radial-" + grainColor.range().indexOf(grainColor(srm)) + ")";
} else if (type == 'Hops') {
return "url(#h-gradient-radial-" + aa + ")";
} else {
return "url(#yeast-gradient)";
}
}
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(data.nodes)
.enter().append("circle")
.attr('class','circles')
.attr("r", 0)
.attr("r", function(d) {return nodeSize(d.value); })
.attr("fill", function(d) { return colorPicker(d.ing_type, d.aa_group, d.srm); })
.on('mouseover', function(d,i) {
tool_tip.show(d.id);})
.on('mouseout', function(d,i) {
tool_tip.hide(d.id);})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("title")
.text(function(d) { return d.id; });
simulation.restart();
simulation.alpha(.5).alphaTarget(0);
simulation
.nodes(data.nodes)
.on("tick", ticked);
simulation.force("link")
.links(data.links);
function ticked() {
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node
// .attr("cx", function(d) { return d.x; })
// .attr("cy", function(d) { return d.y; });
.attr("cx", function(d) { return d.x = Math.max(nodeSize(d.value), Math.min(width - nodeSize(d.value), d.x)); })
.attr("cy", function(d) { return d.y = Math.max(nodeSize(d.value), Math.min(height - nodeSize(d.value), d.y)); });
}
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
| 6e2d3cd31537b49d9e530ddd87346bfa5c400dd8 | [
"JavaScript",
"R"
] | 3 | R | jdubx2/ingredient_network | 207bd6d6998a67ff5c31edb8202009aee490ddd3 | e3b29ee2264f268be3ac47375c226c95a5d1df06 |
refs/heads/master | <file_sep># PKU Hole
* [PKU Hole](#pku-hole)
* [General Usage](#general-usage)
* [Demo](#demo)
This is a package to read PKU Hole.
You can play with it in python's interactive mode.
PKU Hole is a place for PKU students to share their ideas anonymously.
## General Usage
+ All the functions you will need are in `pkuhole.ui`
+ Run `get_list()` to fetch a new list of messages.
+ Run `get_entry(pid)` to see the comments below a certain message.
+ Run `show_debug_info(True)` to see the debug information, which is turned off by defualt.
+ If you are using [iterm2](https://www.iterm2.com/index.html) on macOS, you can see inline images by running `show_inline_image(True)`, which is turned off by default.
## Demo

Have fun.
<file_sep>__all__ = ['ui', 'utils']
<file_sep>from . import utils
def show_debug_info(show_debug):
utils.set_SHOW_DEBUG(show_debug)
def show_inline_image(show_inline_image):
utils.set_SHOW_INLINE_IMAGE(show_inline_image)
def get_list(page_num = 1):
params = {'action': 'getlist', 'p': str(page_num)}
entrys = utils.get_responds(params)
if entrys == None:
return
for msg in entrys['data']:
print('-----------------------------------')
utils.show_op_data(msg)
def get_entry(pid):
params = {'action': 'getcomment', 'pid': str(pid)}
comments = utils.get_responds(params)
params = {'action': 'getone', 'pid': str(pid)}
op = utils.get_responds(params)
if comments == None or op == None:
return
print('-----------------------------------')
utils.show_op_data(op['data'])
for comment in comments['data']:
print('...................................')
utils.show_comment_entry(comment)<file_sep>from urllib.request import urlopen
import termcolor
import base64
import json
SHOW_DEBUG = False
SHOW_INLINE_IMAGE = False
url = 'http://pkuhelper.pku.edu.cn/services/pkuhole'
def set_SHOW_DEBUG(show_debug):
global SHOW_DEBUG
SHOW_DEBUG = show_debug
def set_SHOW_INLINE_IMAGE(show_img):
global SHOW_INLINE_IMAGE
SHOW_INLINE_IMAGE = show_img
def add_params(url, params):
newurl = url + '?'
for k, v in params.items():
newurl += k + '=' + v + '&'
newurl = newurl[:-1]
return newurl
def get_responds(params):
global SHOW_DEBUG
list_url = add_params(url + '/api.php', params)
if SHOW_DEBUG:
print(list_url)
try:
js = urlopen(list_url)
js = json.load(js)
except:
termcolor.cprint('Failed to get responds',color='red')
return None
return js
def get_image(filename):
'''
fetch the content of the required image
:param filename: image filename, usually stored in the 'url' field
:return: the content of the required image
'''
img_url = url + '/images/' + filename
if SHOW_DEBUG:
print(img_url)
try:
img = urlopen(img_url)
img = img.read()
except:
termcolor.cprint('Failed to load image',color='red')
return None
return img
def show_op_data(op_data):
'''
show the msg of the original poster
:param op_data: the 'data' feild of the original poster's decoded json
:return: no return
'''
print(op_data['pid'])
print(op_data['text'])
if SHOW_INLINE_IMAGE:
if op_data['url'] is not '':
op_img = get_image(op_data['url'])
if op_img is not None:
show_image(op_img)
print('Reply: {0}, Likes: {1}'.format(op_data['reply'], op_data['likenum']))
def show_comment_entry(comment):
'''
print a single entry in comments
:param comment: the single entry of comments to print
:return: no return
'''
print('#{0}'.format(comment['cid']))
print(comment['text'])
def show_image(img_content, inline = 1, **kwargs):
'''
Show inline image in iTerm2
:param img_content: the content of the image
:param kwargs:
name base-64 encoded filename. Defaults to "Unnamed file".
size File size in bytes. Optional; this is only used by the progress indicator.
width Width to render. See notes below.
height Height to render. See notes below.
preserveAspectRatio If set to 0, then the image's inherent aspect ratio will not be respected;
otherwise, it will fill the specified width and height as much as possible
without stretching. Defaults to 1.
inline If set to 1, the file will be displayed inline. Otherwise, it will be downloaded with
no visual representation in the terminal session. Defaults to 0.
The width and height are given as a number followed by a unit, or the word "auto".
+ N: N character cells.
+ Npx: N pixels.
+ N%: N percent of the session's width or height.
+ auto: The image's inherent size will be used to determine an appropriate dimension.
:return: no return
'''
img_encoded = base64.b64encode(img_content).decode('utf8')
protocol_str = '\033]1337;File='
opt_args = 'inline=' + str(inline)
for k,v in kwargs.items():
opt_args += ';' + k + '=' + v
protocol_str += opt_args
protocol_str += ':' + img_encoded
protocol_str += '\a'
print(protocol_str)
| b303ccceb9b7db4d555de0ac03fb8b1156b39e23 | [
"Markdown",
"Python"
] | 4 | Markdown | moulai/pkuhole | c311cd52111da7f46de27650793ea2078f7ab9bf | 5b8b4d60ff9b3644a54512d03029502ab45926c6 |
refs/heads/master | <file_sep><?php
$station = file_get_contents("http://cloud.tfl.gov.uk/TrackerNet/PredictionDetailed/{$_GET['id']}/{$_GET['station']}");
$simpleXml = simplexml_load_string($station);
$json = json_encode($simpleXml);
echo $json;
?><file_sep><h3 class="center">Upcoming Events</h3>
<?php
$args = array (
'post_type' => 'tribe_events',
'posts_per_page' => '5',
'tax_query' => array(
array(
'taxonomy' => 'tribe_events_cat',
'field' => 'slug',
'terms' => array('london-thinks'),
)
)
);
$event_posts = new WP_Query( $args );
if ( $event_posts->have_posts() ) : while ( $event_posts->have_posts() ) : $event_posts->the_post();
?>
<div <?php post_class('row listing'); ?> itemscope itemtype="http://schema.org/Event">
<div class="small-12 large-12 columns ">
<div class="postdata">
<h6 class="tribe-events-single-section-title"><?php echo tribe_get_organizer() ?> presents: </h6>
<h3 itemprop="name" class="page-title"><a href="<?php the_permalink(); ?>" rel="permalink" itemprop="url" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h3>
<a href="https://plus.google.com/+ConwayhallOrgUk1929" rel="publisher"></a>
<h6><?php echo tribe_events_event_schedule_details(); ?></h6>
<?php if ( tribe_get_cost() ) : ?>
<div class="tribe-events-event-cost">
<span><?php echo tribe_get_cost( null, true ); ?></span>
</div>
<?php endif; ?>
<?php global $post; $free = get_post_meta( $post->ID, '_cmb_free', true ); if( $free == 'on' ) : ?>
<div class="tribe-events-event-cost">
<span>Free</span>
</div>
<?php endif; ?>
<?php global $post; $tix = get_post_meta( $post->ID, '_cmb_tickets', true ); if( $tix != '' ) : ?>
<div class="tribe-events-event-cost">
<span>
<?php global $post; $tix = get_post_meta( $post->ID, '_cmb_tickets', true ); echo $tix; ?>
</span>
</div>
<?php endif; ?>
<meta itemprop="url" content="<?php the_permalink(); ?>">
<meta itemprop="description" content="<?php echo(get_the_excerpt()); ?>">
<meta itemprop="startDate" content="<?php echo tribe_get_start_date( $post->ID, false, 'c' ); ?>">
<meta itemprop="endDate" content="<?php echo tribe_get_end_date( $post->ID, false, 'c' ); ?>">
<span class="updated dtstart" datetime="<?php the_date( 'c' ); ?>"><?php the_time('D, jS M, Y'); ?></span>
</div>
<div class="row">
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-calendar" aria-hidden="true"></i> View "<?php the_title(); ?>"</a></p>
<span itemprop="location" itemscope itemtype="http://schema.org/Place" class="location vcard">
<meta itemprop="name" content="<NAME>" />
<span itemprop="address" itemscope itemtype="http://schema.org/PostalAddress" class="adr">
<meta itemprop="streetAddress" content="25 Red Lion Square" class="locality" />
<meta itemprop="addressLocality" content="London" />
<meta itemprop="postalCode" content="WC1R 4RL" />
</span>
</span>
<div class="callout secondary">
<div class="row">
<div class="small-12 large-6 columns eventCategory">
<?php echo tribe_get_event_categories(); ?>
</div>
<div class="small-12 large-6 columns">
<div>Organiser:</div>
<ul class="tribe-event-categories">
<li><span class="vcard author"><span class="fn"><?php echo tribe_get_organizer_link() ?></span></span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
endwhile;
endif;
?>
<div class="row">
<div class="small-12 columns">
<p><a href="<?php echo tribe_get_events_link() ?>" class="button"><?php _e( '<i aria-hidden="true" class="ch-calendar"></i> All Events', 'tribe-events-calendar' ) ?></a></p>
</div>
</div><file_sep><?php
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'post_parent' => get_the_ID(),
'order' => 'ASC',
'orderby' => 'menu_order'
);
$hire = new WP_Query( $args );
if ( $hire->have_posts() ) : while ( $hire->have_posts() ) : $hire->the_post();
?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns">
<h4 itemprop="name"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h4>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> View <?php the_title(); ?></a></p>
</div>
</div>
<?php
endwhile;
endif;
wp_reset_query();
?><file_sep><?php global $post; $issue = get_post_meta( $post->ID, '_cmb_issue', true ); if( $issue != '' ) : ?>
<p><a href="<?php global $post; $issue = get_post_meta( $post->ID, '_cmb_issue', true ); echo $issue; ?>" class="button"><i class="ch-download" aria-hidden="true"></i> Download PDF version of <?php the_title(); ?></a></p>
<?php else: ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> Read "<?php the_title(); ?>"</a></p>
<?php endif; ?><file_sep><?php get_header(); ?>
<div class="row">
<div class="small-12 large-9 columns main justify">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
date_default_timezone_set('Europe/London');
$start = get_post_meta( get_the_ID(), '_project_startdate', true );
$end = get_post_meta( get_the_ID(), '_project_enddate', true );
$ongoing = get_post_meta( get_the_ID(), '_project_ongoing', true );
$lead = get_post_meta( get_the_ID(), '_project_lead', true );
?>
<div itemscope itemtype="http://schema.org/Article">
<?php get_template_part('parts/global/post', 'meta'); ?>
<?php if(has_post_thumbnail()) { ?>
<figure itemprop="associatedMedia">
<span itemscope itemtype="http://schema.org/ImageObject">
<?php the_post_thumbnail('top', array('itemprop' => 'contentURL')); ?>
<?php if(get_post_meta(get_post_thumbnail_id(), 'owner', true) != '') { ?>
<figcaption>
Image Credit:
<span itemscope itemprop="author" itemtype="http://schema.org/Person">
<?php if(get_post_meta(get_post_thumbnail_id(), 'ownerurl', true) != '') { ?>
<a href="<?php echo get_post_meta(get_post_thumbnail_id(), 'ownerurl', true); ?>" target="_blank">
<?php } ?>
<span itemprop="name"><?php echo get_post_meta(get_post_thumbnail_id(), 'owner', true); ?></span>
<?php if(get_post_meta(get_post_thumbnail_id(), 'ownerurl', true) != '') { ?>
</a>
<?php } ?>
</span>
</figcaption>
<?php } ?>
</span>
</figure>
<?php } ?>
<h2 class="page-title" itemprop="name headline"><?php the_title(); ?></h2>
<?php get_template_part('parts/global/post', 'copyright'); ?>
<?php get_template_part('parts/jobs/related', 'meta'); ?>
<?php if($ongoing != ''){ ?>
<h6>Ongoing</h6>
<?php } else { ?>
<?php if($start != '' && $end != ''){ ?>
<h6>From: <?php echo date_i18n( 'jS F Y', $start ); ?> - <?php echo date_i18n( 'jS F Y', $end ); ?><?php if($today > $end){ echo ' (Project Ended)'; } ?></h6>
<?php } else { ?>
<?php if($start != ''){ ?>
<h6>Start Date: <?php echo date_i18n( 'jS F Y', $start ); ?></h6>
<?php } ?>
<?php if($end != ''){ ?>
<h6>End Date: <?php echo date_i18n( 'jS F Y', $end ); ?></h6>
<?php } ?>
<?php } ?>
<?php } ?>
<?php get_template_part('parts/ethicalrecord/ethical', 'record'); ?>
<?php get_template_part('parts/global/lecture', 'video'); ?>
<?php
if($lead != '') {
?>
<h6>Project led by: <?php echo $lead; ?></h6>
<?php
}
?>
<div itemprop="mainEntityOfPage">
<div itemprop="articleBody">
<?php the_content(); ?>
</div>
</div>
<?php get_template_part('parts/global/post', 'tags'); ?>
<?php get_template_part('parts/ethicalrecord/speaker', 'bio'); ?>
<?php get_template_part('parts/ethicalrecord/related', 'issue'); ?>
<?php get_template_part('parts/jobs/related', 'doc'); ?>
<div class="row">
<div class="small-12 large-6 columns postsnav left">
<?php previous_post_link('%link', '<i class="ch-chevron-left"></i> %title'); ?>
</div>
<div class="small-12 large-6 columns postsnav right">
<?php next_post_link('%link', '%title <i class="ch-chevron-right"></i>'); ?>
</div>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
<aside class="small-12 large-3 columns">
<?php get_template_part('sidebar'); ?>
</aside>
</div>
<?php get_footer(); ?><file_sep><?php
// Set content width value based on the theme's design
if ( ! isset( $content_width ) )
$content_width = 870;
// Register Theme Features
function ch_theme() {
add_theme_support( 'woocommerce' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'infinite-scroll', array(
'container' => 'content',
'footer' => 'page',
) );
set_post_thumbnail_size( 870, 250, array( 'center', 'top') );
add_image_size( 'top', 870, 500, array( 'center', 'top') );
add_image_size( 'carousel', 870, 250, array( 'center', 'top') );
add_image_size( 'related', 265, 199, array( 'center', 'center') );
add_image_size( 'squared', 265, 265, array( 'center', 'top') );
add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) );
add_theme_support( 'title-tag' );
add_editor_style( 'editor-style.css' );
load_theme_textdomain( 'ch', get_template_directory() . '/language' );
}
add_action( 'after_setup_theme', 'ch_theme' );
// Register Style
function ch_css() {
wp_register_style( 'grid', get_template_directory_uri() . '/css/grid.css', false, '6.3.0' );
wp_register_style( 'fonts', get_template_directory_uri() . '/css/fonts.css', false, '6.3.0' );
wp_enqueue_style( 'grid' );
wp_enqueue_style( 'fonts' );
}
add_action( 'wp_enqueue_scripts', 'ch_css' );
// Register JS
function ch_js() {
wp_deregister_script('jquery');
wp_enqueue_script( 'jq', get_template_directory_uri() . '/js/vendor/jquery.js', false, '2.2.4', true );
wp_enqueue_script( 'what', get_template_directory_uri() . '/js/vendor/what-input.js', false, '6.3.0', true );
wp_enqueue_script( 'foundation', get_template_directory_uri() . '/js/vendor/foundation.js', false, '6.3.0', true );
wp_enqueue_script( 'map', '//maps.google.com/maps/api/js', false, '7.2', true );
wp_enqueue_script( 'gmap', get_template_directory_uri() . '/js/vendor/map.js', false, '7.2', true );
wp_enqueue_script( 'app', get_template_directory_uri() . '/js/app.js', false, '6.3.0', true );
wp_enqueue_script( 'signalR', 'https://tfl.gov.uk/cdn/static/scripts/plugins/includes/jquery.signalR-2.2.0.min.js', false, '6.3.0', true );
wp_enqueue_script( 'hubs', get_template_directory_uri() . '/js/vendor/hubs.js', false, '6.3.0', true );
wp_enqueue_script( 'jq' );
wp_enqueue_script( 'what' );
wp_enqueue_script( 'foundation' );
wp_enqueue_script( 'app' );
}
add_action( 'wp_enqueue_scripts', 'ch_js' );
function maps() {
if ( is_page(array('Chancery Lane', 'Holborn Station', 'Russell Square', 'Santander Cycle Hire', 'Buses')) ) {
wp_enqueue_script('signalR');
wp_enqueue_script('hubs');
wp_enqueue_script('map');
wp_enqueue_script('gmap');
}
}
add_action('wp_enqueue_scripts', 'maps');
// Woocommerce
remove_action('woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action('woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
remove_action('woocommerce_before_main_content','woocommerce_breadcrumb', 20);
remove_action('woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
add_action('woocommerce_before_main_content', 'ch_container_start', 5);
add_action('woocommerce_before_main_content', 'ch_shop_start', 10);
add_action('woocommerce_after_main_content', 'ch_shop_end', 10);
add_action('woocommerce_after_main_content', 'ch_sidebar', 15);
add_action('woocommerce_after_main_content', 'ch_container_end', 20);
function ch_container_start() {
echo '<div class="row">';
}
function ch_shop_start() {
echo '<div class="small-12 large-9 columns main">';
}
function ch_shop_end() {
echo '</div>';
}
function ch_sidebar() {
echo '<aside class="small-12 large-3 columns">';
echo '<ul class="sidebar">';
dynamic_sidebar('woosidebar');
echo '</ul>';
echo '</aside>';
}
function ch_container_end() {
echo '</div>';
}
// Excerpts on pages
add_action( 'init', 'my_add_excerpts_to_pages' );
function my_add_excerpts_to_pages() {
add_post_type_support( 'page', 'excerpt' );
}
// Reading Time
function ch_reading() {
$post = get_post();
$words = str_word_count( strip_tags( $post->post_content ) );
$minutes = floor( $words / 200 );
$seconds = floor( $words % 200 / ( 200 / 60 ) );
if ( 1 <= $minutes ) {
$estimated_time = 'Estimated ' . $minutes . ' min read';
} else {
$estimated_time = 'Estimated ' . $seconds . ' sec read';
}
return $estimated_time;
}
function default_post_thumbnail( $html ) {
if ( '' == $html ) {
return '<img src="' . get_template_directory_uri() . '/images/ConwayHall.jpg" />';
}
return $html;
}
add_filter( 'post_thumbnail_html', 'default_post_thumbnail' );
// Sticky
function wpb_cpt_sticky_at_top( $posts ) {
if ( is_main_query() && is_post_type_archive() ) {
global $wp_query;
$sticky_posts = get_option( 'sticky_posts' );
$num_posts = count( $posts );
$sticky_offset = 0;
for ($i = 0; $i < $num_posts; $i++) {
if ( in_array( $posts[$i]->ID, $sticky_posts ) ) {
$sticky_post = $posts[$i];
array_splice( $posts, $i, 1 );
array_splice( $posts, $sticky_offset, 0, array($sticky_post) );
$sticky_offset++;
$offset = array_search($sticky_post->ID, $sticky_posts);
unset( $sticky_posts[$offset] );
}
}
if ( !empty( $sticky_posts) ) {
$stickies = get_posts( array(
'post__in' => $sticky_posts,
'post_type' => $wp_query->query_vars['post_type'],
'post_status' => 'publish',
'nopaging' => true
) );
foreach ( $stickies as $sticky_post ) {
array_splice( $posts, $sticky_offset, 0, array( $sticky_post ) );
$sticky_offset++;
}
}
}
return $posts;
}
add_filter( 'the_posts', 'wpb_cpt_sticky_at_top' );
function cpt_sticky_class($classes) {
if ( is_sticky() ) :
$classes[] = 'sticky featured';
return $classes;
endif;
return $classes;
}
add_filter('post_class', 'cpt_sticky_class');
add_filter( 'get_the_archive_title', function ($title) {
if ( is_category() ) {
$title = single_cat_title( '', false );
} elseif ( is_tag() ) {
$title = single_tag_title( '', false );
} elseif ( is_author() ) {
$title = '<span class="vcard">' . get_the_author() . '</span>' ;
} elseif ( is_post_type_archive() ) {
$title = sprintf( __( '%s' ), post_type_archive_title( '', false ) );
} elseif ( is_tax() ) {
$tax = get_taxonomy( get_queried_object()->taxonomy );
$title = sprintf( __( '%2$s' ), $tax->labels->singular_name, single_term_title( '', false ) );
}
return $title;
});
function add_sub_caps() {
global $wp_roles;
$role = get_role('member');
$role->add_cap('read_private_posts');
};
add_action ('admin_head','add_sub_caps');
add_filter( 'private_title_format', 'bl_remove_private_title' );
function bl_remove_private_title( $title ) {
return 'Members Area: %s';
}
function custom_excerpt_length( $length ) {
return 30;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
function new_excerpt_more( $more ) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
function ch_media_info( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'location', true );
$form_fields['owner'] = array(
'value' => $field_value ? $field_value : '',
'label' => __( 'Photo Owner' ),
'helps' => __( 'if set, a photo credit will be shown' )
);
$form_fields['ownerurl'] = array(
'value' => $field_value ? $field_value : '',
'label' => __( 'Photo Owner Website' ),
'helps' => __( 'if set, a photo credit link will be shown' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'ch_media_info', 10, 2 );
function my_save_attachment_location( $attachment_id ) {
if ( isset( $_REQUEST['attachments'][$attachment_id]['owner'] ) ) {
$owner = $_REQUEST['attachments'][$attachment_id]['owner'];
update_post_meta( $attachment_id, 'owner', $owner );
}
if ( isset( $_REQUEST['attachments'][$attachment_id]['ownerurl'] ) ) {
$ownerurl = $_REQUEST['attachments'][$attachment_id]['ownerurl'];
update_post_meta( $attachment_id, 'ownerurl', $ownerurl );
}
}
add_action( 'edit_attachment', 'my_save_attachment_location' );
function add_menu_icons_styles(){
echo '<style>
#adminmenu #menu-posts-carousel div.wp-menu-image:before, #dashboard_right_now .carousel-count a:before {
content: "\f233";
}
#adminmenu #menu-posts-people div.wp-menu-image:before, #dashboard_right_now .people-count a:before {
content: "\f307";
}
#adminmenu #menu-posts-jobs div.wp-menu-image:before, #dashboard_right_now .jobs-count a:before {
content: "\f484";
}
#adminmenu #menu-posts-sunday_concerts div.wp-menu-image:before, #dashboard_right_now .sunday_concerts-count a:before {
content: "\f127";
}
#dashboard_right_now .tribe_events-count a:before {
content: "\f145";
}
#dashboard_right_now .feedback-count a:before {
content: "\f175";
}
#dashboard_right_now .taxonomy-count a:before {
content: "\f325";
}
#adminmenu #menu-posts-pdf div.wp-menu-image:before, #dashboard_right_now .pdf-count a:before {
content: "\f497";
}
#adminmenu #menu-posts-product div.wp-menu-image:before, #dashboard_right_now .product-count a:before {
content: "\f174";
}
#adminmenu #menu-posts-memorial_lecture div.wp-menu-image:before, #dashboard_right_now .memorial_lecture-count a:before {
content: "\f473";
}
#adminmenu #menu-posts-amazon_product div.wp-menu-image:before, #dashboard_right_now .amazon_product-count a:before {
content: "\f174";
}
#adminmenu .menu-icon-speaker div.wp-menu-image:before {
content: "\f488";
}
#adminmenu .menu-icon-issue div.wp-menu-image:before {
content: "\f331";
}
#adminmenu .menu-icon-contacts div.wp-menu-image:before {
content: "\f336";
}
#adminmenu .menu-icon-ethicalrecord div.wp-menu-image:before {
content: "\f464";
}
#dashboard_right_now .speaker-count a:before {
content: "\f488";
}
#dashboard_right_now .issue-count a:before {
content: "\f331";
}
#dashboard_right_now .taxonomy-count a:before {
content: "\f325";
}
#dashboard_right_now .feedback-count a:before {
content: "\f466";
}
#dashboard_right_now .ethicalrecord-count a:before {
content: "\f464";
}
#dashboard_right_now .library_blog-count a:before {
content: "\f512";
}
</style>';
}
add_action( 'admin_head', 'add_menu_icons_styles' );
add_action( 'dashboard_glance_items', 'my_add_cpt_to_dashboard' );
function my_add_cpt_to_dashboard() {
$showTaxonomies = 1;
if ($showTaxonomies) {
$taxonomies = get_taxonomies( array( '_builtin' => false ), 'objects' );
foreach ( $taxonomies as $taxonomy ) {
$num_terms = wp_count_terms( $taxonomy->name );
$num = number_format_i18n( $num_terms );
$text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name, $num_terms );
$associated_post_type = $taxonomy->object_type;
if ( current_user_can( 'manage_categories' ) ) {
$output = '<a href="edit-tags.php?taxonomy=' . $taxonomy->name . '&post_type=' . $associated_post_type[0] . '">' . $num . ' ' . $text .'</a>';
}
echo '<li class="taxonomy-count">' . $output . ' </li>';
}
}
// Custom post types counts
$post_types = get_post_types( array( '_builtin' => false ), 'objects' );
foreach ( $post_types as $post_type ) {
if($post_type->show_in_menu==false) {
continue;
}
$num_posts = wp_count_posts( $post_type->name );
$num = number_format_i18n( $num_posts->publish );
$text = _n( $post_type->labels->singular_name, $post_type->labels->name, $num_posts->publish );
if ( current_user_can( 'edit_posts' ) ) {
$output = '<a href="edit.php?post_type=' . $post_type->name . '">' . $num . ' ' . $text . '</a>';
}
echo '<li class="page-count ' . $post_type->name . '-count">' . $output . '</td>';
}
}<file_sep>(function ($) {
$.fn.tooltip = function (options) {
var defaults = {
color: '#ffffff',
tipColor: '#000000'
};
var options = $.extend(defaults, options);
$(this).hover(
function () {
$(this).append($('<div class="tooltip" style="color:' + options.color + '; background-color:' + options.tipColor + ';">' + $(this).attr('title') + ' <div class="tip-bottom"></div></div>'));
}, function () {
$(this).find('.tooltip').remove();
});
};
})(jQuery);<file_sep>{
"name": "Balcony",
"options": [
{
"name": "Power",
"overlay": "power",
"icon": "ch-plug"
},
{
"name": "Fire Exits",
"overlay": "fire",
"icon": "ch-exit"
}
],
"rooms": [
{
"name": "Theatre",
"capacity": "150",
"overlay": "theatre"
}
]
}<file_sep><?php
$args = array (
'connected_type' => 'lectures2speakers',
'connected_items' => get_queried_object(),
'nopaging' => true,
);
$lecture_speaker = new WP_Query( $args );
$the_count = $lecture_speaker->found_posts;
if ( $lecture_speaker->have_posts() ) {
?>
<div class="metaData">
<a href="#bio" class="button"><i class="ch-chevron-down" aria-hidden="true"></i> More Info</a>
</div>
<?php
} else {
// no posts found
}
wp_reset_postdata();
?><file_sep><?php
require_once('wp-updates-theme.php');
new WPUpdatesThemeUpdater_1953( 'http://wp-updates.com/api/2/theme', basename( get_template_directory() ) );<file_sep><?php
$line = file_get_contents("http://countdown.tfl.gov.uk/stopBoard/{$_GET['stop']}/");
echo $line;
?><file_sep><?php
// Product Types Taxonomy
function type() {
$labels = array(
'name' => _x( 'Product Types', 'Taxonomy General Name', 'ch' ),
'singular_name' => _x( 'Product Type', 'Taxonomy Singular Name', 'ch' ),
'menu_name' => __( 'Product Types', 'ch' ),
'all_items' => __( 'All Types', 'ch' ),
'parent_item' => __( 'Parent Type', 'ch' ),
'parent_item_colon' => __( 'Parent Type:', 'ch' ),
'new_item_name' => __( 'New Type', 'ch' ),
'add_new_item' => __( 'Add New Type', 'ch' ),
'edit_item' => __( 'Edit Type', 'ch' ),
'update_item' => __( 'Update Types', 'ch' ),
'separate_items_with_commas' => __( 'Separate Types with commas', 'ch' ),
'search_items' => __( 'Search Types', 'ch' ),
'add_or_remove_items' => __( 'Add or remove Types', 'ch' ),
'choose_from_most_used' => __( 'Choose from the most used Types', 'ch' ),
'not_found' => __( 'Not Found', 'ch' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'type', array( 'amazon_product' ), $args );
}
// Hook into the 'init' action
add_action( 'init', 'type', 0 );
// Register Custom Jobs Taxonomy
function job_type() {
$labels = array(
'name' => _x( 'Job Types', 'Taxonomy General Name', 'ch' ),
'singular_name' => _x( 'Job Type', 'Taxonomy Singular Name', 'ch' ),
'menu_name' => __( 'Job Types', 'ch' ),
'all_items' => __( 'All Job Types', 'ch' ),
'parent_item' => __( 'Parent Job Type', 'ch' ),
'parent_item_colon' => __( 'Parent Job Type:', 'ch' ),
'new_item_name' => __( 'New Job Type', 'ch' ),
'add_new_item' => __( 'Add New Job Type', 'ch' ),
'edit_item' => __( 'Edit Job Type', 'ch' ),
'update_item' => __( 'Update Job Types', 'ch' ),
'separate_items_with_commas' => __( 'Separate Job Types with commas', 'ch' ),
'search_items' => __( 'Search Job Types', 'ch' ),
'add_or_remove_items' => __( 'Add or remove Job Types', 'ch' ),
'choose_from_most_used' => __( 'Choose from the most used Job Types', 'ch' ),
'not_found' => __( 'Not Found', 'ch' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'job_type', array( 'jobs' ), $args );
}
// Hook into the 'init' action
add_action( 'init', 'job_type', 0 );
add_filter( 'post_class', 'er_taxonomy_post_class', 10, 3 );
function er_taxonomy_post_class( $classes, $class, $ID ) {
$taxonomy = 'taxonomy';
$terms = get_the_terms( (int) $ID, $taxonomy );
if( !empty( $terms ) ) {
foreach( (array) $terms as $order => $term ) {
if( !in_array( $term->slug, $classes ) ) {
$classes[] = $term->slug;
}
}
}
return $classes;
}
// Register Project Taxonomy
function project_tax() {
$labels = array(
'name' => _x( 'Project Category', 'Taxonomy General Name', 'ch' ),
'singular_name' => _x( 'Project Category', 'Taxonomy Singular Name', 'ch' ),
'menu_name' => __( 'Project Category', 'ch' ),
'all_items' => __( 'All Project Categories', 'ch' ),
'parent_item' => __( 'Parent Project Category', 'ch' ),
'parent_item_colon' => __( 'Parent Project Category:', 'ch' ),
'new_item_name' => __( 'New Project Category', 'ch' ),
'add_new_item' => __( 'Add New Project Category', 'ch' ),
'edit_item' => __( 'Edit Project Category', 'ch' ),
'update_item' => __( 'Update Project Category', 'ch' ),
'separate_items_with_commas' => __( 'Separate Project Categories with commas', 'ch' ),
'search_items' => __( 'Search Project Category', 'ch' ),
'add_or_remove_items' => __( 'Add or remove Project Categories', 'ch' ),
'choose_from_most_used' => __( 'Choose from the most used Project Categories', 'ch' ),
'not_found' => __( 'Not Found', 'ch' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'project_category', array( 'project' ), $args );
}
add_action( 'init', 'project_tax', 0 );
// Register Page Tag Taxonomy
function page_tag() {
$labels = array(
'name' => _x( 'Tag', 'Taxonomy General Name', 'ch' ),
'singular_name' => _x( 'Tag', 'Taxonomy Singular Name', 'ch' ),
'menu_name' => __( 'Tags', 'ch' ),
'all_items' => __( 'All Tags', 'ch' ),
'parent_item' => __( 'Parent Tag', 'ch' ),
'parent_item_colon' => __( 'Parent Tag:', 'ch' ),
'new_item_name' => __( 'New Tag', 'ch' ),
'add_new_item' => __( 'Add New Tag', 'ch' ),
'edit_item' => __( 'Edit Tag', 'ch' ),
'update_item' => __( 'Update Tag', 'ch' ),
'separate_items_with_commas' => __( 'Separate Tags with commas', 'ch' ),
'search_items' => __( 'Search Tags', 'ch' ),
'add_or_remove_items' => __( 'Add or remove Tags', 'ch' ),
'choose_from_most_used' => __( 'Choose from the most used Tags', 'ch' ),
'not_found' => __( 'Not Found', 'ch' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'page_tag', array( 'page' ), $args );
}
add_action( 'init', 'page_tag', 0 );
// Register PDF Taxonomy
function pdf_tax() {
$labels = array(
'name' => _x( 'PDF Category', 'Taxonomy General Name', 'ch' ),
'singular_name' => _x( 'PDF Category', 'Taxonomy Singular Name', 'ch' ),
'menu_name' => __( 'PDF Category', 'ch' ),
'all_items' => __( 'All PDF Categories', 'ch' ),
'parent_item' => __( 'Parent PDF Category', 'ch' ),
'parent_item_colon' => __( 'Parent PDF Category:', 'ch' ),
'new_item_name' => __( 'New PDF Category', 'ch' ),
'add_new_item' => __( 'Add New PDF Category', 'ch' ),
'edit_item' => __( 'Edit PDF Category', 'ch' ),
'update_item' => __( 'Update PDF Category', 'ch' ),
'separate_items_with_commas' => __( 'Separate PDF Categories with commas', 'ch' ),
'search_items' => __( 'Search PDF Category', 'ch' ),
'add_or_remove_items' => __( 'Add or remove PDF Categories', 'ch' ),
'choose_from_most_used' => __( 'Choose from the most used PDF Categories', 'ch' ),
'not_found' => __( 'Not Found', 'ch' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'pdf_category', array( 'pdf' ), $args );
}
add_action( 'init', 'pdf_tax', 0 );
function wpdocs_custom_taxonomies_terms_links() {
// Get post by post ID.
$post = get_post( $post->ID );
// Get post type by post.
$post_type = $post->post_type;
// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$out = array();
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$out[] = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
esc_html( $term->name )
);
}
}
}
return implode( ', ', $out );
}<file_sep><?php
$args = array(
'post_type' => 'library_blog',
);
$library = new WP_Query( $args );
if ( $library->have_posts() ) : while ( $library->have_posts() ) : $library->the_post();
?>
<div <?php post_class('row sticky'); ?>>
<div class="small-12 columns">
<h4 itemprop="name"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h4>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> View <?php the_title(); ?></a></p>
</div>
</div>
<?php
endwhile;
?>
<div class="row">
<div class="small-12 columns">
<a href="/library/what-do-you-do-with-a-phd-in-music/library_blog/" class="button"><i class="ch-library2" aria-hidden="true"></i> See more Library Blog posts</a>
</div>
</div>
<?php
endif;
wp_reset_query();
?><file_sep> </main>
<footer id="colophon" class="site-footer" role="contentinfo" itemscope itemtype="http://schema.org/WPFooter">
<div class="row">
<div class="small-12 large-8 columns">
<strong><?php bloginfo('name'); ?></strong><br />
<p><?php echo nl2br( get_theme_mod('ch_address') ); ?></p>
<p><?php echo get_theme_mod('ch_phone'); ?></p>
<p><?php echo nl2br( get_theme_mod('ch_hours') ); ?></p>
<p><?php echo get_theme_mod('ch_tagline'); ?> (registered charity <?php echo get_theme_mod('ch_charity'); ?>)</p>
<?php dynamic_sidebar( 'footer_left' ); ?>
© 1787 - <?php echo date('Y'); ?> Conway Hall</p>
</div>
<div class="small-12 large-4 columns">
<?php dynamic_sidebar( 'footer_right' ); ?>
</div>
</div>
</footer>
</div>
</div>
<?php wp_footer(); ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-30440586-1', 'auto');
ga('send', 'pageview');
</script>
<!-- Google Code for Remarketing Tag -->
<!--------------------------------------------------
Remarketing tags may not be associated with personally identifiable information or placed on pages related to sensitive categories. See more information and instructions on how to setup the tag on: http://google.com/ads/remarketingsetup?utm_source=Email&utm_medium=Email&utm_term=Email&utm_content=Emails&utm_campaign=Emails
--------------------------------------------------->
<script type="text/javascript">
var google_tag_params = {
ecomm_prodid: 'REPLACE_WITH_VALUE',
ecomm_pagetype: 'REPLACE_WITH_VALUE',
ecomm_totalvalue: 'REPLACE_WITH_VALUE',
};
</script>
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 980427979;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;
/* ]]> */
</script>
<script type="text/javascript" src="//http://www.googleadservices.com/pagead/conversion.js?utm_source=Email&utm_medium=Email&utm_term=Email&utm_content=Emails&utm_campaign=Emails">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//http://googleads.g.doubleclick.net/pagead/viewthroughconversion/980427979/?value=0&guid=ON&script=0%22%2F&utm_source=Email&utm_medium=Email&utm_term=Email&utm_content=Emails&utm_campaign=Emails>
</div>
</noscript>
</body>
</html><file_sep><?php
function google_search_widget() {
register_widget('GS_Widget');
}
add_action('widgets_init', 'google_search_widget');
class GS_Widget extends WP_Widget {
function __construct() {
$widget_ops = array( 'classname' => 'google_search_widget', 'description' => __( 'Conway Hall Google Search', 'ch' ) );
parent::__construct( 'chgsearch', __( 'Conway Hall Google Search Widget', 'bci' ), $widget_ops );
}
function widget( $args, $instance) {
$title = apply_filters( 'widget_title', $instance['title']);
echo '<li class="widget gs-widget">';
echo '<h2 class="widgettitle">'. $title .'</h2>';
echo '<script>';
echo '(function() {';
echo 'var cx = "015352071736437870634:4muuitsu3iu";';
echo 'var gcse = document.createElement("script");';
echo 'gcse.type = "text/javascript";';
echo 'gcse.async = true;';
echo 'gcse.src = "https://cse.google.com/cse.js?cx=" + cx;';
echo 'var s = document.getElementsByTagName("script")[0];';
echo 's.parentNode.insertBefore(gcse, s);';
echo '})();';
echo '</script>';
echo '<div class="w-form field form-wrapper">';
echo '<form name="cse" id="searchbox" action="/search" method="get">';
echo '<input type="hidden" name="cx" value="015352071736437870634:4muuitsu3iu" /><!-- Replace YOUR_CSEID with your CSE ID (!) -->';
echo '<input type="hidden" name="ie" value="utf-8" />';
echo '<input type="hidden" name="hl" value="en" />';
echo '<input name="q" type="text" class="your-custom-field-class" placeholder="Search" />';
echo '<input class="search-submit" value="Search" type="submit" name="sa" />';
echo '</form>';
echo '</div>';
echo '</li>';
}
function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
} else {
$title = __( 'Search', 'ch' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
}
function ch_subpages_load_widgets() {
register_widget( 'ch_Subpages_Widget' );
}
add_action( 'widgets_init', 'ch_subpages_load_widgets' );
class ch_Subpages_Widget extends WP_Widget {
function __construct() {
$widget_ops = array( 'classname' => 'widget_subpages', 'description' => __( 'Lists current section subpages', 'ch' ) );
parent::__construct( 'subpages-widget', __( 'Subpages Widget', 'ch' ), $widget_ops );
}
function widget( $args, $instance ) {
extract( $args, EXTR_SKIP );
$post_types = get_post_types( array( 'hierarchical' => true ) );
if ( !is_singular( $post_types ) && !apply_filters( 'ch_subpages_widget_display_override', false ) )
return;
global $post;
$parents = array_reverse( get_ancestors( $post->ID, 'page' ) );
$parents[] = $post->ID;
$parents = apply_filters( 'ch_subpages_widget_parents', $parents );
$args = array(
'child_of' => $parents[0],
'parent' => $parents[0],
'sort_column' => 'menu_order',
'post_type' => get_post_type(),
);
$depth = 1;
$subpages = get_pages( apply_filters( 'ch_subpages_widget_args', $args, $depth ) );
if ( empty( $subpages ) )
return;
echo $before_widget;
global $ch_subpages_is_first;
$ch_subpages_is_first = true;
$title = esc_attr( $instance['title'] );
if( 1 == $instance['title_from_parent'] ) {
$title = get_the_title( $parents[0] );
if( 1 == $instance['title_link'] )
$title = '<a href="' . get_permalink( $parents[0] ) . '">' . apply_filters( 'ch_subpages_widget_title', $title ) . '</a>';
}
if( !empty( $title ) )
echo $before_title . $title . $after_title;
if( !isset( $instance['deep_subpages'] ) )
$instance['deep_subpages'] = 0;
if( !isset( $instance['nest_subpages'] ) )
$instance['nest_subpages'] = 0;
$this->build_subpages( $subpages, $parents, $instance['deep_subpages'], $depth, $instance['nest_subpages'] );
echo $after_widget;
}
function build_subpages( $subpages, $parents, $deep_subpages = 0, $depth = 1, $nest_subpages = 0 ) {
if( empty( $subpages ) )
return;
global $post, $ch_subpages_is_first;
echo '<ul class="subpages_widget">';
foreach ( $subpages as $subpage ) {
$class = array();
$class[] = 'menu-item-' . $subpage->ID;
if ( $subpage->ID == $post->ID )
$class[] = 'widget_subpages_current_page';
if( $ch_subpages_is_first )
$class[] .= 'first-menu-item';
$ch_subpages_is_first = false;
$class = apply_filters( 'ch_subpages_widget_class', $class, $subpage );
$class = !empty( $class ) ? ' class="' . implode( ' ', $class ) . '"' : '';
echo '<li' . $class . '><a href="' . get_permalink( $subpage->ID ) . '" rel="Permalink" title="Permalink to ' . apply_filters( 'ch_subpages_page_title', $subpage->post_title, $subpage ) . '">' . apply_filters( 'ch_subpages_page_title', $subpage->post_title, $subpage ) . '</a>';
if (!$nest_subpages)
echo '</li>';
do_action( 'ch_subpages_widget_menu_extra', $subpage, $class );
if ( $deep_subpages && in_array( $subpage->ID, $parents ) ) {
$args = array(
'child_of' => $subpage->ID,
'parent' => $subpage->ID,
'sort_column' => 'menu_order',
'post_type' => get_post_type(),
);
$deeper_pages = get_pages( apply_filters( 'ch_subpages_widget_args', $args, $depth ) );
$depth++;
$this->build_subpages( $deeper_pages, $parents, $deep_subpages, $depth, $nest_subpages );
}
if ($nest_subpages)
echo '</li>';
}
echo '</ul>';
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = esc_attr( $new_instance['title'] );
$instance['title_from_parent'] = (int) $new_instance['title_from_parent'];
$instance['title_link'] = (int) $new_instance['title_link'];
$instance['deep_subpages'] = (int) $new_instance['deep_subpages'];
$instance['nest_subpages'] = (int) $new_instance['nest_subpages'];
return $instance;
}
function form( $instance ) {
$defaults = array( 'title' => '', 'title_from_parent' => 0, 'title_link' => 0, 'deep_subpages' => 0, 'nest_subpages' => 0 );
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'ch' );?></label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" />
</p>
<p>
<input class="checkbox" type="checkbox" value="1" <?php checked( $instance['title_from_parent'], 1 ); ?> id="<?php echo $this->get_field_id( 'title_from_parent' ); ?>" name="<?php echo $this->get_field_name( 'title_from_parent' ); ?>" />
<label for="<?php echo $this->get_field_id( 'title_from_parent' ); ?>"><?php _e( 'Use top level page as section title.', 'ch' );?></label>
</p>
<p>
<input class="checkbox" type="checkbox" value="1" <?php checked( $instance['title_link'], 1 ); ?> id="<?php echo $this->get_field_id( 'title_link' ); ?>" name="<?php echo $this->get_field_name( 'title_link' ); ?>" />
<label for="<?php echo $this->get_field_id( 'title_link' ); ?>"><?php _e( 'Make title a link', 'ch' ); echo '<br /><em>('; _e( 'only if "use top level page" is checked', 'ch' ); echo ')</em></label>';?>
</p>
<p>
<input class="checkbox" type="checkbox" value="1" <?php checked( $instance['deep_subpages'], 1 ); ?> id="<?php echo $this->get_field_id( 'deep_subpages' ); ?>" name="<?php echo $this->get_field_name( 'deep_subpages' ); ?>" />
<label for="<?php echo $this->get_field_id( 'deep_subpages' ); ?>"><?php _e( 'Include the current page\'s subpages', 'ch' ); ?></label>
</p>
<p>
<input class="checkbox" type="checkbox" value="1" <?php checked( $instance['nest_subpages'], 1 ); ?> id="<?php echo $this->get_field_id( 'nest_subpages' ); ?>" name="<?php echo $this->get_field_name( 'nest_subpages' ); ?>" />
<label for="<?php echo $this->get_field_id( 'nest_subpages' ); ?>"><?php _e( 'Nest sub-page <ul> inside parent <li>', 'ch' ); echo '<br /><em>('; _e( "only if "Include the current page's subpages" is checked", 'ch' ); echo ')</em></label>';?></p>
<?php
}
}
function ch_search_widget() {
register_widget( 'CH_Search' );
}
add_action( 'widgets_init', 'ch_search_widget' );
class CH_Search extends WP_Widget {
function __construct() {
$widget_ops = array( 'classname' => 'widget_ch_search', 'description' => __( 'Conway Hall Search', 'ch' ) );
parent::__construct( 'chsearch', __( 'Conway Hall Search Widget', 'ch' ), $widget_ops );
}
function widget( $args, $instance) {
$asidesearch = new WP_Advanced_Search('asidesearch');
$title = apply_filters( 'widget_title', $instance['title']);
echo '<li class="widget new-joiners-widget">';
echo '<h5 class="widget">'. $title .'</h5>';
echo $asidesearch->the_form();
echo '</li>';
}
function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
} else {
$title = __( 'Search', 'ch' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
}
function ch_login() {
register_widget( 'CH_Login' );
}
add_action( 'widgets_init', 'ch_login' );
class CH_Login extends WP_Widget {
function __construct() {
$widget_ops = array( 'classname' => 'widget_ch_login', 'description' => __( 'Conway Hall Log In', 'ch' ) );
parent::__construct( 'chlogin', __( 'Conway Hall Log In Widget', 'ch' ), $widget_ops );
}
function widget( $args, $instance) {
$title = apply_filters( 'widget_title', $instance['title']);
echo '<li class="widget widget-login">';
if ( is_user_logged_in() ) {
echo '<h2 class="widgettitle">My Details</h2>';
echo '<ul class="widget">';
$current_user = wp_get_current_user();
echo '<li>Hello ' . $current_user->user_firstname . '</li>';
$allowed_roles = array('administrator', 'trustee');
if( array_intersect($allowed_roles, $current_user->roles ) ) {
echo '<li><a href="/ethical-society/members-area/"><i class="ch-lock" aria-hidden="true"></i> Members Area</a></li>';
}
if ( in_array( 'member', (array) $current_user->roles ) ) {
echo '<li><a href="/ethical-society/trustees-area/"><i class="ch-lock" aria-hidden="true"></i> Members Area</a></li>';
}
} else {
echo '<h2 class="widgettitle">'. $title .'</h2>';
echo '<ul class="widget">';
echo '<li>' . wp_loginout() .'</li>';
}
echo '</ul>';
echo '</li>';
}
function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
} else {
$title = __( 'Log In', 'ch' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
}
class CustomTaxonomyWidget extends WP_Widget
{
public function __construct()
{
parent::__construct(
'custom_taxonomy_widget',
'Custom Taxonomy Widget',
array('description' => 'Allows you to create a new Sidebar widget to display terms from custom taxonomies!')
);
}
public function widget($args, $instance)
{
extract($args);
$title = apply_filters('widget_title', $instance['title']);
$hide_empty = (isset($instance['hide_empty'])) ? true : false;
$order_options = (isset($instance['order_options'])) ? explode('/', $instance['order_options']) : array('', '');
$get_terms_args = array(
'hide_empty' => $hide_empty,
'orderby' => (isset($order_options[0])) ? $order_options[0] : 'name',
'order' => (isset($order_options[1])) ? $order_options[1] : 'ASC',
'number' => (isset($instance['max_terms'])) ? $instance['max_terms'] : '',
'exclude' => (isset($instance['exclude'])) ? $instance['exclude'] : '',
'include' => (isset($instance['include'])) ? $instance['include'] : '',
'pad_counts' => true
);
$terms = get_terms($instance['custom_taxonomies'], $get_terms_args);
if (empty($terms) && isset($instance['hide_widget_empty']))
return;
echo $before_widget;
if (! empty($title))
echo $before_title . $title . $after_title;
?>
<ul>
<?php foreach ($terms as $term): ?>
<li class="<?php echo ($term->parent != "0") ? 'taxonomy-has-parent' : null; ?>">
<a href="<?php echo get_term_link($term); ?>"><?php echo $term->name; ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php
echo $after_widget;
}
public function form($instance)
{
$field_data = array(
'title' => array(
'id' => $this->get_field_id('title'),
'name' => $this->get_field_name('title'),
'value' => (isset($instance['title'])) ? $instance['title'] : __('New Title')
),
'taxonomies' => array(
'name' => $this->get_field_name('custom_taxonomies'),
'value' => (isset($instance['custom_taxonomies'])) ? $instance['custom_taxonomies'] : ''
),
'max_terms' => array(
'id' => $this->get_field_id('max_terms'),
'name' => $this->get_field_name('max_terms'),
'value' => (isset($instance['max_terms'])) ? $instance['max_terms'] : ''
),
'hide_widget_empty' => array(
'id' => $this->get_field_id('hide_widget_empty'),
'name' => $this->get_field_name('hide_widget_empty'),
'value' => (isset($instance['hide_widget_empty'])) ? 'true' : ''
),
'hide_empty' => array(
'id' => $this->get_field_id('hide_empty'),
'name' => $this->get_field_name('hide_empty'),
'value' => (isset($instance['hide_empty'])) ? 'true' : ''
),
'order_options' => array(
'id' => $this->get_field_id('order_options'),
'name' => $this->get_field_name('order_options'),
'value' => (isset($instance['order_options'])) ? $instance['order_options'] : 'name'
),
'exclude' => array(
'id' => $this->get_field_id('exclude'),
'name' => $this->get_field_name('exclude'),
'value' => (isset($instance['exclude'])) ? $instance['exclude'] : ''
),
'include' => array(
'id' => $this->get_field_id('include'),
'name' => $this->get_field_name('include'),
'value' => (isset($instance['include'])) ? $instance['include'] : ''
)
);
$taxonomies = get_taxonomies(array('_builtin' => false), 'objects');
?>
<p>
<label for="<?php echo $field_data['title']['id']; ?>"><?php _e('Title:'); ?></label>
<input class="widefat" id="<?php echo $field_data['title']['id']; ?>" name="<?php echo $field_data['title']['name']; ?>" type="text" value="<?php echo esc_attr($field_data['title']['value']); ?>">
</p>
<p style='font-weight: bold;'><?php _e('Options:'); ?></p>
<p>
<input id="<?php echo $field_data['hide_widget_empty']['id']; ?>" name="<?php echo $field_data['hide_widget_empty']['name']; ?>" type="checkbox" value="true" <?php checked($field_data['hide_widget_empty']['value'], 'true'); ?>>
<label for="<?php echo $field_data['hide_widget_empty']['id']; ?>"><?php _e('Hide Widget If There Are No Terms To Be Displayd?'); ?></label>
</p>
<p>
<input id="<?php echo $field_data['hide_empty']['id']; ?>" name="<?php echo $field_data['hide_empty']['name']; ?>" type="checkbox" value="true" <?php checked($field_data['hide_empty']['value'], 'true'); ?>>
<label for="<?php echo $field_data['hide_empty']['id']; ?>"><?php _e('Hide Terms That Have No Related Posts?'); ?></label>
</p>
<p>
<label for="<?php echo $field_data['order_options']['id']; ?>"><?php _e('Order Terms By:'); ?></label><br>
<select id="<?php echo $field_data['order_options']['id']; ?>" name="<?php echo $field_data['order_options']['name']; ?>">
<option value="id/ASC" <?php selected($field_data['order_options']['value'], 'id/ASC'); ?>>ID Ascending</option>
<option value="id/DESC" <?php selected($field_data['order_options']['value'], 'id/DESC'); ?>>ID Descending</option>
<option value="count/ASC" <?php selected($field_data['order_options']['value'], 'count/ASC'); ?>>Count Ascending</option>
<option value="count/DESC" <?php selected($field_data['order_options']['value'], 'count/DESC'); ?>>Count Descending</option>
<option value="name/ASC" <?php selected($field_data['order_options']['value'], 'name/ASC'); ?>>Name Ascending</option>
<option value="name/DESC" <?php selected($field_data['order_options']['value'], 'name/DESC'); ?>>Name Descending</option>
<option value="slug/ASC" <?php selected($field_data['order_options']['value'], 'slug/ASC'); ?>>Slug Ascending</option>
<option value="slug/DESC" <?php selected($field_data['order_options']['value'], 'slug/DESC'); ?>>Slug Descending</option>
</select>
</p>
<p>
<label for="<?php echo $field_data['max_terms']['id']; ?>"><?php _e('Maximum Number Of Terms To Return:'); ?></label>
<input class="widefat" id="<?php echo $field_data['max_terms']['id']; ?>" name="<?php echo $field_data['max_terms']['name']; ?>" type="text" value="<?php echo esc_attr($field_data['max_terms']['value']); ?>" placeholder="Keep Empty To Display All">
</p>
<p>
<label for="<?php echo $field_data['exclude']['id']; ?>"><?php _e('Ids To Exclude From Being Displayed:'); ?></label>
<input class="widefat" id="<?php echo $field_data['exclude']['id']; ?>" name="<?php echo $field_data['exclude']['name']; ?>" type="text" value="<?php echo esc_attr($field_data['exclude']['value']); ?>" placeholder="Separate ids with a comma ','">
</p>
<p>
<label for="<?php echo $field_data['include']['id']; ?>"><?php _e('Only Display Terms With The Following Ids:'); ?></label>
<input class="widefat" id="<?php echo $field_data['include']['id']; ?>" name="<?php echo $field_data['include']['name']; ?>" type="text" value="<?php echo esc_attr($field_data['include']['value']); ?>" placeholder="Separate ids with a comma ','">
</p>
<p style='font-weight: bold;'><?php _e('Custom Taxonomies:'); ?></p>
<?php foreach($taxonomies as $taxonomy): ?>
<p>
<input id="<?php echo $taxonomy->name; ?>" name="<?php echo $field_data['taxonomies']['name']; ?>[]" type="checkbox" value="<?php echo $taxonomy->name; ?>" <?php echo $this->is_taxonomy_checked($field_data['taxonomies']['value'], $taxonomy->name); ?>>
<label for="<?php echo $taxonomy->name; ?>"><?php echo $taxonomy->labels->name; ?></label>
</p>
<?php endforeach; ?>
<?php
}
public function update($new_instance, $old_instance)
{
$instance['title'] = strip_tags($new_instance['title']);
$instance['hide_widget_empty'] = $new_instance['hide_widget_empty'];
$instance['hide_empty'] = $new_instance['hide_empty'];
$instance['order_options'] = $new_instance['order_options'];
$instance['max_terms'] = $new_instance['max_terms'];
$instance['exclude'] = $new_instance['exclude'];
$instance['include'] = $new_instance['include'];
$instance['custom_taxonomies'] = $new_instance['custom_taxonomies'];
return $instance;
}
public function is_taxonomy_checked($custom_taxonomies_checked, $taxonomy_name)
{
if (! is_array($custom_taxonomies_checked))
return checked($custom_taxonomies_checked, $taxonomy_name);
if (in_array($taxonomy_name, $custom_taxonomies_checked))
return 'checked="checked"';
}
}
add_action('widgets_init', 'init_custom_taxonomy_widget');
function init_custom_taxonomy_widget()
{
register_widget('CustomTaxonomyWidget');
}
<file_sep>{
"name": "<NAME>",
"options": [
{
"name": "Power",
"overlay": "power",
"icon": "ch-plug"
},
{
"name": "Dimensions",
"overlay": "dimensions",
"icon": "ch-enlarge"
}
],
"rooms": [
{
"name": "Boardroom",
"capacity": "22",
"overlay": "boardroom"
},
{
"name": "<NAME>",
"capacity": "30",
"overlay": "ushape"
},
{
"name": "Buffet",
"capacity": "35",
"overlay": "buffet"
},
{
"name": "Theatre",
"capacity": "35",
"overlay": "theatre"
}
]
}<file_sep><?php
/**
* Template Name: Full Width Page
*/
get_header();
?>
<div class="row">
<div class="small-12 large-12 columns main justify">
<h2 class="page-title" data-id="<?php echo $page_id; ?>" id="topofpage"><?php the_title(); ?></h2>
<?php
if( is_page( array( 'Main Hall Room Planner', 'Foyer Room Planner', 'Bertrand Russell Room Planner', 'Brockway Room Planner', 'Artists Room Planner', 'Club Room Planner', 'Balcony Room Planner' ) ) ) {
get_template_part('parts/planit/room', 'planner');
}
if( is_page( array( 'Main Hall 360 Degree Tour', 'Foyer 360 Degree Tour', 'Bertrand Russell Room 360 Degree Tour', 'Brockway Room 360 Degree Tour', 'Artists Room 360 Degree Tour', 'Club Room 360 Degree Tour', 'Balcony 360 Degree Tour', 'Library 360 Degree Tour', 'Foyer (Open Doors) 360 Degree Tour' ) ) ) {
get_template_part('parts/planit/pano', 'tour');
}
?>
<?php
$custom_taxterms = wp_get_object_terms( $post->ID, 'page_tag', array('fields' => 'ids') );
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => 3,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'page_tag',
'field' => 'id',
'terms' => $custom_taxterms
)
),
'post__not_in' => array ($post->ID),
);
$related_items = new WP_Query( $args );
if ($related_items->have_posts()) :
echo '<div class="row endrelated"><div class="small-12 large-12 columns center related"><h3>Other pages to consider</h3></div>';
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( ); ?></a>
<h5><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h5>
<?php the_excerpt(); ?>
</div>
<?php
endwhile;
echo '</div>';
endif;
wp_reset_postdata();
?>
</div>
</div>
<?php get_footer(); ?><file_sep><?php
$line = file_get_contents("http://countdown.tfl.gov.uk/markers/swLat/{$_GET['swLat']}/swLng/{$_GET['swLng']}/neLat/{$_GET['neLat']}/neLng/{$_GET['neLng']}/");
echo $line;
?><file_sep><?php
$args = array (
'connected_type' => 'pdf_to_page',
'connected_items' => get_queried_object(),
'nopaging' => true,
);
$lecture_speaker = new WP_Query( $args );
$the_count = $lecture_speaker->found_posts;
if ( $lecture_speaker->have_posts() ) {
?>
<div class="row endrelated2" id="bio">
<div class="small-12 large-12 columns center related">
<h3>Related Document<?php if ( ( $lecture_speaker->have_posts() ) && ( $the_count > 1 ) ) : ?>s<?php endif; ?></h3>
</div>
<?php
while ( $lecture_speaker->have_posts() ) {
$lecture_speaker->the_post();
?>
<div class="small-12 medium-4 large-4 columns">
<div class="card">
<div class="card-divider">
<h5><a href="<?php global $post; $text = get_post_meta( $post->ID, '_cmb_pdf', true ); echo $text; ?>" title="<?php the_title_attribute(); ?>" target="_blank"><?php the_title(); ?></a></h5>
</div>
<a href="<?php global $post; $text = get_post_meta( $post->ID, '_cmb_pdf', true ); echo $text; ?>" title="<?php the_title_attribute(); ?>" target="_blank"><?php the_post_thumbnail('related'); ?></a>
</div>
</div>
<?php
}
?>
</div>
<?php
} else {
// no posts found
}
wp_reset_postdata();
?><file_sep>
<?php
$args = array (
'post_type' => array( 'jobs' ),
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$project_current = new WP_Query( $args );
?>
<?php if ($project_current->have_posts()) : while ($project_current->have_posts()) : $project_current->the_post(); ?>
<?php
date_default_timezone_set('Europe/London');
$start = get_post_meta( get_the_ID(), '_project_startdate', true );
$end = get_post_meta( get_the_ID(), '_project_enddate', true );
$ongoing = get_post_meta( get_the_ID(), '_project_ongoing', true );
$lead = get_post_meta( get_the_ID(), '_project_lead', true );
?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns">
<h4 itemprop="name"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h4>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> View <?php the_title(); ?></a></p>
<p><strong>Closing Date:</strong> <?php echo do_shortcode('[postexpirator]'); ?></p>
<p><?php echo get_the_term_list( $post->ID, 'job_type', 'Posted in: ', ', ', '' ); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<file_sep> <h2>Current Projects</h2>
<?php
$args = array (
'post_type' => array( 'project' ),
'posts_per_page' => 3,
'orderby' => 'menu_order',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'OR',
'ongoing' => array(
'key' => '_project_ongoing',
'compare' => 'EXISTS'
),
'start_date' => array(
array(
'key' => '_project_enddate',
'value' => current_time('timestamp'),
'type' => 'numeric',
'compare' => '>='
)
)
),
);
$project_current = new WP_Query( $args );
?>
<?php if ($project_current->have_posts()) : while ($project_current->have_posts()) : $project_current->the_post(); ?>
<?php
date_default_timezone_set('Europe/London');
$start = get_post_meta( get_the_ID(), '_project_startdate', true );
$end = get_post_meta( get_the_ID(), '_project_enddate', true );
$ongoing = get_post_meta( get_the_ID(), '_project_ongoing', true );
$lead = get_post_meta( get_the_ID(), '_project_lead', true );
?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns">
<h4 itemprop="name"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h4>
<?php if($ongoing != ''){ ?>
<h6>Ongoing</h6>
<?php } else { ?>
<?php if($start != '' && $end != ''){ ?>
<h6>From: <?php echo date_i18n( 'jS F Y', $start ); ?> - <?php echo date_i18n( 'jS F Y', $end ); ?><?php if($today > $end){ echo ' (Project Ended)'; } ?></h6>
<?php } else { ?>
<?php if($start != ''){ ?>
<h6>Start Date: <?php echo date_i18n( 'jS F Y', $start ); ?></h6>
<?php } ?>
<?php if($end != ''){ ?>
<h6>End Date: <?php echo date_i18n( 'jS F Y', $end ); ?></h6>
<?php } ?>
<?php } ?>
<?php } ?>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<?php
if($lead != '') {
?>
<h6>Project led by: <?php echo $lead; ?></h6>
<?php
}
?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> View <?php the_title(); ?></a></p>
<p class="meta">Project categories: <?php echo wpdocs_custom_taxonomies_terms_links(); ?></p>
</div>
</div>
<?php endwhile; ?>
<p>See more <a href="/learning-at-conway-hall/projects/current-projects/">Current Projects</a></p>
<?php endif; ?>
<hr />
<h2>Past Projects</h2>
<?php
$args = array (
'post_type' => array( 'project' ),
'posts_per_page' => 3,
'orderby' => 'menu_order',
'order' => 'ASC',
'meta_query' => array(
'start_date' => array(
array(
'key' => '_project_enddate',
'value' => current_time('timestamp'),
'type' => 'numeric',
'compare' => '<'
)
)
),
);
$project_current = new WP_Query( $args );
?>
<?php if ($project_current->have_posts()) : while ($project_current->have_posts()) : $project_current->the_post(); ?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns">
<h4 itemprop="name"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h4>
<?php if($ongoing != ''){ ?>
<h6>Ongoing</h6>
<?php } else { ?>
<?php if($start != '' && $end != ''){ ?>
<h6>From: <?php echo date_i18n( 'jS F Y', $start ); ?> - <?php echo date_i18n( 'jS F Y', $end ); ?><?php if($today > $end){ echo ' (Project Ended)'; } ?></h6>
<?php } else { ?>
<?php if($start != ''){ ?>
<h6>Start Date: <?php echo date_i18n( 'jS F Y', $start ); ?></h6>
<?php } ?>
<?php if($end != ''){ ?>
<h6>End Date: <?php echo date_i18n( 'jS F Y', $end ); ?></h6>
<?php } ?>
<?php } ?>
<?php } ?>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> View <?php the_title(); ?></a></p>
<p class="meta">Project categories: <?php echo wpdocs_custom_taxonomies_terms_links(); ?></p>
</div>
</div>
<?php endwhile; ?>
<p>See more <a href="/learning-at-conway-hall/projects/past-projects/">Past Projects</a></p>
<?php endif; ?>
<file_sep>{
"name": "<NAME>",
"options": [
{
"name": "Power",
"overlay": "power",
"icon": "ch-plug"
},
{
"name": "Screens",
"overlay": "screens",
"icon": "ch-television"
},
{
"name": "Dimensions",
"overlay": "dimensions",
"icon": "ch-enlarge"
}
],
"rooms": [
{
"name": "Boardroom",
"capacity": "28",
"overlay": "boardroom"
},
{
"name": "Dinner",
"capacity": "30",
"overlay": "dinner"
},
{
"name": "Cabaret",
"capacity": "32",
"overlay": "cabaret"
},
{
"name": "<NAME>",
"capacity": "50",
"overlay": "ushape"
},
{
"name": "Buffet",
"capacity": "50",
"overlay": "buffet"
},
{
"name": "Theatre",
"capacity": "70",
"overlay": "theatre"
},
{
"name": "<NAME>",
"capacity": "36",
"overlay": "hollowsquare"
},
{
"name": "Theatre Landscape",
"capacity": "70",
"overlay": "theatrelandscape"
}
]
}<file_sep><?php get_header(); ?>
<div class="row">
<div class="small-12 large-9 columns main justify">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div itemscope itemtype="http://schema.org/Article">
<?php get_template_part('parts/global/post', 'meta'); ?>
<?php
$page_id = get_the_ID();
?>
<?php if(has_post_thumbnail()) { ?>
<figure itemprop="associatedMedia">
<span itemscope itemtype="http://schema.org/ImageObject">
<?php the_post_thumbnail('top', array('itemprop' => 'contentURL')); ?>
<?php if(get_post_meta(get_post_thumbnail_id(), 'owner', true) != '') { ?>
<figcaption>
Image Credit:
<span itemscope itemprop="author" itemtype="http://schema.org/Person">
<?php if(get_post_meta(get_post_thumbnail_id(), 'ownerurl', true) != '') { ?>
<a href="<?php echo get_post_meta(get_post_thumbnail_id(), 'ownerurl', true); ?>" target="_blank">
<?php } ?>
<span itemprop="name"><?php echo get_post_meta(get_post_thumbnail_id(), 'owner', true); ?></span>
<?php if(get_post_meta(get_post_thumbnail_id(), 'ownerurl', true) != '') { ?>
</a>
<?php } ?>
</span>
</figcaption>
<?php } ?>
</span>
</figure>
<?php } ?>
<h2 class="page-title" data-id="<?php echo $page_id; ?>" itemprop="headline"><?php the_title(); ?></h2>
<?php get_template_part('parts/global/post', 'copyright'); ?>
<?php get_template_part('parts/global/related', 'pdfmeta'); ?>
<div itemprop="mainEntityOfPage">
<?php the_content(); ?>
<?php
if(is_page('Members Area')) {
get_template_part('parts/global/log', 'in');
}
?>
<?php
if(is_page('Password Recovery')) {
get_template_part('parts/global/password', 'recovery');
}
?>
</div>
<?php
if(is_page('Past Issues')) {
get_template_part('parts/issue/decade', 'list');
}
if(is_page('What do you do with a PhD in Music?')) {
get_template_part('parts/library/library', 'blog');
}
if(is_page('Chancery Lane')) {
get_template_part('parts/tfl/chancery', 'lane');
}
if(is_page('Holborn Station')) {
get_template_part('parts/tfl/holborn', 'station');
}
if(is_page('Russell Square')) {
get_template_part('parts/tfl/russell', 'square');
}
if(is_page('Santander Cycle Hire')) {
get_template_part('parts/tfl/bike', 'hire');
}
if(is_page('Buses')) {
get_template_part('parts/tfl/bus', 'stops');
}
if(is_page('Current Projects')) {
get_template_part('parts/projects/current', 'projects');
}
if(is_page('Past Projects')) {
get_template_part('parts/projects/past', 'projects');
}
?>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php get_template_part('parts/global/related', 'pdf'); ?>
<?php
if(is_page('Concerts Programme')) {
get_template_part('parts/sundayconcerts/sundayconcerts', 'programme');
}
if(is_page('People')) {
get_template_part('parts/people/people', 'loop');
}
if(is_page('Our Projects')) {
get_template_part('parts/learning/learning', 'loop');
}
if(is_page('Opportunities')) {
get_template_part('parts/jobs/jobs', 'loop');
}
get_template_part('parts/global/sub', 'pages');
?>
<?php get_template_part('parts/global/related', 'pages'); ?>
</div>
<aside class="small-12 large-3 columns">
<?php get_template_part('sidebar'); ?>
</aside>
</div>
<?php get_footer(); ?><file_sep><?php get_header(); ?>
<div class="row">
<div class="small-12 large-9 columns">
<div class="row">
<div class="small-12 columns">
<h2 class="archive-title"><?php the_archive_title(); ?></h2>
</div>
</div>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class('row'); ?>>
<div class="small-12 columns main">
<h3 itemprop="name" class="page-title"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h3>
<?php get_template_part('parts/ethicalrecord/ethical', 'record'); ?>
<?php if(has_post_thumbnail()) { ?>
<div class="row">
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns">
<?php the_excerpt(); ?>
<?php get_template_part('parts/issue/read', 'issue'); ?>
</div>
</div>
<?php } else { ?>
<?php the_excerpt(); ?>
<?php get_template_part('parts/issue/read', 'issue'); ?>
<?php } ?>
</div>
</div>
<?php endwhile; ?>
<div class="small button-group">
<?php wp_pagenavi(); ?>
</div>
<?php endif; ?>
</div>
<aside class="small-12 large-3 columns">
<?php get_template_part('sidebar'); ?>
</aside>
</div>
<?php get_footer(); ?><file_sep> <div class="row" id="holbornStation">
<div class="small-12 medium-6 columns">
<h3 class="label Central Line"><a class="active" data-line="central">Central Line</a></h3>
</div>
<div class="small-12 medium-6 columns">
<h3 class="label Piccadilly Line"><a class="" data-line="piccadilly">Piccadilly Line</a></h3>
</div>
<div class="small-12 columns">
<div class="row">
<div class="small-9 medium-4 large-4 columns"><h5>Destination</h5></div>
<div class="small-3 medium-2 large-2 columns"><h5>Due</h5></div>
<div class="small-12 medium-3 large-3 columns show-for-medium"><h5>Currently</h5></div>
<div class="small-12 medium-3 large-3 columns show-for-medium"><h5>Platform</h5></div>
</div>
<div class="row">
<div class="small-12 large-12 columns" id="tube"><div class="loading"><img src="<?php echo bloginfo('template_url'); ?>/images/ripple.svg"></div></div>
</div>
<div id="map"></div>
<div id="box"></div>
</div>
</div>
<file_sep>{
"name": "<NAME>",
"options": [
{
"name": "Power",
"overlay": "power",
"icon": "ch-plug"
},
{
"name": "Fire Exits",
"overlay": "fire",
"icon": "ch-exit"
},
{
"name": "HD Cameras",
"overlay": "hdcams",
"icon": "ch-video-camera2"
},
{
"name": "Screens",
"overlay": "screens",
"icon": "ch-television"
},
{
"name": "Dimensions",
"overlay": "dimensions",
"icon": "ch-enlarge"
}
],
"rooms": [
{
"name": "Boardroom",
"capacity": "42",
"overlay": "boardroom"
},
{
"name": "Dinner",
"capacity": "108",
"overlay": "dinner"
},
{
"name": "Cabaret",
"capacity": "75",
"overlay": "cabaret"
},
{
"name": "<NAME>",
"capacity": "75",
"overlay": "ushape"
},
{
"name": "Exam",
"capacity": "99",
"overlay": "exam"
},
{
"name": "Buffet",
"capacity": "250",
"overlay": "buffet"
},
{
"name": "Theatre",
"capacity": "250",
"overlay": "theatre"
},
{
"name": "<NAME>",
"capacity": "60",
"overlay": "hollowsquare"
}
]
}<file_sep><?php
function lectureSpeaker() {
p2p_register_connection_type( array(
'name' => 'lectures2speakers',
'from' => 'speaker',
'to' => 'ethicalrecord'
) );
}
add_action( 'p2p_init', 'lectureSpeaker' );
function issuePost() {
p2p_register_connection_type( array(
'name' => 'issue2post',
'from' => 'issue',
'to' => 'ethicalrecord'
) );
}
add_action( 'p2p_init', 'issuePost' );
function projectEvent() {
p2p_register_connection_type( array(
'name' => 'project2event',
'from' => 'project',
'to' => 'tribe_events'
) );
}
add_action( 'p2p_init', 'projectEvent' );
function my_connection_types() {
p2p_register_connection_type( array(
'name' => 'pdf_to_page',
'from' => 'pdf',
'to' => 'page'
) );
}
add_action( 'p2p_init', 'my_connection_types' );
function job_pdf() {
p2p_register_connection_type( array(
'name' => 'pdf_to_job',
'from' => 'pdf',
'to' => 'jobs'
) );
}
add_action( 'p2p_init', 'job_pdf' );
function lecture_pdf() {
p2p_register_connection_type( array(
'name' => 'pdf_to_lecture',
'from' => 'pdf',
'to' => 'memorial_lecture'
) );
}
add_action( 'p2p_init', 'lecture_pdf' );
function concert_pdf() {
p2p_register_connection_type( array(
'name' => 'pdf_to_concert',
'from' => 'pdf',
'to' => 'sunday_concerts'
) );
}
add_action( 'p2p_init', 'concert_pdf' );
function event_pdf() {
p2p_register_connection_type( array(
'name' => 'pdf_to_event',
'from' => 'pdf',
'to' => 'tribe_events'
) );
}
add_action( 'p2p_init', 'event_pdf' );
function post_pdf() {
p2p_register_connection_type( array(
'name' => 'pdf_to_post',
'from' => 'pdf',
'to' => 'post'
) );
}
add_action( 'p2p_init', 'post_pdf' );
<file_sep><?php get_header(); ?>
<div class="row">
<div class="small-12 large-9 columns main">
<?php get_template_part('parts/home/home', 'orbit'); ?>
<h4 class="description"><?php echo bloginfo( 'description' ); ?></h4>
<ul class="accordion" data-responsive-accordion-tabs="tabs small-accordion large-tabs">
<li class="accordion-item is-active" data-accordion-item>
<a href="#" class="accordion-title">Events</a>
<div class="accordion-content" data-tab-content>
<?php get_template_part('parts/home/home', 'events'); ?>
</div>
</li>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title">Venue Hire</a>
<div class="accordion-content" data-tab-content>
<?php get_template_part('parts/home/home', 'hire'); ?>
</div>
</li>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title">Library</a>
<div class="accordion-content" data-tab-content>
<?php get_template_part('parts/home/home', 'library'); ?>
</div>
</li>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title">Sunday Concerts</a>
<div class="accordion-content" data-tab-content>
<?php get_template_part('parts/home/sunday', 'concerts'); ?>
</div>
</li>
<li class="accordion-item" data-accordion-item>
<a href="#" class="accordion-title">Ethical Record</a>
<div class="accordion-content" data-tab-content>
<?php get_template_part('parts/home/home', 'ethical'); ?>
</div>
</li>
</ul>
</div>
<aside class="small-12 large-3 columns">
<?php get_template_part('sidebar'); ?>
</aside>
</div>
<?php get_footer(); ?><file_sep><?php
// WP_Query arguments
$args = array (
'post_type' => 'people',
'order' => 'ASC',
'orderby' => 'menu_order',
);
// The Query
$room_hire = new WP_Query( $args );
// The Loop
if ( $room_hire->have_posts() ) {
while ( $room_hire->have_posts() ) {
$room_hire->the_post();
?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns">
<h4 itemprop="name"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h4>
<h5><?php global $post; $text = get_post_meta( $post->ID, '_cmb_title', true ); echo $text; ?></h5>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-user" aria-hidden="true"></i> View <?php the_title(); ?></a></p>
</div>
</div>
<?php
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?><file_sep><?php
$line = file_get_contents("http://www.tfl.gov.uk/tfl/syndication/feeds/cycle-hire/livecyclehireupdates.xml");
$simpleXml = simplexml_load_string(trim($line));
$terminalName = "{$_GET['dock']}";
$dock = $simpleXml->xpath("//station[terminalName='$terminalName']");
$json = json_encode($dock);
echo $json;
?><file_sep><!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js no-svg">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "WebSite",
"name" : "<?php echo bloginfo( 'name' ); ?>",
"alternateName" : "<?php echo bloginfo( 'name' ); ?> • <?php echo bloginfo( 'description' ); ?>",
"url": "<?php echo bloginfo( 'url' ); ?>",
"potentialAction": {
"@type": "SearchAction",
"target": "<?php echo bloginfo( 'url' ); ?>/?s={search_term_string}",
"query-input": "required name=search_term_string"
}
}
</script>
<?php wp_head(); ?>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); ?>" />
</head>
<body <?php body_class(); ?> itemscope itemtype="http://schema.org/WebPage">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.9&appId=895339160541870";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="off-canvas-wrapper">
<div class="off-canvas position-left" id="offCanvas" data-off-canvas>
<button class="close-button" aria-label="Close menu" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
<div class="top-bar-left">
<?php
wp_nav_menu(array(
'container' => false,
'menu' => __( 'Top Bar Menu', 'tfh' ),
'menu_class' => 'vertical menu',
'theme_location' => 'topbar-menu',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'fallback_cb' => 'f6_offcanvasr_menu_fallback',
'walker' => new F6_OFFCANVAS_MENU_WALKER(),
));
?>
<?php
wp_nav_menu(array(
'container' => false,
'menu' => __( 'Social Media Menu', 'tfh' ),
'menu_class' => 'vertical medium-horizontal menu',
'theme_location' => 'social-media',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'fallback_cb' => 'f6_offcanvasr_menu_fallback',
'walker' => new F6_OFFCANVAS_MENU_WALKER(),
));
?>
</div>
</div>
<div class="off-canvas-content" data-off-canvas-content>
<div id="page" class="site">
<header id="masthead" class="site-header" role="banner" itemscope itemtype="http://schema.org/WPHeader">
<div class="title-bar">
<div class="title-bar-left">
<button class="ch-chevron-left" type="button" data-open="offCanvas"> Menu</button>
</div>
</div>
<div class="top-bar" id="animated-menu">
<div class="top-bar-left">
<?php
wp_nav_menu(array(
'container' => false,
'menu' => __( 'Top Bar Menu', 'tfh' ),
'menu_class' => 'vertical medium-horizontal menu',
'theme_location' => 'topbar-menu',
'items_wrap' => '<ul id="%1$s" class="%2$s" data-responsive-menu="medium-dropdown">%3$s</ul>',
'fallback_cb' => 'f6_topbar_menu_fallback',
'walker' => new F6_TOPBAR_MENU_WALKER(),
));
?>
</div>
<div class="top-bar-right">
<?php
wp_nav_menu(array(
'container' => false,
'menu' => __( 'Social Media Menu', 'tfh' ),
'menu_class' => 'vertical medium-horizontal menu',
'theme_location' => 'social-media',
'items_wrap' => '<ul id="%1$s" class="%2$s" data-responsive-menu="medium-dropdown">%3$s</ul>',
'fallback_cb' => 'f6_topbar_menu_fallback',
'walker' => new F6_TOPBAR_MENU_WALKER(),
));
?>
</div>
</div>
<div class="row">
<div class="small-12 columns center tagline">
<h1>
<a href="<?php echo bloginfo( 'url' ); ?>">
<i aria-hidden="true" class="ch-logo"></i>
</a>
</h1>
</div>
</div>
</header>
<main role="main" itemscope itemtype="http://schema.org/Blog" id="main"><file_sep><div class="row">
<div class="small-12 columns" id="tour" data-room="<?php the_title(); ?>"></div>
<div id="other" class="small-12 large-12 columns">
<div class="row">
<div class="small-6 columns"></div>
<div class="small-6 columns">
<a href="http://www.panaround.co.uk/" rel="noopener" target="_blank"><img src="<?php echo bloginfo('template_url'); ?>/planit/global/img/planit-logo.png" alt="planit-logo" width="56" height="35" class="alignright" /></a>
</div>
</div>
</div>
</div>
<script src="<?php echo bloginfo('template_url'); ?>/planit/global/js/flash-detection.min.js"></script>
<script src="<?php echo bloginfo('template_url'); ?>/planit/global/js/swfobject.js"></script>
<script src="<?php echo bloginfo('template_url'); ?>/planit/global/embedpano.js"></script><file_sep><?php
function mySearchWPXpdfPath() {
return '/pdftotext';
}
add_filter( 'searchwp_xpdf_path', 'mySearchWPXpdfPath' );
function my_searchwp_process_term_limit() {
return 500;
}
add_filter( 'searchwp_process_term_limit', 'my_searchwp_process_term_limit' );
// Init CMB2
if ( file_exists( dirname( __FILE__ ) . '/cmb2/init.php' ) ) {
require_once dirname( __FILE__ ) . '/cmb2/init.php';
} elseif ( file_exists( dirname( __FILE__ ) . '/CMB2/init.php' ) ) {
require_once dirname( __FILE__ ) . '/CMB2/init.php';
}
require_once('functions/theme.php');
require_once('functions/menus.php');
require_once('functions/sidebars.php');
require_once('functions/taxonomies.php');
require_once('functions/post_types.php');
require_once('functions/meta.php');
require_once('functions/widgets.php');
require_once('functions/p2p.php');
require_once('functions/customise.php');
<file_sep>{
"name": "Club Room",
"options": [
{
"name": "Power",
"overlay": "power",
"icon": "ch-plug"
},
{
"name": "Fire Exits",
"overlay": "fire",
"icon": "ch-exit"
},
{
"name": "Dimensions",
"overlay": "dimensions",
"icon": "ch-enlarge"
}
],
"rooms": [
{
"name": "Boardroom",
"capacity": "16",
"overlay": "boardroom"
},
{
"name": "Cabaret",
"capacity": "32",
"overlay": "cabaret"
},
{
"name": "<NAME>",
"capacity": "30",
"overlay": "ushape"
},
{
"name": "Buffet",
"capacity": "40",
"overlay": "buffet"
},
{
"name": "Theatre",
"capacity": "35",
"overlay": "theatre"
},
{
"name": "<NAME>",
"capacity": "20",
"overlay": "hollowsquare"
}
]
}<file_sep><?php
function _register_menu() {
register_nav_menu( 'topbar-menu', __( 'Top Bar Menu','textdomain' ) );
register_nav_menu( 'mobile-menu', __( 'Mobile Menu','textdomain' ) );
register_nav_menu( 'social-media', __( 'Social Media Menu','textdomain' ) );
}
add_action( 'after_setup_theme', '_theme_setup' );
function _theme_setup() {
add_action( 'init', '_register_menu' );
add_theme_support( 'menus' );
}
//Walker
class F6_TOPBAR_MENU_WALKER extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"horizontal menu\" data-submenu>\n";
}
}
//Optional fallback
function f6_topbar_menu_fallback($args) {
$walker_page = new Walker_Page();
$fallback = $walker_page->walk(get_pages(), 0);
$fallback = str_replace("<ul class='children'>", '<ul class="children submenu menu horizontal" data-submenu>', $fallback);
echo '<ul class="vertical medium-horizontal menu" data-dropdown-menu>'.$fallback.'</ul>';
}
//Walker
class F6_OFFCANVAS_MENU_WALKER extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"nested vertical menu\">\n";
}
}
//Optional fallback
function f6_offcanvasr_menu_fallback($args) {
$walker_page = new Walker_Page();
$fallback = $walker_page->walk(get_pages(), 0);
$fallback = str_replace("<ul class='nested vertical menu'>", '<ul class="nested vertical menu">', $fallback);
echo '<ul class="nested vertical menu">'.$fallback.'</ul>';
}
add_action('nav_menu_css_class', 'add_current_nav_class', 10, 2 );
function add_current_nav_class($classes, $item) {
global $post;
$current_post_type = get_post_type_object(get_post_type($post->ID));
$current_post_type_slug = $current_post_type->rewrite['slug'];
$menu_slug = strtolower(trim($item->url));
if (strpos($menu_slug,$current_post_type_slug) !== false) {
$classes[] = 'current-menu-item';
}
return $classes;
}<file_sep><?php
add_action( 'tribe_eb_after_event_creation', 'my_change_tribe_eventbrite_currency', 10, 4 );
function my_change_tribe_eventbrite_currency( $eventbrite_id, $venue_id, $organizer_id, $post_id ) {
$currency_acro = 'GBP';
$parameters = 'id=' . $eventbrite_id . '¤cy=' . $currency_acro;
$success = Event_Tickets_PRO::instance()->sendEventBriteRequest( 'event_update', $parameters, $post_id, true, true, false );
if ( !$success ) {
add_filter( 'tribe_eb_error_message', 'my_change_tribe_eventbrite_currency_failed' );
}
}
function my_change_tribe_eventbrite_currency_failed() {
return 'Failed to update the currency.';
}
function my_wootickets_tribe_get_cost( $cost, $postId, $withCurrencySymbol ) {
if ( empty($cost) && class_exists('TribeWooTickets') ) {
// see if the event has tickets associated with it
$wootickets = TribeWooTickets::get_instance();
$ticket_ids = $wootickets->get_Tickets_ids( $postId );
if ( empty($ticket_ids) ) {
return '';
}
// see if any tickets remain, and what price range they have
$max_price = 0;
$min_price = 0;
$sold_out = TRUE;
foreach ( $ticket_ids as $ticket_id ) {
$ticket = $wootickets->get_ticket($postId, $ticket_id);
if ( $ticket->stock ) {
$sold_out = FALSE;
$price = $ticket->price;
if ( $price > $max_price ) {
$max_price = $price;
}
if ( empty($min_price) || $price < $min_price ) {
$min_price = $price;
}
}
}
if ( $sold_out ) { // all of the tickets are sold out
return __('Sold Out');
}
if ( empty($price) ) { // none of the tickets costs anything
return __('Free');
}
// make a string showing the price (or range, if applicable)
$currency = tribe_get_option( 'defaultCurrencySymbol', '£' );
if ( empty($min_price) || $min_price == $max_price ) {
return $currency . $max_price;
}
return $currency . $min_price . ' - ' . $currency . $max_price;
}
return $cost; // return the default, if nothing above returned
}
add_filter( 'tribe_get_cost', 'my_wootickets_tribe_get_cost', 10, 3 );
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = get_template_directory_uri() . '/img/ConwayHall.jpg';
}
return $first_img;
}
function tribe_get_event_website_button( $event = null, $label = 'Book Now' ) {
$url = tribe_get_event_website_url( $event );
if ( ! empty( $url ) ) {
$label = is_null( $label ) ? $url : $label;
$html = sprintf(
'<a href="%s" target="_blank">%s</a>',
$url,
'Book Now'
);
} else {
$html = '';
}
return apply_filters( 'tribe_get_event_website_button', $html );
}
function custom_widget_featured_image() {
global $post;
echo tribe_event_featured_image( $post->ID, 'calendar' );
}
add_action( 'tribe_events_list_widget_before_the_event_title', 'custom_widget_featured_image' );
add_filter('wp_list_categories', 'add_slug_css_list_categories');
function add_slug_css_list_categories($list) {
$cats = get_categories(array('taxonomy' => 'taxonomy'));
foreach($cats as $cat) {
$find = 'cat-item-' . $cat->term_id . '"';
$replace = 'category-' . $cat->slug . '"';
$list = str_replace( $find, $replace, $list );
$find = 'cat-item-' . $cat->term_id . ' ';
$replace = 'category-' . $cat->slug . ' ';
$list = str_replace( $find, $replace, $list );
}
return $list;
}
add_action( 'save_post_tribe_events', 'force_cost_update' );
function force_cost_update( $event_id ) {
TribeEventsAPI::update_event_cost( $event_id );
}
class TicketingCostConflict {
static $original_cost;
static function resolve() {
add_filter( 'tribe_get_cost', array( __CLASS__, 'store_pre_eb' ), 5 );
add_filter( 'tribe_get_cost', array( __CLASS__, 'maybe_undo_eb_change' ), 50, 2 );
}
static function store_pre_eb( $cost ) {
self::$original_cost = $cost;
}
static function maybe_undo_eb_change( $cost, $event_id ) {
if ( ! class_exists( 'Event_Tickets_PRO' ) ) return $cost;
if ( Event_Tickets_PRO::instance()->getEventId( $event_id ) ) return $cost;
return self::$original_cost;
}
}
TicketingCostConflict::resolve();
function theme_options_panel(){
add_menu_page('Conway Hall', 'Conway Hall', 'manage_options', 'conway-hall-admin', 'conway_hall_admin', 'dashicons-shield', 30);
add_submenu_page( 'conway-hall-admin', 'Email Signature Generator', 'Email Signature', 'manage_options', 'email-signature', 'ch_email');
add_submenu_page( 'conway-hall-admin', 'Secure Password Generator', 'Password Generator', 'manage_options', 'password-generator', 'ch_password');
}
add_action('admin_menu', 'theme_options_panel');
function conway_hall_admin(){
echo '<div class="wrap">
<h2><i class="dashicons dashicons-shield"></i> Conway Hall Admin</h2>
<p>You can generate your email signature or a secure password from here.</p>
<p><i class="dashicons dashicons-email-alt"></i> <a href="/wp-admin/admin.php?page=email-signature">Generate an email signature</a></p>
<p><i class="dashicons dashicons-admin-network"></i> <a href="/wp-admin/admin.php?page=password-generator">Generate a secure password</a></p>
</div>';
}
function ch_email(){
include(get_template_directory().'/email-signature.php');
}
function ch_password(){
include(get_template_directory().'/password-generator.php');
}
function events_calendar_remove_scripts() {
if (!is_admin() && !in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) {
wp_dequeue_script( 'the-events-calendar');
wp_dequeue_script( 'tribe-events-list');
wp_dequeue_script( 'tribe-events-ajax-day');
}}
add_action('wp_print_scripts', 'events_calendar_remove_scripts' , 10);
add_action('wp_footer', 'events_calendar_remove_scripts' , 10);<file_sep><?php
$er = file_get_contents("http://ethicalrecord.org.uk/feed/");
echo $er;
?><file_sep><?php if( has_tag() ) { ?>
<h6>Tagged</h6>
<p><i class="ch-tag" aria-hidden="true"></i> <?php the_tags('', ', ', ''); ?></p>
<?php } else { ?>
<?php } ?>
<?php
$terms = get_the_terms( $post->ID, 'taxonomy' );
if ( $terms && ! is_wp_error( $terms ) ) :
$taxonomy_links = array();
foreach ( $terms as $term ) {
$taxonomy_links[] = '<a href="/ethicalrecord/taxonomy/'.$term->slug.'">'.$term->name.'</a>';
}
$taxonomy = join( ", ", $taxonomy_links );
?>
<p class="taxonomy">
<i class="ch-map-signs" aria-hidden="true"></i> <?php echo $taxonomy; ?>
</p>
<?php endif; ?><file_sep><?php
$args = array (
'connected_type' => 'pdf_to_concert',
'connected_items' => $post,
'nopaging' => true,
);
$sunday_pdf = new WP_Query( $args );
if ($sunday_pdf->have_posts()) : while ($sunday_pdf->have_posts()) : $sunday_pdf->the_post();
?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" class="button"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php
endif;
wp_reset_postdata();
?>
<?php
// Find connected pages
$connected = new WP_Query( array(
'connected_type' => 'pdf_to_concert',
'connected_items' => get_queried_object(),
'nopaging' => true,
) );
// Display connected pages
if ( $connected->have_posts() ) :
?>
<h3>Related pages:</h3>
<ul>
<?php while ( $connected->have_posts() ) : $connected->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php
// Prevent weirdness
wp_reset_postdata();
endif;
?><file_sep> <ul class="sidebar">
<?php if ( ! dynamic_sidebar('joinsidebar') ) : ?>
<li>{static sidebar item 1}</li>
<?php endif; ?>
<?php if ( ! dynamic_sidebar('right') ) : ?>
<?php
// Find connected pages
$connected = new WP_Query( array(
'connected_type' => 'pdf_to_job',
'connected_items' => get_queried_object(),
'nopaging' => true,
) );
// Display connected pages
if ( $connected->have_posts() ) :
?>
<li class="widget">
<h5 class="widgettitle">Related Job:</h3>
<ul class="menu related">
<?php while ( $connected->have_posts() ) : $connected->the_post(); ?>
<li><a href="<?php global $post; $text = get_post_meta( $post->ID, '_cmb_pdf', true ); echo $text; ?>" download><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
</li>
<?php
// Prevent weirdness
wp_reset_postdata();
endif;
?>
<li>{static sidebar item 1}</li>
<?php endif; ?>
</ul>
<ul class="sidebar">
<li class="widget"><h2 class="widgettitle">Facebook</h2><div class="fb-page" data-href="https://www.facebook.com/conwayhallethicalsociety/" data-tabs="timeline" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="false"><blockquote cite="https://www.facebook.com/conwayhallethicalsociety/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/conwayhallethicalsociety/">Conway Hall</a></blockquote></div></li>
<li class="widget"><h2 class="widgettitle">@ConwayHall</h2><a class="twitter-timeline" data-chrome="nofooter noheader noborders transparent" data-dnt="true" href="https://twitter.com/ConwayHall" data-widget-id="545334184664117248">Tweets by @ConwayHall</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script></li>
</ul><file_sep><div class="orbit show-for-medium" role="region" aria-label="Conway Hall Homepage" data-orbit>
<?php
$args = array (
'post_type' => 'carousel',
'posts_per_page_' => '10',
'orderby' => 'menu_order'
);
$carousel = new WP_Query( $args );
if( $carousel->have_posts() ) :
?>
<ul class="orbit-container">
<button class="orbit-previous"><span class="show-for-sr">Previous Slide</span>◀︎</button>
<button class="orbit-next"><span class="show-for-sr">Next Slide</span>▶︎</button>
<?php
while ( $carousel->have_posts() ) : $carousel->the_post();
?>
<li class="orbit-slide" data-slide="<?php echo get_post_field( 'menu_order', $post_id); ?>">
<a href="<?php global $post; $text = get_post_meta( $post->ID, '_cmb_url', true ); echo $text; ?>"><?php the_post_thumbnail( 'carousel' ); ?></a>
<figcaption class="orbit-caption">
<a href="<?php global $post; $text = get_post_meta( $post->ID, '_cmb_url', true ); echo $text; ?>">
<h4><?php the_title(); ?></h4>
<?php the_excerpt(); ?>
</a>
</figcaption>
</li>
<?php
endwhile;
?>
</ul>
</div>
<?php
endif;
wp_reset_postdata();
?><file_sep><?php
/* Template Name: PDF Search Page */
global $post;
$query = isset( $_REQUEST['docsearch'] ) ? sanitize_text_field( $_REQUEST['docsearch'] ) : '';
$doc = isset( $_REQUEST['doc'] ) ? absint( $_REQUEST['doc'] ) : 1;
if ( class_exists( 'SWP_Query' ) ) {
$engine = 'pdf';
$swp_query = new SWP_Query(
array(
's' => $query,
'engine' => $engine,
'page' => $doc,
)
);
$pagination = paginate_links( array(
'format' => '?doc=%#%',
'current' => $doc,
'total' => $swp_query->max_num_pages,
'type' => 'list'
) );
}
get_header();
?>
<div class="row">
<div class="small-12 large-9 columns main">
<div class="row">
<div class="small-12 columns">
<form role="search" method="get" class="searchform group" action="<?php echo esc_html( get_permalink() ); ?>">
<label>
<span class="offscreen"><?php echo _x( 'Search PDFs for:', 'label' ) ?></span>
<input type="search" class="search-field" placeholder="Search..." value="<?php echo $query; ?>" name="docsearch" />
</label>
<input type="submit" class="search-submit" value=" Search ">
</form>
<?php if ( ! empty( $query ) ) : ?>
<p>Please be aware that the search results are dependant upon Optical Character Recognition (OCR) scanning technology and that, although, this has increased rapidly over the years there are limitations in regards to the source materials and character formatting.</p>
<h4><?php echo $swp_query->found_posts; ?> results for "<?php echo $query; ?>"</h4>
<?php endif; ?>
</div>
</div>
<?php
if ( ! empty( $query ) && isset( $swp_query ) && ! empty( $swp_query->posts ) ) {
foreach ( $swp_query->posts as $post ) {
setup_postdata( $post );
?>
<?php
global $post;
$pdf_content = get_post_meta( $post->ID, 'searchwp_content', true )
?>
<?php
global $post;
$lecspeaker = get_post_meta( $post->ID, '_cmb_lecspeaker', true );
$date = get_post_meta( $post->ID, '_cmb_lecdate', true );
$abstract = get_post_meta( $post->ID, '_cmb_abstract', true );
$author = get_post_meta( $post->ID, '_cmb_author', true );
$publisher = get_post_meta( $post->ID, '_cmb_publisher', true );
$reviewer = get_post_meta( $post->ID, '_cmb_vpauthor', true );
$lead = get_post_meta( $post->ID, '_project_lead', true );
$bio = get_post_meta( $post->ID, '_project_bio', true );
$jobtitle = get_post_meta( $post->ID, '_cmb_title', true );
$searchwp_doc_content = wp_get_attachment_metadata( $post->ID, 'searchwp_doc_content', true );
$price = get_post_meta( $post->ID, '_cmb_tickets', true );
$free = get_post_meta( $post->ID, '_cmb_free', true );
?>
<div class="row">
<div class="sticky">
<div class="small-12 columns">
<?php
$post_type = get_post_type( $post->ID );
switch( $post_type ) {
case 'post':
echo '<h6><i aria-hidden="true" class="ch-file-empty2"></i> Post</h6>';
break;
case 'page':
echo '<h6><i aria-hidden="true" class="ch-file-text23"></i> Page</h6>';
break;
case 'tribe_events':
echo '<h6><i aria-hidden="true" class="ch-calendar3"></i> Event</h6>';
break;
case 'ethicalrecord':
echo '<h6><i aria-hidden="true" class="ch-books"></i> Ethical Record</h6>';
break;
case 'issue':
echo '<h6><i aria-hidden="true" class="ch-book3"></i> Issue</h6>';
break;
case 'jobs':
echo '<h6><i aria-hidden="true" class="ch-briefcase2"></i> Job</h6>';
break;
case 'project':
echo '<h6><i aria-hidden="true" class="ch-folder-open-o"></i> Project</h6>';
break;
case 'memorial_lecture':
echo '<h6><i aria-hidden="true" class="ch-bullhorn2"></i> Conway Memorial Lecture</h6>';
break;
case 'sunday_concerts':
echo '<h6><i aria-hidden="true" class="ch-music"></i> Sunday Concert</h6>';
break;
case 'tribe_venue':
echo '<h6><i aria-hidden="true" class="ch-office2"></i> Venue</h6>';
break;
case 'library_blog':
echo '<h6><i aria-hidden="true" class="ch-library2"></i> Library Blog</h6>';
break;
}
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
<div class="small-12 large-4 columns">
</div>
<div class="small-12 large-8 columns">
<?php echo substr($pdf_content, 0, 250); ?>...
</div>
</div>
</div>
<?php
}
?>
<div class="small button-group">
<?php wp_pagenavi(); ?>
</div>
<?php
wp_reset_postdata();
if ( $swp_query->max_num_pages > 1 ) {
?>
<div class="navigation pagination" role="navigation">
<h2 class="screen-reader-text">Posts navigation</h2>
<div class="nav-links">
<?php echo wp_kses_post( $pagination ); ?>
</div>
</div>
<?php
}
} else {}
?>
</div>
<aside class="small-12 large-3 columns">
<?php get_template_part('sidebar'); ?>
</aside>
</div>
<?php get_footer(); ?><file_sep> <?php
if(is_user_logged_in()) {
global $user_login;
$current_user = new WP_User(wp_get_current_user()->ID);
$user_roles = $current_user->roles;
foreach ($user_roles as $role) {
if ($role == 'trustee' || $role == 'member' || $role == 'nonukmember'|| $role == 'nonukinstitution' || $role == 'editor' || $role == 'administrator' ) {
global $current_user;
if ( isset($current_user) ) {
echo '<p><strong>Welcome, ' . $current_user->user_firstname . ', to the Members\' Area of Conway Hall Ethical Society!</strong></p>';
}
?>
<p><br /><a href="<?php echo wp_logout_url(get_permalink()); ?>" title="Logout"><i class="icon-lock-open"></i>Logout</a></p>
<?php
} else {
?>
<h4>Please enter your details in order to access this part of the site:</h4>
<?php
wp_login_form( $args );
?>
<p><a href="/password-recovery/">Lost password?</a></p>
<?php
}
}
} else {
?>
<h4>Please enter your details in order to access this part of the site:</h4>
<?php
wp_login_form( $args );
}
?>
<p><a href="/password-recovery/">Lost password?</a></p><file_sep><?php
add_action( 'cmb2_admin_init', 'extra_info2' );
function extra_info2() {
$prefix = '_cmb_';
$cmb_ethicalrecord = new_cmb2_box( array(
'id' => $prefix . 'meta',
'title' => __( 'Ethical Record Info', 'ch' ),
'object_types' => array( 'ethicalrecord' ),
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Lectures',
'id' => $prefix . '',
'type' => 'title',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Speaker',
'id' => $prefix . 'lecspeaker',
'type' => 'text',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Lecture Date',
'id' => $prefix . 'lecdate2',
'type' => 'text_date_timestamp',
'date_format' => 'd/m/Y'
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Lecture Abstract',
'desc' => 'Try to limit to around 20 - 50 words.',
'id' => $prefix . 'abstract',
'type' => 'textarea',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Lecture References/Footnotes',
'desc' => 'Try to limit to around 20 - 50 words.',
'id' => $prefix . 'ref',
'type' => 'wysiwyg',
'options' => array(
'wpautop' => true, // use wpautop?
'media_buttons' => true, // show insert/upload button(s)
// 'textarea_name' => $editor_id, // set the textarea name to something different, square brackets [] can be used here
'textarea_rows' => get_option('default_post_edit_rows', 10), // rows="..."
'tabindex' => '',
'editor_css' => '', // intended for extra styles for both visual and HTML editors buttons, needs to include the `<style>` tags, can use "scoped".
'editor_class' => '', // add extra class(es) to the editor textarea
'teeny' => true, // output the minimal editor config used in Press This
'dfw' => false, // replace the default fullscreen with DFW (needs specific css)
'tinymce' => true, // load TinyMCE, can be used to pass settings directly to TinyMCE using an array()
'quicktags' => true // load Quicktags, can be used to pass settings directly to Quicktags using an array()
),
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Lecture Video',
'desc' => 'Enter a YouTube, Vimeo, etc URL. Supports services listed at <a href="http://codex.wordpress.org/Embeds" target="_blank">http://codex.wordpress.org/Embeds</a>.',
'id' => $prefix . 'lecture_video',
'type' => 'oembed',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Book Reviews',
'id' => $prefix . 'br',
'type' => 'title',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Book Author(s)',
'id' => $prefix . 'author',
'type' => 'text',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Book Publisher',
'id' => $prefix . 'publisher',
'type' => 'text',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'ISBN',
'id' => $prefix . 'isbn',
'type' => 'text',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Review Author',
'id' => $prefix . 'vpauthor',
'type' => 'text',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Videos',
'id' => $prefix . 'vr',
'type' => 'title',
) );
$cmb_ethicalrecord->add_field( array(
'name' => 'Video',
'desc' => 'Enter a YouTube, Vimeo, etc URL. Supports services listed at <a href="http://codex.wordpress.org/Embeds" target="_blank">http://codex.wordpress.org/Embeds</a>.',
'id' => $prefix . 'video',
'type' => 'oembed',
) );
}
add_action( 'cmb2_admin_init', 'issue_info' );
function issue_info() {
$prefix = '_cmb_';
$cmb = new_cmb2_box( array(
'id' => 'test_metabox',
'title' => 'Issue Info',
'object_types' => array( 'issue' ),
) );
$cmb->add_field( array(
'name' => 'PDF',
'id' => $prefix . 'issue',
'type' => 'file',
) );
}
add_action( 'cmb2_admin_init', 'free_events2' );
function free_events2() {
$prefix = '_cmb_';
$cmb_event = new_cmb2_box( array(
'id' => 'event_meta',
'title' => 'Free Event?',
'object_types' => array( 'tribe_events' ),
'context' => 'side',
'priority' => 'high',
'show_names' => true,
) );
$cmb_event->add_field( array(
'name' => 'Tick if a free event',
'id' => $prefix . 'free',
'type' => 'checkbox',
) );
$cmb_event->add_field( array(
'name' => 'Non-EventBrite ticket costs',
'id' => $prefix . 'tickets',
'type' => 'text_small',
) );
}
add_action( 'cmb2_admin_init', 'amazon_link2' );
function amazon_link2() {
$prefix = '_cmb_';
$cmb_amazon = new_cmb2_box( array(
'id' => 'amazon',
'title' => 'Amazon Link',
'object_types' => array( 'amazon_product' ),
) );
$cmb_amazon->add_field( array(
'name' => 'Author',
'id' => $prefix . 'author',
'type' => 'text',
) );
$cmb_amazon->add_field( array(
'name' => 'Link to Amazon',
'id' => $prefix . 'url',
'type' => 'text_url',
) );
}
add_action( 'cmb2_admin_init', 'carousel_link2' );
function carousel_link2() {
$prefix = '_cmb_';
$cmb_carousel = new_cmb2_box( array(
'id' => 'carousel',
'title' => 'Link',
'object_types' => array( 'carousel' ),
) );
$cmb_carousel->add_field( array(
'name' => 'Link to page',
'id' => $prefix . 'url',
'type' => 'text_url',
) );
}
add_action( 'cmb2_admin_init', 'job_title2' );
function job_title2() {
$prefix = '_cmb_';
$cmb_job = new_cmb2_box( array(
'id' => 'job',
'title' => 'Job Title',
'object_types' => array( 'people' ),
) );
$cmb_job->add_field( array(
'name' => 'Job Title',
'id' => $prefix . 'title',
'type' => 'text',
) );
}
add_action( 'cmb2_admin_init', 'pdf_box2' );
function pdf_box2() {
$prefix = '_cmb_';
$cmb_pdf = new_cmb2_box( array(
'id' => 'pdf',
'title' => 'PDF',
'object_types' => array( 'pdf' ),
) );
$cmb_pdf->add_field( array(
'name' => 'PDF File',
'id' => $prefix . 'pdf',
'type' => 'file',
) );
}
add_action( 'cmb2_admin_init', 'memorial_speaker2' );
function memorial_speaker2() {
$prefix = '_cmb_';
$cmb_memorial = new_cmb2_box( array(
'id' => 'memorial_speaker',
'title' => 'Speaker',
'object_types' => array( 'memorial_lecture' ),
) );
$cmb_memorial->add_field( array(
'name' => 'Speaker',
'id' => $prefix . 'speaker',
'type' => 'text',
) );
}
add_action( 'cmb2_admin_init', 'project_meta2' );
function project_meta2() {
$prefix = '_project_';
$cmb_project = new_cmb2_box( array(
'id' => 'project',
'title' => 'Project Details',
'object_types' => array( 'project' ),
) );
$cmb_project->add_field( array(
'name' => 'Start Date',
'id' => $prefix . 'startdate',
'type' => 'text_date_timestamp',
'date_format' => 'd m Y',
) );
$cmb_project->add_field( array(
'name' => 'End Date',
'id' => $prefix . 'enddate',
'type' => 'text_date_timestamp',
'date_format' => 'd m Y',
) );
$cmb_project->add_field( array(
'name' => 'Ongoing?',
'id' => $prefix . 'ongoing',
'type' => 'checkbox',
) );
$cmb_project->add_field( array(
'name' => 'Project Lead',
'id' => $prefix . 'ptitle',
'type' => 'title',
) );
$cmb_project->add_field( array(
'name' => 'Project Lead Name',
'id' => $prefix . 'lead',
'type' => 'text',
) );
$cmb_project->add_field( array(
'name' => 'Project Lead Photo',
'id' => $prefix . 'leadpic',
'type' => 'file',
) );
$cmb_project->add_field( array(
'name' => 'Project Lead Bio',
'id' => $prefix . 'bio',
'type' => 'wysiwyg',
'options' => array(
'wpautop' => true, // use wpautop?
'media_buttons' => true, // show insert/upload button(s)
// 'textarea_name' => $editor_id, // set the textarea name to something different, square brackets [] can be used here
'textarea_rows' => get_option('default_post_edit_rows', 10), // rows="..."
'tabindex' => '',
'editor_css' => '', // intended for extra styles for both visual and HTML editors buttons, needs to include the `<style>` tags, can use "scoped".
'editor_class' => '', // add extra class(es) to the editor textarea
'teeny' => true, // output the minimal editor config used in Press This
'dfw' => false, // replace the default fullscreen with DFW (needs specific css)
'tinymce' => true, // load TinyMCE, can be used to pass settings directly to TinyMCE using an array()
'quicktags' => true // load Quicktags, can be used to pass settings directly to Quicktags using an array()
),
) );
}
add_action( 'cmb2_admin_init', 'page_meta' );
function page_meta() {
$prefix = '_page_';
$cmb_page = new_cmb2_box( array(
'id' => 'page',
'title' => 'Page Side Images',
'object_types' => array( 'page' ),
) );
$cmb_page->add_field( array(
'name' => 'Show Images',
'id' => $prefix . 'showimg',
'description' => __( 'check this to show side images for the page', 'ch' ),
'type' => 'checkbox',
) );
$page_images = $cmb_page->add_field( array(
'id' => 'sideimages',
'type' => 'group',
'options' => array(
'group_title' => __( 'Image {#}', 'ch' ),
'add_button' => __( 'Add Another Image', 'ch' ),
'remove_button' => __( 'Remove Image', 'ch' ),
'sortable' => true, // beta
),
) );
$cmb_page->add_group_field( $page_images, array(
'name' => 'Image',
'id' => 'sideimg',
'type' => 'file',
) );
$cmb_page->add_group_field( $page_images, array(
'name' => 'Image Caption',
'id' => 'sidecaption',
'type' => 'text',
) );
}
add_action( 'cmb2_admin_init', 'sundayconcert_meta' );
function sundayconcert_meta() {
$prefix = '_sundayconcert_';
$cmb_page = new_cmb2_box( array(
'id' => 'sundayconcert',
'title' => 'Sunday Concert Pre-Concert Talks/Recitals',
'object_types' => array( 'tribe_events' ),
) );
$cmb_page->add_field( array(
'name' => 'Show Images',
'id' => $prefix . 'description',
'description' => __( 'Add info about Pre-Concert Talks/Recitals here', 'ch' ),
'type' => 'wysiwyg',
) );
}<file_sep><?php
$args = array (
'connected_type' => 'lectures2speakers',
'connected_items' => get_queried_object(),
'nopaging' => true,
);
$lecture_speaker = new WP_Query( $args );
$the_count = $lecture_speaker->found_posts;
if ( $lecture_speaker->have_posts() ) {
?>
<div class="row endrelated" id="bio">
<div class="small-12 large-12 columns center related">
<h3>Speaker<?php if ( ( $lecture_speaker->have_posts() ) && ( $the_count > 1 ) ) : ?>s<?php endif; ?></h3>
</div>
<?php
while ( $lecture_speaker->have_posts() ) {
$lecture_speaker->the_post();
?>
<div class="small-12 medium-4 large-4 columns">
<div class="card">
<div class="card-divider">
<h5><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h5>
</div>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('related'); ?></a>
<div class="card-section">
<?php the_excerpt(); ?>
</div>
</div>
</div>
<?php
}
?>
</div>
<?php
} else {
// no posts found
}
wp_reset_postdata();
?><file_sep> <?php
global $wpdb;
$error = '';
$success = '';
// check if we're in reset form
if( isset( $_POST['action'] ) && 'reset' == $_POST['action'] )
{
$email = $wpdb->escape(trim($_POST['email']));
if( empty( $email ) ) {
$error = 'Enter a username or e-mail address..';
} else if( ! is_email( $email )) {
$error = 'Invalid username or e-mail address.';
} else if( ! email_exists( $email ) ) {
$error = 'There is no user registered with that email address.';
} else {
$random_password = wp_generate_password( 12, false );
$user = get_user_by( 'email', $email );
$update_user = wp_update_user( array (
'ID' => $user->ID,
'user_pass' => $<PASSWORD>
)
);
// if update user return true then lets send user an email containing the new password
if( $update_user ) {
$to = $email;
$subject = 'Your new password';
$sender = get_option('name');
$message = 'Your new password is: '.$<PASSWORD>;
$headers[] = 'MIME-Version: 1.0' . "\r\n";
$headers[] = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers[] = "X-Mailer: PHP \r\n";
$headers[] = 'From: '.$sender.' <'.$email.'>' . "\r\n";
$mail = wp_mail( $to, $subject, $message, $headers );
if( $mail )
$success = 'Check your email address for your new password.';
?>
<script>
//change the url to the page in your site you want to see after password reset is done:
document.location="<?php echo bloginfo('url');?>";
</script>
<?php
} else {
$error = 'Oops something went wrong updating your account.';
}
}
}
?>
<form method="post">
<fieldset>
<p>Please enter your email address. You will receive a temporary password via email.</p>
<p><label for="user_login">E-mail:</label>
<input type="text" name="email" id="user_login" value="" />
<input type="hidden" name="action" value="reset" />
<input type="submit" value="Get New Password" class="button" id="submit" />
</p>
</fieldset>
</form>
<file_sep><?php global $post; $video = get_post_meta( $post->ID, '_cmb_lecture_video', true ); if( $video != '' ) : ?>
<?php echo apply_filters( 'the_content', get_post_meta( get_the_ID(), $prefix . '_cmb_video', true ) ); ?>
<?php endif; ?><file_sep><?php get_header(); ?>
<div class="row">
<div class="small-12 large-9 columns">
<?php
if(is_home()) {
$id=771;
$post = get_post($id);
$content = apply_filters('the_content', $post->post_content);
$title = apply_filters('the_title', $post->post_title);
echo '<h2>' . $title . '</h2>';
echo $content;
}
?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns main">
<?php
$term_list = wp_get_post_terms( $post->ID, 'section', array("fields" => "all") );
?>
<h6>
<?php
foreach($term_list as $term_single) {
echo $term_single->name;
}
?>
</h6>
<h3 itemprop="name" class="page-title"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h3>
<?php get_template_part('parts/ethicalrecord/ethical', 'record'); ?>
<?php if(has_post_thumbnail()) { ?>
<div class="row">
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns">
<?php the_excerpt(); ?>
<?php get_template_part('parts/issue/read', 'issue'); ?>
</div>
</div>
<?php } else { ?>
<?php the_excerpt(); ?>
<?php get_template_part('parts/issue/read', 'issue'); ?>
<?php } ?>
</div>
</div>
<?php endwhile; ?>
<div class="small button-group">
<?php wp_pagenavi(); ?>
</div>
<?php endif; ?>
</div>
<aside class="small-12 large-3 columns">
<?php get_template_part('sidebar'); ?>
</aside>
</div>
<?php get_footer(); ?><file_sep>{
"name": "Artists Room",
"options": [
{
"name": "Power",
"overlay": "power",
"icon": "ch-plug"
},
{
"name": "Dimensions",
"overlay": "dimensions",
"icon": "ch-enlarge"
}
],
"rooms": [
{
"name": "Boardroom",
"capacity": "16",
"overlay": "boardroom"
},
{
"name": "U Shape",
"capacity": "15",
"overlay": "ushape"
},
{
"name": "Theatre",
"capacity": "16",
"overlay": "theatre"
}
]
}<file_sep> <?php
$args = array (
'connected_type' => 'issue2post',
'connected_items' => $post,
'nopaging' => true,
);
$issue = new WP_Query( $args );
if ( $issue->have_posts() ) : while ( $issue->have_posts() ) : $issue->the_post();
?>
<div class="row">
<div <?php post_class('small-12 large-12 columns'); ?>>
<?php if( has_tag() ) { ?>
<p><i class="ch-tag" aria-hidden="true"></i><?php the_tags('', ', ', ''); ?></p>
<?php } else { ?>
<?php } ?>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<?php get_template_part('parts/ethicalrecord/ethical', 'record'); ?>
</div>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
?><file_sep><h3 class="center">Ethical Record</h3>
<?php
$args = array(
'post_type' => 'ethicalrecord',
);
$ethical = new WP_Query( $args );
if ( $ethical->have_posts() ) : while ( $ethical->have_posts() ) : $ethical->the_post();
?>
<div <?php post_class('row listing'); ?>>
<div class="small-12 columns">
<div class="postdata">
<?php
$term_list = wp_get_post_terms( $post->ID, 'section', array("fields" => "all") );
?>
<h6>
<?php
foreach($term_list as $term_single) {
echo $term_single->name;
}
?>
</h6>
<h3 itemprop="name" class="page-title"><a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>"><?php echo the_title(); ?></a></h3>
<?php get_template_part('parts/ethicalrecord/ethical', 'record'); ?>
</div>
</div>
<?php if(has_post_thumbnail()) { ?>
<div class="small-12 large-4 columns">
<a href="<?php the_permalink(); ?>" rel="permalink" title="Permalink to <?php the_title(); ?>" class="th"><?php the_post_thumbnail('related'); ?></a>
</div>
<div class="small-12 large-8 columns entry-content description summary" itemprop="description">
<?php } else { ?>
<div class="small-12 large-12 columns entry-content description summary" itemprop="description">
<?php } ?>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="button"><i class="ch-book" aria-hidden="true"></i> View "<?php the_title(); ?>"</a></p>
</div>
</div>
<?php
endwhile;
endif;
wp_reset_query();
?>
<div class="row">
<div class="small-12 columns">
<p><a href="<?php echo tribe_get_events_link() ?>" class="button"><?php _e( '<i aria-hidden="true" class="ch-book"></i> More from the Ethical Record', 'ch' ) ?></a></p>
</div>
</div>
<file_sep><ul class="taxonomies">
<?php
$taxonomy = 'decade';
$orderby = 'name';
$show_count = 0;
$pad_counts = 0;
$hierarchical = 1;
$title = '';
$args = array (
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => 0
);
wp_list_categories($args)
?>
</ul><file_sep><?php
$args = array (
'connected_type' => 'pdf_to_event',
'connected_items' => $post,
'nopaging' => true,
);
$sunday_pdf = new WP_Query( $args );
if ($sunday_pdf->have_posts()) : while ($sunday_pdf->have_posts()) : $sunday_pdf->the_post();
?>
<a href="<?php global $post; $text = get_post_meta( $post->ID, '_cmb_pdf', true ); echo $text; ?>" title="<?php the_title_attribute(); ?>" class="button"><i class="ch-download"></i> Download <br /><?php the_title(); ?></a><br />
<?php
endwhile;
endif;
wp_reset_postdata();
?><file_sep><div class="hide">
<div itemprop="image" itemscope itemtype="http://schema.org/ImageObject">
<?php $image_data = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<?php $image_width = $image_data[1]; ?>
<?php $image_height = $image_data[2]; ?>
<img src="<?php the_post_thumbnail_url(); ?>" itemprop="url">
<meta itemprop="height" content="<?php echo $image_width; ?>" />
<meta itemprop="width" content="<?php echo $image_height; ?>" />
</div>
Written by:
<span itemscope itemprop="author" itemtype="http://schema.org/Person">
<span itemprop="name">
<a itemprop="url" href="Author URL"><?php echo get_the_author_meta( 'user_nicename' ); ?></a>
</span>
</span>
Published by:
<span itemscope itemprop="publisher" itemtype="http://schema.org/Organization">
<span itemprop="name"><a itemprop="url" href="<?php echo bloginfo( 'url' ); ?>"><?php echo get_theme_mod('ch_org'); ?></a></span>
<div itemprop="logo" itemscope itemtype="https://schema.org/ImageObject">
<img src="<?php echo get_theme_mod('ch_logo'); ?>"/>
<meta itemprop="url" content="<?php echo get_theme_mod( 'ch_logo' ); ?>">
</div>
</span>
Copyright holder:
<span itemscope itemprop="sourceOrganization" itemtype="http://schema.org/Organization">
<span itemprop="name"><a itemprop="url" href="<?php echo bloginfo( 'url' ); ?>"><?php echo get_theme_mod('ch_org'); ?></a></span>
<img itemprop="logo" src="<?php echo get_theme_mod( 'ch_logo' ); ?>" />
</span>
</div><file_sep><?php
function ch_sidebars() {
$args = array(
'id' => 'right',
'class' => 'right',
'name' => __( 'Right Sidebar', 'ch' ),
);
register_sidebar( $args );
$args = array(
'id' => 'joinsidebar',
'class' => 'joinsidebar',
'name' => __( 'Join/Donate Sidebar', 'ch' ),
);
register_sidebar( $args );
$args = array(
'id' => 'p2psidebar',
'class' => 'p2psidebar',
'name' => __( 'Connected Items Sidebar', 'ch' ),
);
register_sidebar( $args );
$args = array(
'id' => 'footer_left',
'class' => 'footer_left',
'name' => __( 'Footer Left', 'ch' ),
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h2 class="rounded">',
'after_title' => '</h2>',
);
register_sidebar( $args );
$args = array(
'id' => 'footer_right',
'class' => 'footer_right',
'name' => __( 'Footer Right', 'ch' ),
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h2 class="rounded">',
'after_title' => '</h2>',
);
register_sidebar( $args );
$args = array(
'id' => 'woosidebar',
'class' => 'woosidebar',
'name' => __( 'Shop Sidebar', 'ch' ),
);
register_sidebar( $args );
}
add_action( 'widgets_init', 'ch_sidebars' );<file_sep><?php global $post; $date2 = get_post_meta( $post->ID, '_cmb_lecdate2', true ); if( $date2 != '' ) : ?>
<h6>Lecture date: <?php echo date_i18n('D, jS M, Y', $date2); ?></h6>
<?php else : ?>
<?php global $post; $date = get_post_meta( $post->ID, '_cmb_lecdate', true ); if( $date != '' ) : ?>
<h6>Lecture date: <?php echo date('D, jS M, Y', strtotime($date)); ?></h6>
<?php endif; ?>
<?php endif; ?><file_sep><?php
/**
* List View Single Event
* This file contains one event in the list view
*
* Override this template in your own theme by creating a file at [your-theme]/tribe-events/list/single-event.php
*
* @package TribeEventsCalendar
*
*/
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
// Setup an array of venue details for use later in the template
$venue_details = tribe_get_venue_details();
// Venue microformats
$has_venue_address = ( ! empty( $venue_details['address'] ) ) ? ' location' : '';
// Organizer
$organizer = tribe_get_organizer();
$website = tribe_get_event_website_url();
$price = get_post_meta( get_the_ID(), '_cmb_tickets', true );
$free = get_post_meta( get_the_ID(), '_cmb_free', true );
?>
<div class="small-12 columns">
<!-- Event Cost -->
<?php if ( $free === 'on' ) : ?>
<div class="tribe-events-event-cost">
<span>Free</span>
</div>
<?php endif; ?>
<?php if ( $price != '' ) : ?>
<div class="tribe-events-event-cost">
<span><?php echo $price; ?></span>
</div>
<?php endif; ?>
<!-- Event Title -->
<div class="postdata">
<?php do_action( 'tribe_events_before_the_event_title' ) ?>
<h5 class="tribe-events-single-section-title aligncenter"><?php echo tribe_get_organizer() ?> presents: </h5>
<h3 class="entry-title summary">
<a class="url" href="<?php echo esc_url( tribe_get_event_link() ); ?>" title="<?php the_title_attribute() ?>" rel="bookmark">
<?php the_title() ?>
</a>
</h3>
<?php do_action( 'tribe_events_after_the_event_title' ) ?>
<!-- Event Meta -->
<?php do_action( 'tribe_events_before_the_meta' ) ?>
<div class="tribe-events-event-meta vcard">
<div class="author <?php echo esc_attr( $has_venue_address ); ?>">
<!-- Schedule & Recurrence Details -->
<div class="updated published time-details">
<?php echo tribe_events_event_schedule_details() ?>
</div>
<?php if ( $venue_details ) : ?>
<!-- Venue Display Info -->
<div class="tribe-events-venue-details">
<?php echo implode( ', ', $venue_details ); ?>
</div> <!-- .tribe-events-venue-details -->
<?php endif; ?>
</div>
</div><!-- .tribe-events-event-meta -->
<?php do_action( 'tribe_events_after_the_meta' ) ?>
</div>
</div>
<div class="small-12 large-4 columns">
<!-- Event Image -->
<?php echo tribe_event_featured_image( null, 'medium' ) ?>
</div>
<div class="small-12 large-8 columns">
<!-- Event Content -->
<?php do_action( 'tribe_events_before_the_content' ) ?>
<div class="tribe-events-list-event-description tribe-events-content description entry-summary">
<?php the_excerpt() ?>
<?php if(get_post_meta( get_the_ID(), '_sundayconcert_description', true ) != ''){ ?>
<div class="alert callout">
<?php echo wpautop(get_post_meta( get_the_ID(), '_sundayconcert_description', true )); ?>
</div>
<?php } ?>
<p>
<a href="<?php the_permalink(); ?>" class="button"><i class="ch-calendar" aria-hidden="true"></i> View <?php the_title(); ?></a>
<?php if ( ! empty( $website ) ) : ?>
<a href="<?php echo $website; ?>" class="tribe-events-button">BOOK NOW</a>
<?php endif ?>
</p>
<div class="callout secondary">
<div class="row">
<div class="small-12 large-6 columns eventCategory">
<?php echo tribe_get_event_categories(); ?>
</div>
<div class="small-12 large-6 columns">
<div>Organiser:</div>
<ul class="tribe-event-categories">
<li><span class="vcard author"><span class="fn"><?php echo tribe_get_organizer_link() ?></span></span></li>
</ul>
</div>
</div>
</div>
<?php if ( tribe_get_cost() ) : ?>
<div class="tribe-events-event-cost">
<span><?php echo tribe_get_cost( null, true ); ?></span>
</div>
<?php endif; ?>
</div><!-- .tribe-events-list-event-description -->
</div>
<?php
do_action( 'tribe_events_after_the_content' );
<file_sep>/*!
* Planit - jQuery Plugin
* Version: 3.5
* @requires jQuery v1.6 or later
*
* Copyright 2015 Panaround - <EMAIL>
*
*/
(function($) {
"use strict";
$.fn.planit = function(options) {
var defaults = {
basepath: '/wp-content/themes/conway-hall/planit/',
roomName: 'room-name',
userAgentDetection: false,
userAgentIsMobile: false,
mobileBreakpoint: 750
},
floorplanHeight,
currentLayout,
currentContext = 'plan',
previousContext = 'plan',
config = {layouts:[],settings:{},gallery:[]},
imgUrls = [],
selectedGalleryImage = {},
views = 1,
$container = $(this);
var settings = $.extend( true, {}, defaults, options );
var isMobile = checkIfMobile(settings);
$(function() {
loadConfig(function() {
preloadImages(imgUrls, function() {
appendToHead(function() {
initFB();
render(function() {
initCarousel();
initSwipe();
initScrollbars();
checkIfMobile(settings);
if ($('#planit').width() >= 500) {
$('#planit').removeClass('menu_hidden');
$('#menu_toggle').removeClass('active');
smoothTransition();
}
});
});
});
});
});
/*===============*\
|| LOAD CONFIG ||
\*===============*/
function loadConfig(callback) {
var xmlPath = settings.basepath + '/' + settings.roomName + '/xml/config.xml';
$.get(xmlPath, function(xmldata) {
$(xmldata).find('layout').each(function() {
var layout = {
layout: $(this).attr('title'),
capacity: $(this).find('capacity').text()
};
config.layouts.push(layout);
imgUrls.push(settings.basepath + '/' + settings.roomName + '/floorplans/' + $(this).attr("title") + '.' + $(xmldata).find('layoutFileType').text());
if (currentLayout === undefined) currentLayout = $(this).attr("title");
});
config.settings.planTitle = $(xmldata).find('planTitle').text();
config.settings.layoutFileType = $(xmldata).find('layoutFileType').text();
config.settings.showVirtualTour = ($(xmldata).find('showVirtualTour').text() === "true");
config.settings.showGallery = ($(xmldata).find('showGallery').text() === "true");
config.settings.showOptions = ($(xmldata).find('showOptions').text() === "true");
config.settings.showEnquiry = ($(xmldata).find('showEnquiry').text() === "true");
if ($(xmldata).find('showEnquiry').text() === "true") config.settings.enquiryEmailAddress = $(xmldata).find('enquiryEmailAddress').text();
config.settings.primaryColour = $(xmldata).find('primaryColour').text();
config.settings.secondaryColour = $(xmldata).find('secondaryColour').text();
config.settings.options = [];
config.settings.gallery = [];
if (config.settings.showVirtualTour) views += 1;
if (config.settings.showGallery) views += 1;
// options
$(xmldata).find('option').each(function() {
if ($(this).text() === "true") {
config.settings.options.push({
option: $(this).attr('title'),
id: $(this).attr('id'),
name: $(this).data('name')
});
}
});
// gallery
$(xmldata).find('image').each(function() {
config.settings.gallery.push({
title: $(this).attr('title'),
filename: $(this).text(),
});
if (selectedGalleryImage.title === undefined) selectedGalleryImage.title = $(this).attr('title');
});
selectedGalleryImage.number = 1;
settings = $.extend( true, {}, settings, config.settings );
if (typeof callback === "function") {
callback();
}
});
}
/*==================*\
|| PRELOAD IMAGES ||
\*==================*/
function preloadImages(imgUrls, callback) {
var i,
j,
loaded = 0;
for (i = 0, j = imgUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == imgUrls.length && (typeof callback === "function")) {
callback();
}
};
img.src = src;
} (new Image(), imgUrls[i]));
}
}
/*======================================*\
|| ADD FILE DEPENDENCIES TO PAGE HEAD ||
\*======================================*/
function appendToHead(callback) {
var headLayout = '';
var scripts = ['jquery.printarea.min.js','jquery.fancybox.min.js','flash-detection.min.js','swfobject.min.js','jquery.mCustomScrollbar.min.js','jquery.touchSwipe.min.js','jquery.jcarousel.min.js','jquery.tooltip.min.js','tour.min.js'];
for (var i = scripts.length - 1; i >= 0; i--) {
headLayout += '<script type="text/javascript" src="' + settings.basepath + '/global/js/' + scripts[i] + '"></script>';
}
headLayout += '<link rel="stylesheet" type="text/css" href="' + settings.basepath + '/global/lightwindow/jquery.fancybox.min.css" media="screen" />';
headLayout += '<link rel="stylesheet" type="text/css" href="' + settings.basepath + '/global/css/style.css" media="screen" />';
headLayout += '<link rel="stylesheet" type="text/css" href="' + settings.basepath + '/global/css/skin.css" media="screen" />';
headLayout += '<link rel="stylesheet" type="text/css" href="' + settings.basepath + '/global/css/jquery.mCustomScrollbar.min.css" media="screen" />';
headLayout += '<link rel="stylesheet" type="text/css" href="' + settings.basepath + '/global/css/print.min.css" media="print" />';
$('head').append(headLayout);
if (typeof callback === "function") {
callback();
}
}
/*============================*\
|| COMPONENTS TO INITIALISE ||
\*============================*/
function initFB() {
$('.fancybox').fancybox({
'scrolling': 'no'
});
}
function initCarousel() {
$('#mycarousel').jcarousel({
auto: true,
vertical: true,
scroll: 1,
wrap: 'last',
itemFallbackDimension: 105
});
$('.jcarousel-container-vertical').outerHeight($('#planit').height()-80);
}
function initSwipe() {
$("#gallery_display").swipe( {
swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
swipeHandler(event, direction, distance, duration, fingerCount, fingerData);
},
threshold:0
});
}
function initScrollbars() {
$(".jcarousel-container-vertical").mCustomScrollbar({
scrollButtons:{enable:false},
scrollbarPosition:"outside"
});
}
/*==========*\
|| RENDER ||
\*==========*/
function render(callback) {
$container.append(
$('<div>').attr('id', 'planit_container').append(
getGallery(),
getPlanitLeft(),
getPlanitRight()
),
getLightbox()
);
// check to see if dom has loaded required parts of page, hide preloader after successful detection
var poller = window.setInterval(function(){
var detected = document.getElementById('marker');
if (detected) {
window.clearInterval(poller);
$(detected).remove();
$('#preloader').hide();
setImagePosition();
if (typeof callback === "function") {
callback();
}
}
}, 100);
}
/*===========================*\
|| UPDATE WINDOW ON RESIZE ||
\*===========================*/
$(window).resize(function() {
isMobile = checkIfMobile(settings);
if (currentContext == 'plan') setImagePosition();
if (currentContext == 'gallery') {
resizeGalleryImage(null, $("#gallery_display img"));
$('.jcarousel-container-vertical').outerHeight($('#planit').height()-80);
}
if ($('#planit').width() < 500) {
if (!$('#planit').hasClass('menu_hidden')) {
$('#menu_toggle').fadeOut(function() {
$(this).addClass('active');
});
$('#planit').addClass('menu_hidden');
smoothTransition();
}
} else if ($('#menu_toggle').is(':hidden')) {
$('#menu_toggle').fadeIn();
$('#planit').removeClass('menu_hidden');
smoothTransition();
}
});
/*=====================*\
|| CONSTITUENT PARTS ||
\*=====================*/
function getPlanitLeft() {
var capacities = $('<ul>').attr('id', 'capacities'),
node;
$.each(config.layouts, function( index, entry ) {
node = $('<li data-current-layout="' + entry.layout + '">' + prettyPrint(entry.layout) + '<span>' + entry.capacity + '</span></li>');
if (entry.layout == currentLayout) {
node.addClass('selected');
}
capacities.append(node);
});
var pLeft = '<div id="planit_left"><div class="planit_left_col capacities round"><div class="title round">Layouts & Capacities</div>' +
capacities.prop('outerHTML') + '</div>';
if (settings.showOptions) {
pLeft += '<div class="planit_left_col options round"><div class="title round">Options</div><ul>';
var counter;
$.each(settings.options, function(key, value) {
if (counter === undefined) counter = key;
if (counter % 2 === 0) pLeft += ' <li>';
pLeft += '<a id="' + value.id + '" href="#" data-alt="' + value.id + '_mob"><div><i class="icon-' + value.id + '" aria-hidden="true"></i></div><span>' + value.name + '</span></a>';
counter += 1;
if (counter % 2 === 0) pLeft += ' </li>';
});
if (settings.showEnquiry === true) pLeft += '<li><a class="enquire" style="background:' + settings.secondaryColour + '" href="mailto:' + settings.enquiryEmailAddress + '"><span>Enquire about this room</span></a></li>';
pLeft += '</ul></div>';
}
pLeft += '</div>';
return pLeft;
}
function getPlanitRight() {
var layouts = $('<select>').attr('id', 'layouts-select'),
capacity,
node;
$.each(config.layouts, function( index, entry ) {
node = $('<option value="' + entry.layout + '" data-capacity="' + entry.capacity + '">' + prettyPrint(entry.layout) + '</option>');
layouts.append(node);
if (index === 0) capacity = entry.capacity;
});
var mobileTopNav = '<div id="top-bar-mobile"><div id="floorplan_title_mobile">' + settings.planTitle + '</div>' +
'<div id="mobile_room_select">' + // plan
'<div><div>Room Layout Style</div><div class="left">Capacity</div></div>' +
'<div><div>' + layouts.prop('outerHTML') + '</div><div><span class="capacity">' + capacity + '</span></div></div></div>';
if (settings.showGallery === true) {
mobileTopNav += '<div id="mobile_gallery">' + // gallery
'<div><div>Gallery</div></div>' +
'<div><div id="current-image-title">' + settings.gallery[0].title + '</div><div><span class="current-image">1</span> of ' + settings.gallery.length + '</div></div></div>';
}
mobileTopNav += '<div id="mobile_virtual_tour"><div>Virtual Tour</div></div></div>'; // tour
var pRight = '<div id="planit_right"><div id="main_content_panel"><div id="preloader"><div></div></div>' +
mobileTopNav +
'<div id="plan_info"><a href="#" id="menu_toggle" class="active"><span></span></a><div id="floorplan_title">' + settings.planTitle + '</div></div>' +
'<div id="gallery_display"></div>' +
'<div id="panaround_virtual_tour"><div id="html5_tour"></div></div><div id="planit_floorplan_display">' +
'<img id="image_floorplan_base" src="' + settings.basepath + '/' + settings.roomName + '/floorplans/base.jpg" />' +
'<img id="current_layer" src="' + settings.basepath + '/' + settings.roomName + '/floorplans/' + currentLayout + '.' + settings.layoutFileType + '" /><div id="marker"></div>';
// Overlay images
$.each(settings.options, function(key, value) {
pRight += '<img id="image_' + value.id + '" class="overlays" src ="' + settings.basepath + '/' + settings.roomName + '/floorplans/' + value.id + '.svg" />';
});
pRight += '</div><div id="swipe-message"><img src="' + settings.basepath + '/global/img/swipe.svg">Swipe left & right to view</div>' +
'<div id="planit_right_footer" class="' + prettyPrint(views) + '">';
if (settings.showOptions) {
pRight += '<div id="mobile_options">';
if (settings.options.length > 0) pRight += '<div class="header">Options</div>';
var counter;
$.each(settings.options, function(key, value) {
if (counter === undefined) counter = key;
pRight += '<a id="' + value.id + '_mob" href="#" class="button options mob ' + prettyPrint(settings.options.length) + '" data-alt="' + value.id + '"><span><i class="icon-' + value.id + '"></i></span>' + value.name + '</a>';
});
pRight += '</div>';
}
if (settings.showVirtualTour === true) pRight += '<a class="button context_switch" style="background:' + settings.secondaryColour + '" data-context="tour" id="tour_button"><span><i class="icon-tour"></i></span>Virtual Tour</a>';
pRight += '<a class="button context_switch" style="background:' + settings.secondaryColour + '" data-context="plan" id="plan_button"><span><i class="icon-plan"></i></span>Floor Plan</a>';
if (settings.showGallery === true) pRight += '<a class="button context_switch" style="background:' + settings.secondaryColour + '" data-context="gallery" id="gallery_button"><span><i class="icon-gallery"></i></span>Gallery</a>';
pRight += '<a class="fancybox button" style="background:' + settings.secondaryColour + '" id="enlarge_button" href="#lightbox" onclick="javascript:setTimeout(function(){$(window).resize();},250)"><span><i class="icon-enlarge"></i></span>Enlarge</a>';
if (settings.showEnquiry === true) pRight += '<a class="enquire button" style="background:' + settings.secondaryColour + '" href="mailto:' + settings.enquiryEmailAddress + '">Enquire about this room</a>';
pRight += '<a href="http://www.panaround.co.uk" target="_blank"><img id="logo" src="' + settings.basepath + '/global/img/planit-logo.png" alt=""/></a></div></div></div>';
return pRight;
}
function getLightbox() {
var lightbox = '<div id="lightbox" style="position:relative;height:'+floorplanHeight+';">' +
'<img id="lightbox_main_image" src="' + settings.basepath + '/' + settings.roomName + '/floorplans/base.jpg" style="width: 100%; position: relative" />' +
'<img id="lightbox_current_layer" src="' + settings.basepath + '/' + settings.roomName + '/floorplans/' + currentLayout + '.' + settings.layoutFileType + '" style="position:absolute; left:0; top: 0; z-index:2;" />';
$.each(settings.options, function(key, value) {
lightbox += '<img id="lightbox_' + value.id + '" src ="' + settings.basepath + '/' + settings.roomName + '/floorplans/' + value.id + '.' + settings.layoutFileType + '" style="position:absolute; display:none; left:0; top: 0; z-index:3;" />';
});
lightbox += '<a href="#" class="print" rel="lightbox" style="background:' + settings.secondaryColour + '">Print</a></div>';
return lightbox;
}
function getGallery() {
var gallery = '<div id="planit_left_gallery" class="hide"><div class="planit_left_col_gallery gallery round"><div class="title round">Gallery</div>';
gallery += '<div id="secondary_title"><span>' + selectedGalleryImage.title + '</span><div id="current_gallery_image"><span class="current-image">1</span> of ' + settings.gallery.length + '</div></div><ul id="mycarousel" class="jcarousel jcarousel-skin">';
$.each(settings.gallery, function(key, value) {
if (key % 2 === 0) gallery += ' <li>';
gallery += '<a href="' + settings.basepath + '/' + settings.roomName + '/gallery/main/' + value.filename + '" data-current-gallery-image="' + (key+1) + '"><img title="' + value.title + '" class="left" src="' + settings.basepath + '/' + settings.roomName + '/gallery/thumbs/' + value.filename + '" width="70" height="70" style="' + (key === 0 ? "opacity:0.5" : "") + '" alt="" /></a>';
if (key % 2 !== 0) gallery += ' </li>';
});
gallery += '</ul></div>';
if (settings.showEnquiry === true) gallery += '<ul id="gallery_enquire"><li><a class="enquire" style="' + settings.secondaryColour + '" href="mailto:' + settings.enquiryEmailAddress + '"><span>Enquire about this room</span></a></li></ul>';
gallery += '</div>';
return gallery;
}
/*==================*\
|| LAYOUT ACTIONS ||
\*==================*/
function setLayout(layout) {
var src = settings.basepath + "/" + settings.roomName + "/floorplans/" + layout + "." + settings.layoutFileType;
if ($('#current_layer').attr('src') !== src) {
var str = navigator.userAgent;
if (str.match("Safari") && str.match("OS X")) {
var replacementImage = '<img id="current_layer" src="' + src +
'" style="width: ' + $('#image_floorplan_base').width() +
'px; height: ' + $('#image_floorplan_base').height() + 'px; left: ' +
$('#image_floorplan_base').css('left') + '; top: ' +
$('#image_floorplan_base').css('top') + ';" />';
$('#current_layer').remove();
$(replacementImage).insertAfter($('#image_floorplan_base'));
} else {
$('#current_layer').attr('src', src);
}
$('#lightbox_current_layer').attr('src', src);
}
}
$("ul#capacities li").live({
mouseenter: function() {
setLayout($(this).data('current-layout'));
},
mouseleave: function() {
setLayout(currentLayout);
},
click: function(e) {
e.preventDefault();
$("ul#capacities li").removeClass('selected');
currentLayout = $(this).data('current-layout');
setLayout(currentLayout);
$(this).addClass('selected');
$("a#single_image").attr('href', settings.basepath + '/' + settings.roomName + '/floorplans/' + currentLayout + '.' + settings.layoutFileType);
}
});
$('select[id="layouts-select"]').live('change', function() {
setLayout($(this).val());
$('span.capacity').html($(this).find(":selected").data('capacity'));
});
/*=====================*\
|| OPTIONS SELECTION ||
\*=====================*/
$("#planit_container .options ul li a:not(.enquire), #mobile_options a:not(.enquire)").on('click', function(e) {
alert('foo');
e.preventDefault();
var id = $(this).hasClass('mob') ? $(this).data('alt') : $(this).attr('id');
var $currentItem = $('#image_' + id);
var $currentLightbox = $('#lightbox_' + id);
$currentItem.toggle();
$currentLightbox.toggle();
$(this).toggleClass('selected');
$('#' + $(this).data('alt')).toggleClass('selected');
console.log($currentItem);
});
$("#planit_container .options ul li a").on({
mouseenter: function() {
$(this).addClass('hovered');
},
mouseleave: function() {
$(this).removeClass('hovered');
}
});
/*===================*\
|| POSITION IMAGES ||
\*===================*/
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
function setImagePosition() {
var $imgContainer = $('#planit_container #planit_floorplan_display'),
$images = $('#planit_container img#image_floorplan_base, #current_layer, img#image_screens, img#image_dimensions, img#image_power, img#image_hdcams, img#image_fire'),
$lightboxElements = $('#lightbox_main_image, #lightbox_current_layer, #lightbox_screens, #lightbox_power, #lightbox_fire, #lightbox_dimensions, #lightbox_hdcams, .fancybox-skin'),
imageHeight = $('#image_floorplan_base').height(),
containerHeight = $imgContainer.height() - 50, // deduct footer height
imageWidth = $('#image_floorplan_base').width(),
containerWidth = $imgContainer.width();
var topOffset = isMobile ? 140 : $('#planit_container #floorplan_title').height()+parseInt($('#planit_container #floorplan_title').css('top'));
containerHeight = (containerHeight-$('#planit_right_footer').height()-topOffset);
var sizes = calculateAspectRatioFit(imageWidth, imageHeight, containerWidth-40, containerHeight); // includes padding compensation
resize(sizes, $images, containerWidth, containerHeight, 0, topOffset);
var floorplanWidth = $('#lightbox').width();
$('#lightbox').css("height", $('#lightbox_main_image').height() + "px");
$lightboxElements.width(floorplanWidth + "px");
}
function resize(sizes, image, containerWidth, containerHeight, widthOffSetAdjustment, heightOffSetAdjustment, callback) {
if (sizes.height > 10 && sizes.width > 10) { // sane limitations
image.css("width", sizes.width);
image.css("height", sizes.height);
var widthOffSet = (containerWidth - sizes.width) / 2;
image.css("left", widthOffSet+widthOffSetAdjustment);
var heightOffSet = (containerHeight - sizes.height) / 2;
image.css("top", heightOffSet+heightOffSetAdjustment);
}
if (typeof callback === "function") {
callback();
}
}
/*====================*\
|| CONTEXT SWITCHER ||
\*====================*/
$('.context_switch').live("click", function() {
previousContext = currentContext;
currentContext = $(this).data('context');
$('#planit_right_footer').removeClass('one two three');
switch(currentContext) {
case 'plan':
showPlan();
break;
case 'tour':
showTour();
break;
case 'gallery':
showGallery();
break;
}
});
/*================*\
|| MENU CONTROL ||
\*================*/
function hideMenu(type, callback) {
if (type == 'plan') $('#planit_left').addClass('hide');
if (type == 'gallery') $('#planit_left_gallery').addClass('hide');
if (currentContext == 'tour') $('#planit_right').addClass('full');
if(!isMobile) {
setTimeout(function() {
if (typeof callback === "function") {
callback();
}
}, 1000);
} else {
if (typeof callback === "function") {
callback();
}
}
}
function showMenu(type, callback) {
if (type == 'plan') $('#planit_left').removeClass('hide');
if (type == 'gallery') $('#planit_left_gallery').removeClass('hide');
$('#planit_right').removeClass('full');
if(!isMobile) {
setTimeout(function() {
if (typeof callback === "function") {
callback();
}
}, 1000);
} else {
if (typeof callback === "function") {
callback();
}
}
}
/*=============*\
|| FLOORPLAN ||
\*=============*/
function hidePlan(callback) {
$('#planit_floorplan_display').animate({opacity:0},450);
$('#enlarge_button').hide();
$('#lightwindow').hide();
$('#plan_button').show();
$('#mobile_room_select').hide();
$('#mobile_options').hide();
hideMenu('plan', function() {
$('#image_floorplan_base').hide();
$('#planit_floorplan_display').hide();
if (typeof callback === "function") {
callback();
}
});
}
function showPlan() {
$('#enlarge_button').show();
$('#mobile_room_select').show();
if (isMobile) $('#mobile_options').show();
$('#plan_button').hide();
$('#planit_right_footer').addClass(prettyPrint(views));
if (previousContext == 'tour') hideTour(function() { showPlanComplete(); });
if (previousContext == 'gallery') hideGallery(function() { showPlanComplete(); });
}
function showPlanComplete() {
$('#panaround_virtual_tour').hide();
$('#planit_floorplan_display').show();
showMenu('plan', function() {
$('#planit_floorplan_display').animate({opacity:1},450);
$('#image_floorplan_base').show();
$('#lightwindow').show();
setImagePosition();
});
}
/*================*\
|| VIRTUAL TOUR ||
\*================*/
function showTour() {
$('#tour_button').hide();
$('#html5_tour').hide();
$('#planit_right_footer').addClass(prettyPrint(views-1));
$('#mobile_virtual_tour').show();
if (previousContext == 'gallery') hideGallery(function() { showTourComplete(); });
if (previousContext == 'plan') hidePlan(function() { showTourComplete(); });
}
function showTourComplete() {
$('#panaround_virtual_tour').css({opacity: 1});
$('#panaround_virtual_tour').fadeIn(function() {
setTimeout(function() {
$('#html5_tour').css("width", "100%");
$('#html5_tour').css("height", "100%");
embedpano({
swf:settings.basepath + "/global/js/tour.swf",
xml: settings.basepath + "/" + settings.roomName + "/tour/tour.xml",
target: "html5_tour",
html5: "auto",
passQueryParameters: true
});
setTimeout(function() {
$('#html5_tour').fadeIn(300);
}, 200);
}, 200);
});
}
function hideTour(callback) {
$('#panaround_virtual_tour').css({opacity: 0});
$('#html5_tour').html('').hide();
$('#mobile_virtual_tour').hide();
$('#tour_button').show();
if (typeof callback === "function") {
callback();
}
}
/*===========*\
|| GALLERY ||
\*===========*/
function showGallery() {
$('#gallery_button').hide();
$('#mobile_gallery').show();
$('#planit_right_footer').addClass(prettyPrint(views-1));
if (isMobile) showSwipeMessage();
if (previousContext == 'tour') hideTour(function() { showGalleryComplete(); });
if (previousContext == 'plan') hidePlan(function() { showGalleryComplete(); });
}
function showGalleryComplete() {
$('#panaround_virtual_tour').hide();
$('#gallery_display').show().animate({opacity:1},450);
$('#planit_left_gallery').show();
showMenu('gallery', function() {
if (isMobile) {
setTimeout(function() { // allow time for the height transition to play out
setGalleryImage(settings.basepath + '/' + settings.roomName + '/gallery/main/image-1.jpg');
},450);
} else {
setGalleryImage(settings.basepath + '/' + settings.roomName + '/gallery/main/image-1.jpg');
}
});
}
function hideGallery(callback) {
$('#gallery_button').show();
$('#mobile_gallery').hide();
$("#gallery_display img").fadeOut();
$('#gallery_display').animate({opacity:0},450);
hideMenu('gallery', function() {
$(this).hide();
$('#gallery_display').hide();
$('#single_image').hide();
if (typeof callback === "function") {
callback();
}
});
}
function setGalleryImage(imgSrc) {
var oldImg = $("#gallery_display img"),
img = $("<img />");
img.attr('src', imgSrc);
img.unbind("load");
img.bind("load", function () {
resizeGalleryImage(this, img, function() {
oldImg.stop(true).fadeOut(100, function() {
$(this).remove();
});
img.fadeIn(400);
});
});
}
function resizeGalleryImage(image, $image, callback) {
var containerWidth = $('#main_content_panel').width()-100;
var containerHeight =$('#main_content_panel').height()-100-$('#planit_right_footer').height();
var sizes;
if (isMobile) containerHeight -= 104;
if (image!==null) {
sizes = calculateAspectRatioFit(image.width, image.height, containerWidth, containerHeight);
$image.hide();
$("#gallery_display").append($image);
} else {
sizes = calculateAspectRatioFit($image.width(), $image.height(), containerWidth, containerHeight);
}
var topOffset = isMobile ? 150 : 65;
resize(sizes, $image, containerWidth, containerHeight, 50, topOffset, function() {
if (typeof callback === "function") {
callback();
}
});
}
$("#mycarousel a").live({
mouseenter: function() {
$('#secondary_title > span').html($(this).find('img').attr('title'));
$('#current_gallery_image .current-image').html($(this).data('current-gallery-image'));
},
mouseleave: function() {
$('#secondary_title > span').html(selectedGalleryImage.title);
$('#current_gallery_image .current-image').html(selectedGalleryImage.number);
},
click: function(e) {
e.preventDefault();
selectedGalleryImage.title = $(this).find('img').attr('title');
selectedGalleryImage.number = $(this).data('current-gallery-image');
$('#secondary_title > span').html(selectedGalleryImage.title);
$('#current_gallery_image .current-image').html($(this).data('current-gallery-image'));
setGalleryImage(this.href);
$('#mycarousel img').css({opacity: 1});
$(this).find('img').css({opacity: 0.5});
}
});
$('#menu_toggle').live('click', function(e) {
e.preventDefault();
$(this).toggleClass('active');
$('#planit').toggleClass('menu_hidden');
smoothTransition();
});
/*==============================*\
|| MOBILE DETECTION & ACTIONS ||
\*==============================*/
function checkIfMobile(settings) {
var isMobile = settings.userAgentDetection ? settings.userAgentIsMobile : window.innerWidth < settings.mobileBreakpoint;
if (isMobile && !$('#planit').hasClass('mobile')) {
$('#planit').addClass('mobile');
if (currentContext == 'plan') {
setTimeout(function() {
if (currentContext == 'plan') $('#planit.mobile #mobile_options').slideDown();
},1000);
}
smoothTransition(function() {
smoothTransition();
});
} else if (!isMobile && $('#planit').hasClass('mobile')) {
$('#planit').removeClass('mobile');
$('#planit #mobile_options').hide();
$('#planit_right_footer').removeClass('absolute');
smoothTransition();
}
return isMobile;
}
function smoothTransition(callback) {
var interval = setInterval(function () {
setImagePosition();
resizeGalleryImage(null, $("#gallery_display img"));
}, 10);
setTimeout(function() {
clearInterval(interval);
if (isMobile) {
$('#planit_right_footer').addClass('absolute');
} else {
$('#planit_right_footer').removeClass('absolute');
}
if (typeof callback === "function") {
callback();
}
}, 1000);
}
function showSwipeMessage() {
setTimeout(function() {
$('#swipe-message').fadeIn(function() {
setTimeout(function() {
$('#swipe-message').fadeOut();
},1500);
});
}, 500);
}
function swipeHandler(event, direction) {
if (isMobile) {
var currentImageArrNumber = parseInt($('span.current-image').html())-1;
if (direction == 'left') {
if (settings.gallery.length > (currentImageArrNumber+1)) {
var nextImage = settings.gallery[currentImageArrNumber+1];
selectedGalleryImage.title = nextImage.title;
$('#secondary_title > span').html(selectedGalleryImage.title);
setGalleryImage(settings.basepath + '/' + settings.roomName + '/gallery/main/' + nextImage.filename);
$('span.current-image').html(currentImageArrNumber+2);
$('#current-image-title').html(nextImage.title);
}
}
if (direction == 'right') {
if ((currentImageArrNumber-1) >= 0) {
var previousImage = settings.gallery[currentImageArrNumber-1];
selectedGalleryImage.title = previousImage.title;
$('#secondary_title > span').html(selectedGalleryImage.title);
setGalleryImage(settings.basepath + '/' + settings.roomName + '/gallery/main/' + previousImage.filename);
$('span.current-image').html(currentImageArrNumber);
$('#current-image-title').html(previousImage.title);
}
}
}
}
};
/*=====================*\
|| DETECT SCRIPT URI ||
\*=====================*/
var scripts = document.getElementsByTagName("script"),
scriptPath = scripts[scripts.length-1].src;
/*==================*\
|| PRINT FUNCTION ||
\*==================*/
$(function() {
$(".print").live('click', function() {
var container = $(this).attr('rel');
var ua = navigator.userAgent;
// Javascript Browser Detection - Internet Explorer - test for MSIE x.x; True or False
if (/MSIE (\d+\.\d+);/.test(ua) || /rv:11.0/i.test(ua)) {
var divToPrint = document.getElementById(container);
var newWin = window.open();
newWin.document.write(divToPrint.innerHTML);
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
} else {
$('#' + container).printArea();
return false;
}
});
});
/*================*\
|| PRETTY PRINT ||
\*================*/
function prettyPrint(input) {
switch(input) {
case 'ushape':
input = 'U Shape';
break;
case 1:
input = 'one';
break;
case 2:
input = 'two';
break;
case 3:
input = 'three';
break;
case 4:
input = 'four';
break;
default:
break;
}
return input;
}
/*===========*\
|| HELPERS ||
\*===========*/
// Live -> ON
$.fn.extend({
live: function(types, data, fn) {
$(this.context).on(types, this.selector, data, fn);
return this;
}
});
function getCurrentBasePath(url) {
var a = document.createElement('a');
a.href = url;
if (! a.pathname) return url;
a.pathname = a.pathname.replace(/[^/]*$/, '');
return a.href;
}
})($);
<file_sep><?php
class ch_options {
private $key = 'ch_options';
private $metabox_id = 'ch_option_metabox';
protected $title = '';
protected $options_page = '';
private static $instance = null;
private function __construct() {
$this->title = __( 'Site Options', 'ch' );
}
public static function get_instance() {
if( is_null( self::$instance ) ) {
self::$instance = new self();
self::$instance->hooks();
}
return self::$instance;
}
public function hooks() {
add_action( 'admin_init', array( $this, 'init' ) );
add_action( 'admin_menu', array( $this, 'add_options_page' ) );
add_action( 'cmb2_admin_init', array( $this, 'add_options_page_metabox' ) );
}
public function init() {
register_setting( $this->key, $this->key );
}
public function add_options_page() {
$this->options_page = add_menu_page( $this->title, $this->title, 'manage_options', $this->key, array( $this, 'admin_page_display' ) );
add_action( "admin_print_styles-{$this->options_page}", array( 'CMB2_hookup', 'enqueue_cmb_css' ) );
}
public function admin_page_display() {
cmb2_metabox_form( $this->metabox_id, $this->key );
}
function add_options_page_metabox() {
add_action( "cmb2_save_options-page_fields_{$this->metabox_id}", array( $this, 'settings_notices' ), 10, 2 );
$cmb = new_cmb2_box( array(
'id' => $this->metabox_id,
'hookup' => false,
'cmb_styles' => false,
'show_on' => array(
'key' => 'options-page',
'value' => array( $this->key, )
),
) );
$cmb->add_field( array(
'name' => __( 'Organisation Name', 'ch' ),
'id' => 'org',
'type' => 'text',
));
$cmb->add_field( array(
'name' => __( 'Organisation Logo', 'ch' ),
'id' => 'orglogo',
'type' => 'file',
));
$cmb->add_field( array(
'name' => __( 'Error Page Title', 'ch' ),
'id' => '404_title',
'type' => 'text',
));
$cmb->add_field( array(
'name' => __( 'Error Page Content', 'ch' ),
'id' => '404_content',
'type' => 'wysiwyg',
));
}
public function settings_notices( $object_id, $updated ) {
if ( $object_id !== $this->key || empty( $updated ) ) {
return;
}
add_settings_error( $this->key . '-notices', '', __( 'Settings updated.', 'ch' ), 'updated' );
settings_errors( $this->key . '-notices' );
}
public function __get( $field ) {
if ( in_array( $field, array( 'key', 'metabox_id', 'title', 'options_page' ), true ) ) {
return $this->{$field};
}
throw new Exception( 'Invalid property: ' . $field );
}
}
function ch_options() {
return ch_options::get_instance();
}
function ch_get_option( $key = '' ) {
return cmb2_get_option( ch_options()->key, $key );
}
ch_options();<file_sep><meta itemprop="keywords" content="Keywords"/>
<meta itemprop="inLanguage" content="en-GB"/>
<meta itemprop="description" content="<?php echo(get_the_excerpt()); ?>"/>
<meta itemprop="about" content="<?php echo(get_the_excerpt()); ?>"/>
<meta itemprop="isFamilyFriendly" content="True"/>
<meta itemprop="datePublished" content="<?php the_time('c'); ?>"/>
<meta itemprop="dateModified" content="<?php the_modified_date('c'); ?>"/><file_sep><div class="row description">
<div class="postdata small-12 large-6 columns">
<?php global $post; $date2 = get_post_meta( $post->ID, '_cmb_lecdate2', true ); if( $date2 != '' ) : ?>
<h6>Lecture date: <?php echo date_i18n('D, jS M, Y', $date2); ?></h6>
<?php else : ?>
<?php global $post; $date = get_post_meta( $post->ID, '_cmb_lecdate', true ); if( $date != '' ) : ?>
<h6>Lecture date: <?php echo date('D, jS M, Y', strtotime($date)); ?></h6>
<?php endif; ?>
<?php endif; ?>
<h6>Posted on: <time datetime="Publish Date"><?php the_time( 'D, jS M, Y' ); ?></time></h6>
<?php if(get_post_type( get_the_ID() ) == 'ethicalrecord') { ?>
<h6><?php echo ch_reading(); ?></h6>
<?php } ?>
<?php global $post; $author = get_post_meta( $post->ID, '_cmb_author', true ); if( $author != '' ) : ?>
<p>By: <strong><?php global $post; $publisher = get_post_meta( $post->ID, '_cmb_author', true ); echo $publisher; ?></strong>
<?php global $post; $author = get_post_meta( $post->ID, '_cmb_publisher', true ); if( $author != '' ) : ?>
(<?php global $post; $publisher = get_post_meta( $post->ID, '_cmb_publisher', true ); echo $publisher; ?>)
<?php endif; ?>
</p>
<?php global $post; $reviewer = get_post_meta( $post->ID, '_cmb_vpauthor', true ); if( $reviewer != '' ) : ?>
<p>Review by: <?php global $post; $reviewer = get_post_meta( $post->ID, '_cmb_vpauthor', true ); echo $reviewer; ?></p>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="postdata small-12 large-6 columns">
<?php if(is_singular('ethicalrecord')) { ?>
<?php get_template_part('parts/ethicalrecord/related', 'meta'); ?>
<?php } ?>
</div>
</div> | 5d154f5ebd5f01fbf942075e5f3db7a01ca47503 | [
"JavaScript",
"PHP"
] | 61 | PHP | PrydonianDigital/Conway-Hall-2 | 46fed93b05bf42cfda897d4e81aec23e4f4e6a85 | 18723ee64455b995e56f6a8055fcf61ab977a2d2 |
refs/heads/master | <repo_name>herbherbherb/Wiki_Crawler<file_sep>/test_app.py
import os
import tempfile
import pytest
from app import app
import unittest
import unittest
from flask import Flask
from flask_testing import TestCase
import json
"""
Sources:
https://pythonhosted.org/Flask-Testing/
"""
class FlaskrTestCase(unittest.TestCase):
print("Running API Test Cases: ")
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
# Default port is 5000
app.config['LIVESERVER_PORT'] = 5001
# Default timeout is 5 seconds
app.config['LIVESERVER_TIMEOUT'] = 10
self.app = app.test_client()
return app
def test_filter_actor(self):
data = {'name': 'Mark|name=Chris', 'age': '35|age=45|age=73'}
with app.test_client() as c:
c.get('/init')
response = c.get('/actors', query_string = data)
result = json.loads(response.data)
self.assertIn("<NAME>", result['Actors'])
self.assertIn("<NAME>", result['Actors'])
self.assertIn("<NAME>", result['Actors'])
def test_filter_movies(self):
with app.test_client() as c:
c.get('/init')
data1 = {'name': 'The|name=Fine|name=September', 'year': '2015|year=2016|year=1981|year=1987',
'gross': 486434}
response = c.get('/movies', query_string = data1)
result = json.loads(response.data)
self.assertIn("September", result['Movies'])
data2 = {'name': 'The|name=Fine|name=September', 'year': '2015|year=2016|year=1981|year=1987'}
response = c.get('/movies', query_string = data2)
result = json.loads(response.data)
self.assertIn("September", result['Movies'])
self.assertIn("The Great Muppet Caper", result['Movies'])
self.assertIn("So Fine", result['Movies'])
self.assertIn("Zorro, The Gay Blade", result['Movies'])
def test_get_actor(self):
with app.test_client() as c:
c.get('/init')
response = c.get('/actors/Betty Buckley')
result = json.loads(response.data)
answer = {'Actor Age': 69, 'Actor Movies': ['Split'], 'Actor Name': '<NAME>', 'Actor Total Gross': 193, 'Actor Wiki Page': ''}
self.assertEqual(answer, result['Betty Buckley'])
response = c.get('/actors/Betty_Buckley')
result = json.loads(response.data)
answer = {'Actor Age': 69, 'Actor Movies': ['Split'], 'Actor Name': '<NAME>', 'Actor Total Gross': 193, 'Actor Wiki Page': ''}
self.assertEqual(answer, result['Betty Buckley'])
def test_get_movie(self):
with app.test_client() as c:
c.get('/init')
response = c.get('/movies/Blind Date')
result = json.loads(response.data)['Blind Date']
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertEqual(39, result['Movie Box Office'])
self.assertEqual(1987, result['Movie Year'])
response = c.get('/movies/Blind_Date')
result = json.loads(response.data)['Blind Date']
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertEqual(39, result['Movie Box Office'])
self.assertEqual(1987, result['Movie Year'])
def test_update_actors(self):
headers = {'content-type': 'application/json'}
with app.test_client() as c:
data1 = {'age': 27111, 'total_gross': 2414124, 'wiki_page': 'https://en.wikipedia.org/wiki/Bruce_Willis'}
c.get('/init')
response = c.put('/actors/<NAME>', data=json.dumps(data1), headers=headers)
result = json.loads(response.data)['<NAME>']
self.assertEqual(27111, result['Actor Age'])
self.assertEqual(2414124, result['Actor Total Gross'])
self.assertEqual("https://en.wikipedia.org/wiki/Bruce_Willis", result['Actor Wiki Page'])
data2 = {'name': '<NAME>', 'age': 27111, 'total_gross': 2414124, 'wiki_page': 'https://en.wikipedia.org/wiki/Bruce_Willis'}
response = c.put('/actors/<NAME>', data=json.dumps(data2), headers=headers)
result = json.loads(response.data)['<NAME>']
self.assertEqual('<NAME>', result['Actor Name'])
response = c.get('/actors/<NAME>')
self.assertEqual(str(response), "<Response streamed [404 NOT FOUND]>")
def test_update_movies(self):
headers = {'content-type': 'application/json'}
with app.test_client() as c:
data1 = {'date': 2018, 'box_office': 1999, 'wiki_page': 'https://en.wikipedia.org/wiki/Blind_Date_(1987_film)'}
c.get('/init')
response = c.put('/movies/Blind_Date', data=json.dumps(data1), headers=headers)
result = json.loads(response.data)['Blind Date']
self.assertEqual(1999, result['Movie Box Office'])
self.assertEqual(2018, result['Movie Year'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
data2 = {'name': 'Blind Date12', 'date': 2018, 'box_office': 1999, 'wiki_page': 'https://en.wikipedia.org/wiki/Blind_Date_(1987_film)'}
response = c.put('/movies/Blind_Date', data=json.dumps(data2), headers=headers)
result = json.loads(response.data)['Blind Date12']
self.assertEqual(1999, result['Movie Box Office'])
self.assertEqual('Blind Date12', result['Movie Name'])
self.assertEqual(2018, result['Movie Year'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
response = c.get('/movies/Blind_Date')
self.assertEqual(str(response), "<Response streamed [404 NOT FOUND]>")
def test_delete_actor(self):
headers = {'content-type': 'application/json'}
with app.test_client() as c:
c.get('/init')
response = c.get('/actors/Bruce_Willis')
result = json.loads(response.data)['<NAME>']
self.assertEqual(61, result['Actor Age'])
self.assertEqual(562709189, result['Actor Total Gross'])
response = c.delete('/actors/Bruce_Willis')
self.assertEqual(str(response), "<Response streamed [200 OK]>")
response = c.get('/actors/Bruce_Willis')
self.assertEqual(str(response), "<Response streamed [404 NOT FOUND]>")
def test_delete_movie(self):
headers = {'content-type': 'application/json'}
with app.test_client() as c:
c.get('/init')
response = c.get('/movies/Blind Date')
result = json.loads(response.data)['Blind Date']
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertIn('<NAME>', result['Movie Actors'])
self.assertEqual(39, result['Movie Box Office'])
self.assertEqual(1987, result['Movie Year'])
response = c.delete('/movies/Blind Date')
self.assertEqual(str(response), "<Response streamed [200 OK]>")
response = c.get('/movies/Blind Date')
self.assertEqual(str(response), "<Response streamed [404 NOT FOUND]>")
def test_add_actors(self):
headers = {'content-type': 'application/json'}
with app.test_client() as c:
c.get('/init')
data1 = {'age': 21,
'total_gross': 99999, 'wiki_page': 'https://en.wikipedia.org/wiki/Herbert_Wang',
'movies': ["Blind Date", "The Verdict"]}
response = c.post('/actors', data=json.dumps(data1), headers=headers)
self.assertEqual(str(response), "<Response streamed [400 BAD REQUEST]>")
data2 = {'name': '<NAME>', 'age': 21,
'total_gross': 99999, 'wiki_page': 'https://en.wikipedia.org/wiki/Herbert_Wang',
'movies': ["Blind Date", "The Verdict"]}
response = c.post('/actors', data=json.dumps(data2), headers=headers)
self.assertEqual(str(response), "<Response streamed [201 CREATED]>")
response = c.get('/actors/<NAME>')
result = json.loads(response.data)['<NAME>']
answer = {'Actor Age': 21, 'Actor Movies': ['Blind Date', 'The Verdict'], 'Actor Name': '<NAME>', 'Actor Total Gross': 99999, 'Actor Wiki Page': 'https://en.wikipedia.org/wiki/Herbert_Wang'}
self.assertEqual(answer, result)
response = c.get('/movies/Blind Date')
result = json.loads(response.data)['Blind Date']
self.assertIn('<NAME>', result['Movie Actors'])
def test_add_movies(self):
headers = {'content-type': 'application/json'}
with app.test_client() as c:
c.get('/init')
data1 = {'date': 2018,
'box_office': 123456, 'wiki_page': 'https://en.wikipedia.org/wiki/Fun_Movie_by_Herbert_Wang',
'actors': ["<NAME>", "<NAME>"]}
response = c.post('/movies', data=json.dumps(data1), headers=headers)
self.assertEqual(str(response), "<Response streamed [400 BAD REQUEST]>")
data2 = {'name': 'Fun Movie by <NAME>', 'date': 2018,
'box_office': 123456, 'wiki_page': 'https://en.wikipedia.org/wiki/Fun_Movie_by_Herbert_Wang',
'actors': ["<NAME>", "<NAME>"]}
response = c.post('/movies', data=json.dumps(data2), headers=headers)
self.assertEqual(str(response), "<Response streamed [201 CREATED]>")
response = c.get('/movies/Fun Movie by <NAME>')
result = json.loads(response.data)['Fun Movie by <NAME>']
answer = {'Movie Actors': ['<NAME>'], 'Movie Box Office': 123456, 'Movie Name': 'Fun Movie by <NAME>', 'Movie Wiki Page': 'https://en.wikipedia.org/wiki/Fun_Movie_by_Herbert_Wang', 'Movie Year': 2018}
self.assertIn('Betty Buckley', result['Movie Actors'])
self.assertEqual(123456, result['Movie Box Office'])
self.assertEqual(2018, result['Movie Year'])
response = c.get('/actors/Betty Buckley')
result = json.loads(response.data)['Betty Buckley']
self.assertIn('Fun Movie by <NAME>', result['Actor Movies'])
if __name__ == '__main__':
unittest.main()<file_sep>/model/Scraper/spider.py
import re
import scrapy
from scrapy import Spider
from bs4 import BeautifulSoup
from dateparser import parse as parse_date
from .item import Actor, Movie
import config
"""
Source:
https://github.com/alecxe/scrapy-fake-useragent
https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/
https://github.com/horizon-blue/wiki-crawler
"""
wiki_root = "https://en.wikipedia.org"
wiki_start = config.wiki_start
# wiki_start = "https://en.wikipedia.org/wiki/Johnny_Depp"
# wiki_start = "https://en.wikipedia.org/wiki/Jennifer_Lawrence"
divider = "============================================================================"
class MySpider(scrapy.Spider):
allowed_domains = ["en.wikipedia.org"]
name = "uniqueSpider"
custom_settings = {
"DOWNLOADER_MIDDLEWARES": {
"scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,
"scrapy_fake_useragent.middleware.RandomUserAgentMiddleware": 400,
},
"EXTENSIONS": {
"scrapy.extensions.closespider.CloseSpider": 1,
},
"ITEM_PIPELINES": {
"model.Scraper.pipeline.JsonWriterPipeline": 300,
},
"CLOSESPIDER_ITEMCOUNT": config.CLOSESPIDER_ITEMCOUNT,
"COOKIES_ENABLED": False,
"DOWNLOAD_DELAY": 0.1,
}
"""
* Parse function that scrappy will call
"""
def start_requests(self):
yield scrapy.Request(wiki_start, meta={'_movie_': False, '_movie_list_': False})
"""
* Parse function that scrappy will call
"""
def parse(self, response):
if response.meta["_movie_"] == True:
yield from self.movie_parser(response)
elif response.meta["_movie_list_"] == True:
yield from self.movieList_parser(response)
else:
yield from self.actor_parser(response)
"""
* Function to parse given movie information, include movie name, movie grossing, movie date, movie casts included, and wiki page link
"""
def movie_parser(self, response):
ret = {}
try:
bs, movie_name = self.parser_helper(response)
movie_actor = self.get_movie_actor(bs)
movie_gross = self.get_movie_gross(bs)
new_movie = Movie(name=movie_name, gross=movie_gross, \
date=self.get_movie_date(bs), actors=movie_actor, page=response.request.url)
yield new_movie
for cast in movie_actor:
if movie_gross != None:
yield scrapy.Request(wiki_root + cast, meta={'_movie_': False, '_movie_list_': False})
except AttributeError:
yield ret
"""
* Helper function that extract movie’s release date, information is crawled from the side panel
"""
def get_movie_date(self, bs):
movie_date = None
try:
movie_date = bs.find("table", attrs={"class": "infobox"}).find("span", attrs={"class": "bday dtstart published updated"}).text
except AttributeError:
pass
return movie_date
"""
* Given a movie, find all the casts that play this movie. Crawl the info from side panel.
"""
def get_movie_actor(self, bs):
movie_actor = []
try:
casts = bs.find("table", attrs={"class": "infobox"}).find(text="Starring").find_parent("tr").find_all("a")
for cast in casts:
if cast.has_attr('href') and not cast['href'].startswith("#"):
movie_actor.append(cast['href'])
except AttributeError:
pass
return movie_actor
"""
* Helper function that converts string currency value into float
"""
def get_movie_gross(self, bs):
ret = None
try:
movie_gross = bs.find("table", attrs={"class": "infobox"}).find(text="Box office").find_parent() \
.find_next_sibling().next_element.strip()
ret = float(movie_gross.replace(r"[(\[].*[)\][^\d.]", "").replace(" ", "").strip('$trbmilon'))
if "million" in movie_gross or "Million" in movie_gross:
ret *= 1e6
if "billion" in movie_gross or "Billion" in movie_gross:
ret *= 1e9
if "trillion" in movie_gross or "Trillion" in movie_gross:
ret *= 1e12
return ret
except (AttributeError, TypeError, ValueError):
return ret
"""
* Function to parse actor information, include name, age, and page
"""
def actor_parser(self, response):
ret = {}
try:
bs, actor_name = self.parser_helper(response)
new_actor = Actor(actor_name=actor_name, actor_age=self.age_parser(bs), page=response.request.url)
film_starting_point = bs.find("span", id="Filmography")
if film_starting_point == None:
film_starting_point = bs.find("span", id="Selected_filmography")
if film_starting_point == None:
yield new_actor
film_starting_point = film_starting_point.find_parent("h2").find_next_sibling()
if "Main" in film_starting_point.get_text():
article_link = film_starting_point.find("a")
if article_link.has_attr('href') and not article_link["href"].startswith("#"):
href = article_link["href"]
yield scrapy.Request(wiki_root + href, meta={'_movie_': False, '_movie_list_': True})
else:
for next_movie in self.directly_crawl(bs):
yield scrapy.Request(wiki_root + next_movie, meta={'_movie_': True, '_movie_list_': False})
yield new_actor
except AttributeError:
yield ret
"""
* If there is for Main article link to click in, then it means the corresponding movie table are under the actor’s page
"""
def directly_crawl(self, bs):
films_hrefs = []
table_starting_point = bs.find("span", id="Filmography").find_parent("h2") \
.find_next_sibling().find_next_sibling()
th_attr = table_starting_point.find_all("th")
hrefs = [th.find("a") for th in th_attr]
for href in hrefs:
if href != None and href.has_attr('href') and not href["href"].startswith("#"):
films_hrefs.append(href['href'])
return films_hrefs
"""
* This is to crawl the movie lists that on a given page, those movies all contain at least 1 common actors.
* Find the first table that contain hyper link and only crawl titles hyper link.
"""
def movieList_parser(self, response):
ret = {}
bs = BeautifulSoup(response.text, 'lxml')
target_table = None
for t in bs.find_all("table"):
if t.find('a') != None:
target_table = t
break
if target_table == None:
yield {}
else:
th_attr = target_table.find_all("th")
hrefs = [th.find("a") for th in th_attr]
for href in hrefs:
if href != None and href.has_attr('href') and not href["href"].startswith("#"):
yield scrapy.Request(wiki_root + href['href'], meta={'_movie_': True, '_movie_list_': False})
"""
* Parse the age from actor page, there are 2 types, actors can be dead or alive
"""
def age_parser(self, bs):
age = 0
try:
actor_age = bs.find("table", attrs={"class": "infobox"}).find("span", attrs={"class": "noprint ForceAgeToShow"})
if actor_age != None:
age = actor_age.get_text().strip()
else:
bs.prettify(formatter=lambda s: s.replace(u'\xa0', ' '))
age = bs.find("table", attrs={"class": "infobox"}) \
.find("th", string="Died").find_next_sibling() \
.get_text().strip()
age = "Died: " + age[age.find('(') : (age.rfind(')') + 1)]
except AttributeError:
age = None
return age
"""
* Generic parser helper that initialize a beautiful soup instance and get the heading for the actors/movies
"""
def parser_helper(self, response):
bs = BeautifulSoup(response.text, 'lxml')
actor_name = bs.find(id="firstHeading").text.replace(r"\(.*\)", "").strip()
return bs, actor_name
<file_sep>/model/graphy.py
import json
from operator import itemgetter
from scrapy import Item
from .Scraper import Actor, Movie
import re
"""
Source:
https://www.python-course.eu/graphs_python.php
https://www.bogotobogo.com/python/python_graph_data_structures.php
"""
class Vertex:
def __init__(self, name, age, gross, date, page, isMovie):
self.name = name
self.age = age
self.gross = gross
self.date = date
self.page = page
self.adjacent = {}
self.isMoive = isMovie
"""
Helper function that forms that string for vertex, there are 2 kinds of
vertex, "actor" vertex and "movie" vertex
"""
def __str__(self):
if self.isMoive:
return "Movie Name: " + str(self.name) + ", Movie Gross: " \
+ str(self.gross) + ", Movie Date: " + str(self.date) + ", Movie Page: " + str(self.page)
else:
return "Actor Name: " + str(self.name) + ", Actor age: " \
+ str(self.age) + ", Actor Page: " + str(self.page)
"""
* Important helper function that adds a new neighbor to a given vertex
"""
def add_neighbor(self, neighbor, weight):
self.adjacent[neighbor] = weight
"""
* Important helper function that return a given vertex's neighbors
"""
def get_connections(self):
return self.adjacent.keys()
"""
Get the weight of an edge
"""
def get_weight(self, neighbor):
return self.adjacent[neighbor]
class myGraph:
def __init__(self):
self.vert_dict = {}
self.movie_vertices = 0
self.actor_vertices = 0
"""
Helper funtion to go thru vert_dict
"""
def __iter__(self):
return iter(self.vert_dict.values())
"""
Return all vertices that are "movie" vertices
"""
def get_all_movie_name(self):
ret = []
for i in self.vert_dict.keys():
if self.vert_dict[i].isMoive:
ret.append(i)
return ret
"""
Return all vertices that are "actor" vertices
"""
def get_all_actor_name(self):
ret = []
for i in self.vert_dict.keys():
if not self.vert_dict[i].isMoive:
ret.append(i)
return ret
"""
* Important helper function to construct the graph, add vertices to graph
"""
def add_vertex_to_graph(self, name, age, gross, date, page, isMovie):
if gross == None:
self.actor_vertices += 1
else:
self.movie_vertices += 1
new_vertex = Vertex(name, age, gross, date, page, isMovie)
self.vert_dict[name] = new_vertex
return new_vertex
"""
Return the name of the vertex
"""
def get_vertex_info(self, name):
if name in self.vert_dict:
return self.vert_dict[name]
else:
return None
"""
* Important helper function to construct the graph, add egde given a
movie name and a actor name
"""
def add_edge(self, actor_name, movie_name, egde_weight):
if self.vert_dict[actor_name] != None:
self.vert_dict[actor_name].add_neighbor(movie_name, egde_weight)
if self.vert_dict[movie_name] != None:
self.vert_dict[movie_name].add_neighbor(actor_name, egde_weight)
"""
Helper function that returns that vertex name
"""
def get_vertices(self):
return self.vert_dict.keys()
"""
Given a year, find all the movies release that year
"""
def get_all_movie_given_year(self, given):
ret = []
for i in self.vert_dict.keys():
if i == None:
continue
if self.vert_dict[i].isMoive and self.vert_dict[i].date != None and self.vert_dict[i].date[0:4] == given:
ret.append(i)
return ret
"""
Given a year, first find all the movies release that year, then find all
unique casts in those movies
"""
def get_all_actor_given_year(self, given):
ret = set()
for m in self.vert_dict.keys():
if self.vert_dict[m].isMoive and self.vert_dict[m].date != None and self.vert_dict[m].date[0:4] == given:
for a in self.get_actors_given_movie(m):
ret.add(a)
return list(ret)
"""
Given a movie name, return the box office gross
"""
def get_movie_gross(self, movie_name):
if movie_name not in self.vert_dict:
return "Given movie does not exists in graph!"
if not self.vert_dict[movie_name].isMoive:
return "Input is a actor name, please enter a valid movie name!"
return movie_name + "'s Gross: $" + str(self.vert_dict[movie_name].gross)
"""
Query the graph to find oldest top K actors
"""
def get_top_oldest(self, topK):
ret = []
for i in self.vert_dict.keys():
if not self.vert_dict[i].isMoive and self.vert_dict[i].age != None:
m = re.search(r"\d", self.vert_dict[i].age)
age = int(self.vert_dict[i].age[m.start(): m.end()+1])
ret.append((self.vert_dict[i].name, age))
return sorted(ret, key=lambda x: x[1], reverse=True)[0:topK]
"""
Query the graph to find the top X actors with the most total grossing value
"""
def get_topK(self, topK):
ret = []
for i in self.vert_dict.keys():
if not self.vert_dict[i].isMoive:
total_gross = 0
for m in self.get_movies_given_actor(self.vert_dict[i].name):
if self.vert_dict[m].gross != None:
total_gross += self.vert_dict[m].gross
ret.append((self.vert_dict[i].name, total_gross))
res = sorted(ret, key=lambda x: x[1], reverse=True)[0:topK]
return [(x[0], "$"+str(x[1])) for x in res]
"""
Helper function that retrive a particular movie information
"""
def get_movie_info(self, given_name):
if given_name not in self.vert_dict:
return "No such movie found!"
ret = self.vert_dict[given_name]
return ("Movie Name: " + ret.name + "\nGross: $" + \
str(ret.gross) + "\nRelease Date: " + str(ret.date) + \
"\nWiki Page: " + ret.page)
"""
Helper function that retrive a particular actor information
"""
def get_actor_info(self, given_name):
if given_name not in self.vert_dict:
return "No such actor found!"
ret = self.vert_dict[given_name]
return ("Actor Name: " + ret.name + "\nAge: " + \
str(ret.age) + "\nWiki Page: " + ret.page)
"""
Given an actor, list which movies the given actor has worked in
"""
def get_movies_given_actor(self, actor_name):
if actor_name not in self.vert_dict:
return "Given actor does not exists in graph!"
return list(self.vert_dict[actor_name].get_connections())
"""
Given a movie, list which actors worked in a movie
"""
def get_actors_given_movie(self, movie_name):
if movie_name not in self.vert_dict:
return "Given movie does not exists in graph!"
return list(self.vert_dict[movie_name].get_connections())
"""
Function that computes which actors have the most connection with other actors
"""
def get_hub_actors(self):
ret = {}
for i in self.vert_dict.keys():
if not self.vert_dict[i].isMoive:
ret[i] = 0
for cur_movie in self.get_movies_given_actor(i):
ret[i] += (len(self.get_actors_given_movie(cur_movie)) - 1)
highest = max(ret.values())
hub = [str(k) + " with largest connection of " + str(v) + "\n" for k, v in ret.items() if v == highest]
return ''.join(hub)
"""
Function that return all actors' age and their total gross in all movie
"""
def get_correlation(self):
age = []
earning = []
for i in self.vert_dict.keys():
if not self.vert_dict[i].isMoive and self.vert_dict[i].age != None:
if isinstance(self.vert_dict[i].age, int):
if self.vert_dict[i].age == 0 or self.vert_dict[i].gross == 0:
continue
age.append(self.vert_dict[i].age)
earning.append(self.vert_dict[i].gross)
else:
m = re.search(r"\d", self.vert_dict[i].age)
actor_earning = sum(self.vert_dict[i].adjacent.values())
actor_age = int(self.vert_dict[i].age[m.start(): m.end()+1])
if actor_age == 0 or actor_earning == 0:
continue
age.append(actor_age)
earning.append(actor_earning)
res = {}
for i in range(len(age)):
cur_age = int(5 * round(float(age[i])/5))
if cur_age not in res:
res[cur_age] = [1, earning[i]]
else:
res[cur_age][0] += 1
res[cur_age][1] += earning[i]
for key, value in res.items():
res[key] = value[1]/value[0]
highest = max(res.values())
winner = ["Age around " + str(k) + " has the highest average earning of $" + str(int(v)) for k, v in res.items() if v == highest]
return age, earning, winner[0]
"""
Helper function to update parameters
"""
def update_name(self, name, target):
ret = self.vert_dict[name]
if ret != None:
self.vert_dict[str(target)] = self.vert_dict[name]
self.vert_dict[str(target)].name = str(target)
def update_age(self, name, target):
ret = self.vert_dict[name]
if ret != None and not ret.isMoive:
self.vert_dict[name].age = int(target)
def update_gross(self, name, target):
ret = self.vert_dict[name]
if ret != None:
self.vert_dict[name].gross = int(target)
def update_date(self, name, target):
ret = self.vert_dict[name]
if ret != None and ret.isMoive:
self.vert_dict[name].date = int(target)
def update_page(self, name, target):
ret = self.vert_dict[name]
if ret != None:
self.vert_dict[name].page = str(target)
"""
Helper function to delete actor object
"""
def delete_vertex(self, name):
cur_vertex = self.vert_dict[name]
if cur_vertex == None:
return False
for key, neighbor in cur_vertex.adjacent.items():
del self.vert_dict[key].adjacent[name]
del self.vert_dict[name]
return True<file_sep>/model/Scraper/__init__.py
from .spider import MySpider
from .item import Actor, Movie
__all__ = ["MySpider", "Actor", "Movie"]<file_sep>/graphy_test.py
import unittest
from unittest import TestCase
from model.graphy import myGraph
from model.Scraper import Actor, Movie
class TestGraphyMethods(unittest.TestCase):
print("Running Graph Structure Test Cases: ")
def initlize(self):
g = myGraph()
actor1 = Actor(actor_name="Herbert1", actor_age="(aged 21)", page="https://en.wikipedia.org/wiki/Herbert_Wang")
actor2 = Actor(actor_name="Herbert2", actor_age="(aged 25)", page="https://en.wikipedia.org/wiki/Herbert_Wang2")
movie1 = Movie(name="My first movie", gross=13124.0, date="2018-10-7", \
actors=["Herbert1", "Herbert2"], page="wiki_Herbert")
movie2 = Movie(name="My second movie", gross=424232.0, date="2018-1-27", \
actors=["Herbert2"], page="wiki_Herbert2")
g.add_vertex_to_graph(actor1['actor_name'], actor1['actor_age'], None, None, actor1['page'], False)
g.add_vertex_to_graph(actor2['actor_name'], actor2['actor_age'], None, None, actor2['page'], False)
g.add_vertex_to_graph(movie1['name'], None, movie1['gross'], movie1['date'], movie1['page'], True)
g.add_vertex_to_graph(movie2['name'], None, movie2['gross'], movie2['date'], movie2['page'], True)
g.add_edge(actor1['actor_name'], movie1['name'], movie1['gross'])
g.add_edge(actor2['actor_name'], movie1['name'], movie1['gross'])
g.add_edge(actor2['actor_name'], movie2['name'], movie2['gross'])
return g
def test_add_vertex_to_graph(self):
g = self.initlize()
self.assertEqual("Herbert1", g.get_vertex_info("Herbert1").name)
self.assertEqual("(aged 21)", g.get_vertex_info("Herbert1").age)
self.assertEqual("https://en.wikipedia.org/wiki/Herbert_Wang", g.get_vertex_info("Herbert1").page)
self.assertIsNone(g.get_vertex_info("Herbert1").date)
self.assertIsNone(g.get_vertex_info("Herbert1").gross)
self.assertEqual("My first movie", g.get_vertex_info("My first movie").name)
self.assertIsNone(g.get_vertex_info("My first movie").age)
self.assertEqual(13124.0, g.get_vertex_info("My first movie").gross)
self.assertEqual("2018-10-7", g.get_vertex_info("My first movie").date)
self.assertEqual("wiki_Herbert", g.get_vertex_info("My first movie").page)
def test_get_actors_given_movie(self):
g = self.initlize()
ret = g.get_actors_given_movie("My first movie")
self.assertTrue("Herbert1" in ret)
self.assertTrue("Herbert2" in ret)
self.assertEqual(len(ret), 2)
self.assertFalse("Herbert12312" in ret)
def test_get_movies_given_actor(self):
g = self.initlize()
ret = g.get_movies_given_actor("Herbert2")
self.assertTrue("My first movie" in ret)
self.assertTrue("My second movie" in ret)
self.assertEqual(len(ret), 2)
self.assertFalse("My third movie" in ret)
def test_get_all_movie_name(self):
g = self.initlize()
ret = g.get_all_movie_name()
self.assertEqual(len(ret), 2)
self.assertTrue("My first movie" in ret)
self.assertTrue("My second movie" in ret)
self.assertFalse("My third movie" in ret)
def test_get_all_actor_name(self):
g = self.initlize()
ret = g.get_all_actor_name()
self.assertEqual(len(ret), 2)
self.assertTrue("Herbert1" in ret)
self.assertTrue("Herbert2" in ret)
self.assertFalse("Herbert3" in ret)
def test_get_vertex_info(self):
g = self.initlize()
self.assertEqual("Herbert2", g.get_vertex_info("Herbert2").name)
self.assertEqual("(aged 25)", g.get_vertex_info("Herbert2").age)
self.assertEqual("https://en.wikipedia.org/wiki/Herbert_Wang2", g.get_vertex_info("Herbert2").page)
self.assertIsNone(g.get_vertex_info("Herbert2").date)
self.assertIsNone(g.get_vertex_info("Herbert2").gross)
self.assertEqual("My second movie", g.get_vertex_info("My second movie").name)
self.assertIsNone(g.get_vertex_info("My second movie").age)
self.assertEqual(424232.0, g.get_vertex_info("My second movie").gross)
self.assertEqual("2018-1-27", g.get_vertex_info("My second movie").date)
self.assertEqual("wiki_Herbert2", g.get_vertex_info("My second movie").page)
def test_get_vertices(self):
g = self.initlize()
ret = g.get_vertices()
self.assertEqual(len(ret), 4)
self.assertTrue("Herbert1" in ret)
self.assertTrue("Herbert2" in ret)
self.assertTrue("My first movie" in ret)
self.assertTrue("My second movie" in ret)
def test_get_all_movie_given_year(self):
g = self.initlize()
ret = g.get_all_movie_given_year("2018")
self.assertEqual(len(ret), 2)
self.assertTrue("My first movie" in ret)
self.assertTrue("My second movie" in ret)
def test_get_all_actor_given_year(self):
g = self.initlize()
ret = g.get_all_actor_given_year("2018")
self.assertEqual(len(ret), 2)
self.assertTrue("Herbert1" in ret)
self.assertTrue("Herbert2" in ret)
def test_get_movie_gross(self):
g = self.initlize()
ret = g.get_movie_gross("My first movie")
self.assertEqual("My first movie's Gross: $13124.0", ret)
ret = g.get_movie_gross("My second movie")
self.assertEqual("My second movie's Gross: $424232.0", ret)
def test_get_top_oldest(self):
g = self.initlize()
ret = g.get_top_oldest(1)
self.assertEqual(len(ret), 1)
self.assertEqual("Herbert2", ret[0][0])
self.assertEqual(25, ret[0][1])
ret = g.get_top_oldest(2)
self.assertEqual(len(ret), 2)
self.assertEqual("Herbert2", ret[0][0])
self.assertEqual(25, ret[0][1])
self.assertEqual("Herbert1", ret[1][0])
self.assertEqual(21, ret[1][1])
def test_get_topK(self):
g = self.initlize()
ret = g.get_topK(1)
self.assertEqual(len(ret), 1)
self.assertEqual("Herbert2", ret[0][0])
self.assertEqual("$437356.0", ret[0][1])
ret = g.get_topK(2)
self.assertEqual(len(ret), 2)
self.assertEqual("Herbert2", ret[0][0])
self.assertEqual("$437356.0", ret[0][1])
self.assertEqual("Herbert1", ret[1][0])
self.assertEqual("$13124.0", ret[1][1])
def test_get_movie_info(self):
g = self.initlize()
ret = g.get_movie_info("My first movie")
self.assertEqual(ret, "Movie Name: My first movie\nGross: $13124.0\nRelease Date: 2018-10-7\nWiki Page: wiki_Herbert")
ret = g.get_movie_info("My second movie")
self.assertEqual(ret, "Movie Name: My second movie\nGross: $424232.0\nRelease Date: 2018-1-27\nWiki Page: wiki_Herbert2")
ret = g.get_movie_info("Wrong movie")
self.assertNotEqual(ret, "Movie Name: My second movie\nGross: $424232.0\nRelease Date: 2018-1-27\nWiki Page: wiki_Herbert2")
self.assertEqual(ret, "No such movie found!")
def test_get_actor_info(self):
g = self.initlize()
ret = g.get_actor_info("Herbert1")
self.assertEqual(ret, "Actor Name: Herbert1\nAge: (aged 21)\nWiki Page: https://en.wikipedia.org/wiki/Herbert_Wang")
ret = g.get_actor_info("Herbert2")
self.assertEqual(ret, "Actor Name: Herbert2\nAge: (aged 25)\nWiki Page: https://en.wikipedia.org/wiki/Herbert_Wang2")
ret = g.get_actor_info("Wrong actor")
self.assertNotEqual(ret, "Actor Name: Herbert2\nAge: (aged 25)\nWiki Page: https://en.wikipedia.org/wiki/Herbert_Wang2")
self.assertEqual(ret, "No such actor found!")
def test_get_hub_actors(self):
g = self.initlize()
actor3 = Actor(actor_name="Herbert3", actor_age="(aged 40)", page="https://en.wikipedia.org/wiki/Herbert_Wang3")
movie3 = Movie(name="My third movie", gross=93334.0, date="2018-09-14", \
actors=["Herbert3"], page="wiki_Herbert")
g.add_vertex_to_graph(actor3['actor_name'], actor3['actor_age'], None, None, actor3['page'], False)
g.add_vertex_to_graph(movie3['name'], None, movie3['gross'], movie3['date'], movie3['page'], True)
g.add_edge(actor3['actor_name'], movie3['name'], movie3['gross'])
g.add_edge("Herbert2", movie3['name'], movie3['gross'])
self.assertEqual("Herbert2 with largest connection of 2\n", g.get_hub_actors())
def test_delete_vertex(self):
g = self.initlize()
actor3 = Actor(actor_name="Herbert3", actor_age="(aged 40)", page="https://en.wikipedia.org/wiki/Herbert_Wang3")
movie3 = Movie(name="My third movie", gross=93334.0, date="2018-09-14", \
actors=["Herbert3"], page="wiki_Herbert")
g.add_vertex_to_graph(actor3['actor_name'], actor3['actor_age'], None, None, actor3['page'], False)
g.add_vertex_to_graph(movie3['name'], None, movie3['gross'], movie3['date'], movie3['page'], True)
g.add_edge(actor3['actor_name'], movie3['name'], movie3['gross'])
g.add_edge("Herbert2", movie3['name'], movie3['gross'])
g.delete_vertex("Herbert2")
self.assertTrue("Herbert2" not in g.get_actors_given_movie("My third movie"))
self.assertTrue("Herbert2" not in g.get_actors_given_movie("My second movie"))
self.assertTrue("Herbert2" not in g.get_actors_given_movie("My first movie"))
g.add_edge("Herbert1", movie3['name'], movie3['gross'])
g.delete_vertex("My third movie")
self.assertTrue("My third movie" not in g.get_movies_given_actor("Herbert1"))
if __name__ == '__main__':
unittest.main()<file_sep>/config.py
CLOSESPIDER_ITEMCOUNT = 30
wiki_start = "https://en.wikipedia.org/wiki/Morgan_Freeman"
PORT = 5001
# wiki_start = "https://en.wikipedia.org/wiki/Johnny_Depp"
# wiki_start = "https://en.wikipedia.org/wiki/Jennifer_Lawrence"<file_sep>/model/Scraper/item.py
import scrapy
from scrapy import Item
class Actor(scrapy.Item):
actor_name = scrapy.Field()
actor_age = scrapy.Field()
page = scrapy.Field()
class Movie(scrapy.Item):
name = scrapy.Field()
gross = scrapy.Field()
date = scrapy.Field()
actors = scrapy.Field()
page = scrapy.Field()<file_sep>/app.py
from flask import Flask, jsonify
from flask import abort
from flask import request
from model.Scraper import MySpider
from model.graphy import myGraph
from model.Scraper import Actor, Movie
import json_lines
import termios
import contextlib
import time
import re
import numpy as np
import matplotlib.pyplot as plt
import json
import config
global g
app = Flask(__name__)
def read_input(json_file):
g = myGraph()
global actor_name
global movie_name
actor_name = set()
movie_name = set()
movie_list = []
json_str = json_file.read()
actor_data = json.loads(json_str)[0]
movie_data = json.loads(json_str)[1]
num_actor = 0
num_movie = 0
vertices = []
edges = []
item = {}
# vertices = ["one", "two", "three"]
# edges = [(0,2),(2,1),(0,1)]
for key, value in actor_data.items():
if value['json_class'] == "Actor":
actor_name.add(key)
num_actor += 1
g.add_vertex_to_graph(value['name'], value['age'], value['total_gross'], None, "", False)
item[value['name']] = len(vertices)
vertices.append(value['name'])
else:
continue
for key, value in movie_data.items():
if value['json_class'] == "Movie":
movie_name.add(key)
num_movie += 1
g.add_vertex_to_graph(value['name'], None, value['box_office'], value['year'], value['wiki_page'], True)
item[value['name']] = len(vertices)
vertices.append(value['name'])
for actor in value['actors']:
if actor not in actor_name:
continue
g.add_edge(actor, value['name'], value['box_office'])
edges.append((item[actor], item[value['name']]))
else:
continue
global total_actor
global total_movie
total_actor = num_actor
total_movie = num_movie
return g
"""
/actors?attr={attr_value} Example: /actors?name=”Bob”
Filters out all actors that don’t have “Bob” in their name
(Should allow for similar filtering for any other attribute)
You should also be able to filter using boolean operators AND and OR,
i.e. name=”Bob”|name=”Matt”, name=”Bob”&age=35
"""
@app.route('/actors', methods=['GET'])
def filter_actor():
# request.args.to_dict()
# request.args.getlist('attr')
target = request.args.to_dict()
actor_set = set()
if len(target) == 0:
abort(404)
if 'name' in target:
for name in set(str(target['name']).replace("|name=", ",").split(",")):
for actor in actor_name:
if name in actor:
actor_set.add(actor)
if 'age' in target:
age_set = set(str(target['age']).replace("|age=", ",").split(","))
if len(actor_set) == 0:
for actor in actor_name:
cur = g.get_vertex_info(actor)
if str(cur.age) in age_set:
actor_set.add(actor)
else:
for already in actor_set.copy():
cur = g.get_vertex_info(already)
if str(cur.age) not in age_set:
actor_set.remove(already)
return jsonify({"Actors": list(actor_set)})
"""
/movies?attr={attr_value} Example: /movies?name=”Shawshank&Redemption”
Filters out all actors that don’t have “Shawshank&Redemption” in
their name (Should allow for similar filtering for any other attribute)
"""
@app.route('/movies', methods=['GET'])
def filter_movies():
target = request.args.to_dict()
movie_set = set()
if len(target) == 0:
abort(404)
if 'name' in target:
for name in set(str(target['name']).replace("|name=", ",").split(",")):
for movie in movie_name:
if name in movie:
movie_set.add(movie)
if 'year' in target:
year_set = set(str(target['year']).replace("|year=", ",").split(","))
if len(movie_set) == 0:
for movie in movie_name:
cur = g.get_vertex_info(movie)
if str(cur.date) in year_set:
movie_set.add(movie)
else:
for already in movie_set.copy():
cur = g.get_vertex_info(already)
if str(cur.date) not in year_set:
movie_set.remove(already)
if 'gross' in target:
gross_set = set(str(target['gross']).replace("|gross=", ",").split(","))
if len(movie_set) == 0:
for movie in movie_name:
cur = g.get_vertex_info(movie)
if str(cur.gross) in gross_set:
movie_set.add(movie)
else:
for already in movie_set.copy():
cur = g.get_vertex_info(already)
if str(cur.gross) not in gross_set:
movie_set.remove(already)
return jsonify({"Movies": list(movie_set)})
"""
/actors/:{actor_name} Example: /actors/Bruce_Willis
Returns the first Actor object that has name “<NAME>”,
displays actor attributes and metadata
"""
@app.route('/actors/<string:given_name>', methods=['GET'])
def get_actor(given_name):
given_name = given_name.replace("_", " ")
for i in actor_name:
if i.lower() == given_name.lower():
given_name = i
continue
if given_name not in actor_name:
abort(404)
cur = g.get_vertex_info(given_name)
if cur == None:
abort(404)
ret = {}
ret['Actor Name'] = cur.name
ret['Actor Age'] = cur.age
ret['Actor Total Gross'] = cur.gross
ret['Actor Wiki Page'] = cur.page
ret['Actor Movies'] = g.get_movies_given_actor(cur.name)
return jsonify({cur.name: ret})
"""
/movies/:{movie_name} Example: /movies/Shawshank_Redemption
Returns the first Movie object that has correct name, displays movie attributes and metadata
"""
@app.route('/movies/<string:given_name>', methods=['GET'])
def get_movie(given_name):
given_name = given_name.replace("_", " ")
for i in movie_name:
if i.lower() == given_name.lower():
given_name = i
continue
if given_name not in movie_name:
abort(404)
cur = g.get_vertex_info(given_name)
if cur == None:
abort(404)
ret = {}
ret['Movie Name'] = cur.name
ret['Movie Box Office'] = cur.gross
ret['Movie Year'] = cur.date
ret['Movie Wiki Page'] = cur.page
ret['Movie Actors'] = g.get_actors_given_movie(cur.name)
return jsonify({cur.name: ret})
"""
Put: /actors
Leverage PUT requests to update standing content in backend
curl -i -X PUT -H "Content-Type: application/json" -d '
{"total_gross":500}'http://localhost:4567/api/a/actors/Bruce_Willis
"""
@app.route('/actors/<string:given_name>', methods=['PUT'])
def update_actors(given_name):
if not request.json:
abort(400)
given_name = given_name.replace("_", " ")
for i in actor_name:
if i.lower() == given_name.lower():
given_name = i
continue
if given_name not in actor_name:
abort(404)
cur = g.get_vertex_info(given_name)
if cur == None:
abort(404)
if 'age' in request.json:
g.update_age(given_name, request.json.get('age', cur.age))
if 'total_gross' in request.json:
g.update_gross(given_name, request.json.get('total_gross', cur.gross))
if 'wiki_page' in request.json:
g.update_page(given_name, request.json.get('wiki_page', cur.page))
if 'name' in request.json:
g.update_name(given_name, request.json.get('name', cur.name))
actor_name.remove(given_name)
actor_name.add(request.json.get('name', cur.name))
new_cur = g.get_vertex_info(request.json.get('name', cur.name))
if new_cur == None:
abort(404)
ret = {}
ret['Actor Name'] = new_cur.name
ret['Actor Age'] = new_cur.age
ret['Actor Total Gross'] = new_cur.gross
ret['Actor Wiki Page'] = new_cur.page
ret['Actor Movies'] = g.get_movies_given_actor(new_cur.name)
resp = jsonify({new_cur.name: ret, 'success':True})
resp.status_code = 200
return resp
# return jsonify({new_cur.name: ret})
"""
/movies
Leverage PUT requests to update standing content in backend
curl -i -X PUT -H "Content-Type: application/json" -d ' {"box_office":500}'
http://localhost:4567/api/m/movies/Shawshank_Redemption
"""
@app.route('/movies/<string:given_name>', methods=['PUT'])
def update_movies(given_name):
if not request.json:
abort(400)
given_name = given_name.replace("_", " ")
for i in movie_name:
if i.lower() == given_name:
given_name = i
continue
if given_name not in movie_name:
abort(404)
cur = g.get_vertex_info(given_name)
if cur == None:
abort(404)
if 'date' in request.json:
g.update_date(given_name, request.json.get('date', cur.date))
if 'box_office' in request.json:
g.update_gross(given_name, request.json.get('box_office', cur.gross))
if 'wiki_page' in request.json:
g.update_page(given_name, request.json.get('wiki_page', cur.page))
if 'name' in request.json:
g.update_name(given_name, request.json.get('name', cur.name))
movie_name.remove(given_name)
movie_name.add(request.json.get('name', cur.name))
new_cur = g.get_vertex_info(request.json.get('name', cur.name))
if new_cur == None:
abort(404)
ret = {}
ret['Movie Name'] = new_cur.name
ret['Movie Box Office'] = new_cur.gross
ret['Movie Year'] = new_cur.date
ret['Movie Wiki Page'] = new_cur.page
ret['Movie Actors'] = g.get_actors_given_movie(new_cur.name)
resp = jsonify({new_cur.name: ret, 'success':True})
resp.status_code = 200
return resp
"""
Delete:
/actors/:{actor_name}
Leverage DELETE requests to REMOVE content from backend
curl -i -X DELETE -H "Content-Type: application/json"
{API URL}/actors/Bruce_Willis
"""
@app.route('/actors/<string:given_name>', methods=['DELETE'])
def delete_actor(given_name):
given_name = given_name.replace("_", " ")
for i in actor_name:
if i.lower() == given_name.lower():
given_name = i
continue
if given_name not in actor_name:
abort(404)
cur = g.get_vertex_info(given_name)
if cur == None:
abort(404)
actor_name.remove(given_name)
if g.delete_vertex(given_name):
resp = jsonify(success=True)
resp.status_code = 200
return resp
else:
abort(404)
"""
/movies/:{movie_name}
Leverage DELETE requests to REMOVE content from backend
curl -i -X DELETE -H "Content-Type: application/json"
{API URL}/movies/Shawshank_Redemption
"""
@app.route('/movies/<string:given_name>', methods=['DELETE'])
def delete_movie(given_name):
given_name = given_name.replace("_", " ")
for i in movie_name:
if i.lower() == given_name.lower():
given_name = i
continue
if given_name not in movie_name:
abort(404)
cur = g.get_vertex_info(given_name)
if cur == None:
abort(404)
movie_name.remove(given_name)
if g.delete_vertex(given_name):
resp = jsonify(success=True)
resp.status_code = 200
return resp
else:
abort(404)
"""
Post:
/actors
Leverage POST requests to ADD content to backend
curl -i -X POST -H "Content-Type: application/json"
-d'{"name":"<NAME>"}' {API URL}/actors
"""
@app.route('/actors', methods=['POST'])
def add_actors():
if not request.json or 'name' not in request.json:
abort(400)
if 'age' in request.json and type(request.json['age']) != int:
abort(400)
if 'total_gross' in request.json and type(request.json['total_gross']) != int:
abort(400)
if str(request.json.get('name')) in actor_name:
abort(400)
new_name = ""
new_age = 0
new_total_gross = 0
new_page = ""
new_movie = []
if 'name' in request.json:
new_name = str(request.json.get('name'))
actor_name.add(new_name)
if 'age' in request.json:
new_age = int(request.json.get('age'))
if 'total_gross' in request.json:
new_total_gross = int(request.json.get('total_gross'))
if 'wiki_page' in request.json:
new_page = str(request.json.get('wiki_page'))
g.add_vertex_to_graph(new_name, new_age, new_total_gross, None, new_page, False)
if 'movies' in request.json:
for m in request.json.get('movies'):
if m not in movie_name:
continue
cur_movie = g.get_vertex_info(m)
if cur_movie == None:
continue
g.add_edge(new_name, cur_movie.name, cur_movie.gross)
return json.dumps({'success':True}), 201, {'ContentType':'application/json'}
"""
/movies
Leverage POST requests to ADD content to backend
curl -i -X POST -H "Content-Type: application/json"
-d'{"name":"Captain America"}' {API URL}/movies
"""
@app.route('/movies', methods=['POST'])
def add_movies():
if not request.json or 'name' not in request.json:
abort(400)
if 'date' in request.json and type(request.json['date']) != int:
abort(400)
if 'box_office' in request.json and type(request.json['box_office']) != int:
abort(400)
if str(request.json.get('name')) in movie_name:
abort(400)
new_name = ""
new_date = 0
new_box_office = 0
new_page = ""
new_actor = []
if 'name' in request.json:
new_name = str(request.json.get('name'))
movie_name.add(new_name)
if 'date' in request.json:
new_date = int(request.json.get('date'))
if 'box_office' in request.json:
new_box_office = int(request.json.get('box_office'))
if 'wiki_page' in request.json:
new_page = str(request.json.get('wiki_page'))
g.add_vertex_to_graph(new_name, None, new_box_office, new_date, new_page, True)
if 'actors' in request.json:
for a in request.json.get('actors'):
if a not in actor_name:
continue
cur_actor = g.get_vertex_info(a)
if cur_actor == None:
continue
g.add_edge(cur_actor.name, new_name, new_box_office)
return json.dumps({'success':True}), 201, {'ContentType':'application/json'}
@app.route('/init', methods=['GET'])
def app_init():
global g
json_file = open('data.json')
g = read_input(json_file)
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
if __name__ == '__main__':
json_file = open('data.json')
g = read_input(json_file)
app.debug = True
app.run(host='127.0.0.1', port=config.PORT)<file_sep>/model/Scraper/pipeline.py
from scrapy.exceptions import DropItem
import json
from .item import Actor, Movie
import logging
"""
Source:
https://doc.scrapy.org/en/latest/topics/item-pipeline.html
"""
class JsonWriterPipeline(object):
"""
OPen spider once it is done
"""
def open_spider(self, spider):
self.file = open('items.jl', 'w')
self.movie_count = 0
self.actor_count = 0
"""
Close spider once it is done
"""
def close_spider(self, spider):
self.file.close()
"""
Pipeline for scrappy to process each item
"""
def process_item(self, item, spider):
try:
if isinstance(item, Movie):
if not item.get("actors"):
logging.warning("Currecntly processing movie: {}, missing casts list!".format(item["name"]))
raise ValueError("Missing casts list!")
if item.get("gross") is None:
logging.warning("Currecntly processing movie: {}, missing movie gross!".format(item["name"]))
raise ValueError("Missing movie gross!")
if isinstance(item, Actor):
self.actor_count += 1
else:
self.movie_count += 1
logging.info(
"Currecntly Processing {} @ {}. "
"Current Progress - movies: {}, actors: {}".format(
item.__class__.__name__, item["page"], self.movie_count, self.actor_count))
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
except (KeyError, ValueError):
logging.error("Current item {} has incomplete information, cannot be processed!".format(item["name"]))
raise DropItem("Incomplete info in %s" % item)<file_sep>/README.md
# Wiki Crawler with API
# To install
###### It is recommanded to create a virtual environment first:
* To create virenv:
```bash
virtualenv venv
source venv/bin/activate
```
* Then install requirement:
```bash
pip3 install -r requirements.txt
```
# To Run:
###### There are 3 options:
1. Run scraper to generate JSON
```python
python3 main.py scrap
```
2. Use cached JSON to generate graph and query graph
```python
python3 main.py cache
```
3. Use provided JSON to generate graph and query graph
```python
python3 main.py input
```
###### Graph Query:
* Based on the prompt message, enter valid input

* For example:
1. Find how much a "The Boy Next Door (film)" has grossed:
```bash
=> 1 The Boy Next Door (film)
```
2. List which movies an "Morgan Freeman" has worked in:
```bash
=> 2 <NAME>
```
3. List which actors worked in movie "Dreamcatcher (2003 film)":
```bash
=> 3 Dreamcatcher (2003 film)
```
4. List the top 50 actors with the most total grossing value
```bash
=> 4 50
```
5. List the oldest 20 actors
```bash
=> 5 20
```
6. List all the movies in year 2018:
```bash
=> 6 2018
```
7. List all the actors in year 2016:
```bash
=> 7 2016
```
8. Show list of movies:
```bash
=> 8
```
9. Show list of actors:
```bash
=> 9
```
9. Total number of movies:
```bash
=> 10
```
9. Total Number of actors:
```bash
=> 11
```
9. Show given movie info:
```bash
=> 12 The Verdict
```
9. Show given actor info:
```bash
=> 13 <NAME>
```
9. Identify 'hub' actors:
```bash
=> 14
```
9. Calculate age and grossing value correlation and generate plot -> correlation.png:
```bash
=> 15
```
* The correlation graph looks like the following:

* You can also visualize the graph structrue by rendering the graph_cache.svg on a browser, the graph looks like the following:

# To Confige:
* Modify parameters in config.py
```bash
CLOSESPIDER_ITEMCOUNT = 30
wiki_start = "https://en.wikipedia.org/wiki/Morgan_Freeman"
PORT = 5001
```
# To test:
### Test Graph Structure
```python
python3 graphy_test.py
```
* There are total of 16 test cases to run, correct output looks like the following:

# To Run API:
```python
python3 app.py
```
### Test API
```python
python3 test_app.py
```
* To run the API test_app.py, first start running the serve:
```python
python3 app.py
```
* There are total of 10 test cases to run, correct output looks like the following:

<file_sep>/main.py
import scrapy
from scrapy import log
from scrapy.crawler import CrawlerProcess
from model.Scraper import MySpider
from model.graphy import myGraph
from model.Scraper import Actor, Movie
import json_lines
import logging
import sys
import termios
import contextlib
import time
import re
import numpy as np
import matplotlib.pyplot as plt
import json
import igraph
from igraph import *
"""
Source:
https://stackoverflow.com/questions/13437402/how-to-run-scrapy-from-within-a-python-script
https://stackoverflow.com/questions/11918999/key-listeners-in-python
https://github.com/vBlackOut/vHackOS-Python/blob/master/utils.py
"""
divider = "============================================================================"
prompt = "\n Press a number to query graph: \n \
1. Find how much a movie has grossed \n \
2. List which movies an actor has worked in \n \
3. List which actors worked in a movie \n \
4. List the top X actors with the most total grossing value \n \
5. List the oldest X actors \n \
6. List all the movies for a given year \n \
7. List all the actors for a given year \n \
8. Show list of movies \n \
9. Show list of actors \n \
10. Total number of movies \n \
11. Total Number of actors \n \
12. Show given movie info \n \
13. Show given actor info \n \
14. Identify 'hub' actors \n \
15. Calculate age and grossing value correlation and generate plot -> correlation.png \n \
=> "
total_movie = 0
total_actor = 0
my_graph = None
"""
* Important helper function that responds to user's keyboard input
and conduct graph query, base on different keyboard input, it answer
the query differently
"""
def answer(mystr, g):
inputList = mystr.strip().split()
if(len(inputList) > 1 and inputList[0] == '1'):
movie_name = " ".join(inputList[1:])
ret = g.get_movie_gross(movie_name)
if ret == None:
myprint("Can not find gross for " + movie_name + "!")
return
myprint(ret)
if(len(inputList) > 1 and inputList[0] == '2'):
actor_name = " ".join(inputList[1:])
ret = g.get_movies_given_actor(actor_name)
if len(ret) == 0:
myprint("This actor has no corresponding movie!")
return
myprint(ret)
if(len(inputList) > 1 and inputList[0] == '3'):
movie_name = " ".join(inputList[1:])
ret = g.get_actors_given_movie(movie_name)
if len(ret) == 0:
myprint("This movie has no corresponding actor!")
return
myprint(ret)
if(len(inputList) == 2 and inputList[0] == '4'):
try:
topK = int(inputList[1])
k = 1
ret = g.get_topK(topK)
if ret == None or len(ret) == 0:
myprint("Second argument must be a valid integer!")
return
print(divider)
for i in ret:
if(k % 4 == 0):
print()
print(i, end=" ")
k += 1
print()
print(divider)
except (TypeError, ValueError):
myprint("Second argument must be a valid integer!")
if(len(inputList) == 2 and inputList[0] == '5'):
try:
oldest = int(inputList[1])
k = 1
ret = g.get_top_oldest(oldest)
if ret == None or len(ret) == 0:
myprint("Second argument must be a valid integer!")
return
print(divider)
for i in ret:
if(k % 4 == 0):
print()
print(i, end=" ")
k += 1
print()
print(divider)
except (TypeError, ValueError):
myprint("Second argument must be a valid integer!")
if(len(inputList) == 2 and inputList[0] == '6'):
ret = g.get_all_movie_given_year(inputList[1])
if len(ret) == 0:
myprint("No movies in year " + inputList[1])
return
myprint(ret)
if(len(inputList) == 2 and inputList[0] == '7'):
ret = g.get_all_actor_given_year(inputList[1])
if len(ret) == 0:
myprint("No actors in year " + inputList[1])
return
myprint(ret)
if(len(inputList) == 1 and inputList[0] == '8'):
myprint(g.get_all_movie_name())
if(len(inputList) == 1 and inputList[0] == '9'):
myprint(g.get_all_actor_name())
if(len(inputList) == 1 and inputList[0] == '10'):
myprint("Total Number of movies: " + str(total_movie))
if(len(inputList) == 1 and inputList[0] == '11'):
myprint("Total Number of actors: " + str(total_actor))
if(len(inputList) > 1 and inputList[0] == '12'):
movie_name = " ".join(inputList[1:])
myprint(g.get_movie_info(movie_name))
if(len(inputList) > 1 and inputList[0] == '13'):
actor_name = " ".join(inputList[1:])
myprint(g.get_actor_info(actor_name))
if(len(inputList) == 1 and inputList[0] == '14'):
myprint(g.get_hub_actors())
if(len(inputList) == 1 and inputList[0] == '15'):
age, earning, summary = g.get_correlation()
myprint(summary + "\nCorrelation matrix: \n" + str(np.corrcoef(age, earning)))
plt.plot(age, earning, 'ro')
plt.axis([0, max(age), min(earning), max(earning)])
plt.savefig('correlation.png')
def read_input(json_file):
g = myGraph()
actor_list = []
actor_name = set()
movie_list = []
json_str = json_file.read()
actor_data = json.loads(json_str)[0]
movie_data = json.loads(json_str)[1]
num_actor = 0
num_movie = 0
vertices = []
edges = []
item = {}
# vertices = ["one", "two", "three"]
# edges = [(0,2),(2,1),(0,1)]
for key, value in actor_data.items():
if value['json_class'] == "Actor":
actor_name.add(key)
num_actor += 1
g.add_vertex_to_graph(value['name'], value['age'], value['total_gross'], None, "", False)
item[value['name']] = len(vertices)
vertices.append(value['name'])
else:
continue
for key, value in movie_data.items():
if value['json_class'] == "Movie":
num_movie += 1
g.add_vertex_to_graph(value['name'], None, value['box_office'], value['year'], value['wiki_page'], True)
item[value['name']] = len(vertices)
vertices.append(value['name'])
for actor in value['actors']:
if actor not in actor_name:
continue
g.add_edge(actor, value['name'], value['box_office'])
edges.append((item[actor], item[value['name']]))
else:
continue
global total_actor
global total_movie
total_actor = num_actor
total_movie = num_movie
graph = Graph(vertex_attrs={"label": vertices}, edges=edges, directed=False)
Graph.write_svg(graph, "graph_input.svg")
return g
"""
Function to construct the graph structure, get ready for graph query
"""
def constructor_graph(f):
g = myGraph()
actor_list = []
actor_name = set()
movie_list = []
vertices = []
edges = []
items = {}
total_edge = 0
for item in json_lines.reader(f):
# def add_vertex_to_graph(self, name, age, gross, date, page):
if ('actor_name' in item):
# print(item['actor_name'], item['actor_age'])
actor_list.append(item)
actor_name.add(item['actor_name'])
g.add_vertex_to_graph(item['actor_name'], item['actor_age'], None, None, item['page'], False)
actor_detail = "Actor: " + item['actor_name'] + "\nAge: " + str(item['actor_age'])
items[item['actor_name']] = len(vertices)
vertices.append(actor_detail)
else:
movie_list.append(item)
g.add_vertex_to_graph(item['name'], None, item['gross'], item['date'], item['page'], True)
movie_detail = "Movie: " + item['name'] + "\n Total Gross: " + str(item['gross'])
items[item['name']] = len(vertices)
vertices.append(movie_detail)
for m in movie_list:
gross = m['gross']
movie_name = m['name']
i = 1
for actor in m['actors']:
cur_name = actor[actor.rfind("/")+1: ].replace("_", " ")
if cur_name not in actor_name:
continue
egde_weight = gross * (1 + i*0.0001)
i += 1
g.add_edge(cur_name, movie_name, egde_weight)
total_edge += 1
edges.append((items[cur_name], items[movie_name]))
global total_actor
global total_movie
total_actor = len(actor_list)
total_movie = len(movie_list)
print(total_edge)
graph = Graph(vertex_attrs={"label": vertices}, edges=edges, directed=False)
Graph.write_svg(graph, fname="graph_cache.svg", labels='label', colors="blue", vertex_size=3, edge_colors=["yellow"]*1000, font_size="4")
return g
"""
Listen for user's keyboard input and call answer function for grapy query
"""
def listen(g):
myprint("(Press ^C or ^Z to Exit)")
while True:
variable = input(prompt)
answer(variable, g)
"""
Helper function to print string
"""
def myprint(mystring):
print(divider)
print(mystring)
print(divider)
"""
Main function, control logic
"""
def main():
if len(sys.argv) == 2 and sys.argv[1] == "cache":
try:
f = open('items.jl', 'rb')
g = constructor_graph(f)
listen(g)
exit()
except FileNotFoundError:
myprint("No Cached JSON File")
exit()
elif len(sys.argv) == 2 and sys.argv[1] == "scrap":
myprint("Start Scraping...")
process = CrawlerProcess()
process.crawl(MySpider)
process.start()
myprint("Scraping Finished")
try:
f = open('items.jl', 'rb')
g = constructor_graph(f)
listen(g)
exit()
except FileNotFoundError:
myprint("Scrapped JSON cannot be opened, please try again...")
exit()
elif len(sys.argv) == 2 and sys.argv[1] == "input":
try:
json_file = open('data.json')
g = read_input(json_file)
listen(g)
exit()
except FileNotFoundError:
myprint("No Input JSON File")
exit()
else:
myprint("Invalid Argument, exit...")
exit()
if __name__ == "__main__":
main()
<file_sep>/requirements.txt
aniso8601==2.0.1
asn1crypto==0.24.0
attrs==17.4.0
Automat==0.6.0
beautifulsoup4==4.6.0
cffi==1.11.4
click==6.7
constantly==15.1.0
cssselect==1.0.3
coverage==4.5.1
dateparser==0.7.0
fake-useragent==0.1.10
hyperlink==17.3.1
incremental==17.5.0
itsdangerous==0.24
Jinja2==2.10
lxml==4.1.1
MarkupSafe==1.0
matplotlib==2.1.2
numpy==1.14.1
parsel==1.4.0
pyasn1==0.4.2
pyasn1-modules==0.2.1
pycparser==2.18
PyDispatcher==2.0.5
pyOpenSSL==17.5.0
pyparsing==2.2.0
python-dateutil==2.6.1
pytz==2018.3
queuelib==1.4.2
regex==2018.2.21
Scrapy==1.5.0
scrapy-fake-useragent==1.1.0
service-identity==17.0.0
six==1.11.0
Twisted==17.9.0
json-lines
matplotlib
python-igraph
cairocffi
neovim-gui
flask
pytest
Flask-Testing | fe26eea00738885383da2b42ebcbc92cad176b3f | [
"Markdown",
"Python",
"Text"
] | 12 | Python | herbherbherb/Wiki_Crawler | 8705bac66b2cd19ffb713db29c021890c89ed57c | 607dc64e085a8ebb042ba62f42f9a99e568dd09b |
refs/heads/master | <repo_name>yishaiy/EasyOpen<file_sep>/README.md
# EasyOpen
Chrome plugin to easly open google search result.
# Description
When searching in google search with chrome browser, the EasyOpen plugin will put numbers alongside the search result links.
* Clicking <n> will open the result link in a new tab and leave the focus on the current tab.
* Clicking Shift+<n> will open the result link in the current tab.
# Installation
Add with chrome web store: [easyOpen](https://chrome.google.com/webstore/detail/easyopen/pdakhecjfcpdohleegblgbcmpcedbeeb)
<file_sep>/easyOpen.js
var action_links = {};
function init_action_links(links)
{
var nums = "1234567890";
var shift_nums = "!@#$%^&*()";
links = links.slice(0, 10);
var n, sn, link, action;
for (var i = 0; i < links.length; i++)
{
link = links[i];
n = nums[i];
sn = shift_nums[i];
// Show shortcut key
link.innerHTML = n + '. ' + link.innerHTML;
// Add extension action
action_links[n] = {url: link.href, action: "create"};
action_links[sn] = {url: link.href, action: "update"};
}
}
function rimon_search_results()
{
var links = document.getElementsByTagName('a');
links = Array.prototype.slice.call(links);
links = links.filter(function (link) {
var class_name = link.className.toLowerCase();
return ((class_name.search('result') != -1) && (class_name.search('title') != -1));
});
return links;
}
function normal_search_results()
{
var h3s = Array.prototype.slice.call(document.getElementsByTagName('h3'));
var links = h3s.map(h3 => h3.getElementsByTagName('a')[0]);
return links;
}
function search_results()
{
var links = rimon_search_results();
if (links.length == 0) {
links = normal_search_results();
}
return links;
}
function send_open_message(actionLink) {
chrome.runtime.sendMessage(actionLink);
}
(function () {
init_action_links(search_results());
document.addEventListener("keypress", function (keypressed) {
if (document.activeElement.tagName.toLowerCase() !== "input")
{
var ch = keypressed.key;
var result = action_links[ch];
if (result != undefined) {
send_open_message(result);
}
}
});
})();
<file_sep>/eventPage.js
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
if (message.action == "create") {
chrome.tabs.create({url: message.url, selected: false});
} else if (message.action == "update") {
chrome.tabs.update({url: message.url});
}
}
); | 7d53c45ade7486fd31bc1504c638eb3cd258bacf | [
"Markdown",
"JavaScript"
] | 3 | Markdown | yishaiy/EasyOpen | d4cd759c932c4519ab83856c12b2dc8c759b2f2d | 0f694b1b45b6c7b52fa4509dc75d8111d86d5977 |
refs/heads/master | <file_sep>/*
* <NAME>
* CSIS 2420
* Assignment 2
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item>
{
Item[] randeque;
private int N;
public RandomizedQueue()// construct an empty randomized queue
{
randeque = (Item[]) new Object[2];
}
public boolean isEmpty() // is the queue empty?
{
return randeque == null;
}
public int size()// return the number of items on the queue
{
return N;
}
public void enqueue(Item item)// add the item
{
if (item == null) throw new java.lang.NullPointerException("Don't add null items.");
N++;
resize(size());
randeque[N-1] = item;
}
public Item dequeue()// delete and return a random item
{
if(isEmpty()) throw new java.util.NoSuchElementException();
int random = StdRandom.uniform(N);
Item item = randeque[random];
if(random != N-1) randeque[random] = randeque[N-1];
randeque[N-1] = null;
N--;
resize(randeque.length);
return item;
}
public Item sample()// return (but do not delete) a random item
{
if(isEmpty()) throw new java.util.NoSuchElementException();
return randeque[StdRandom.uniform(N)];
}
public Iterator<Item> iterator()// return an independent iterator over items in random order
{
return new ListIterator();
}
private class ListIterator implements Iterator<Item>
{
private int index;
private Item[] items = (Item[]) new Object[N];
public ListIterator()
{
for (int i=0; i < N;i++) {items[i] = randeque[i];}
StdRandom.shuffle(items);
}
public boolean hasNext() { return index < N;}
public void remove() { throw new UnsupportedOperationException(); }
public Item next()
{
if(!hasNext()) throw new java.util.NoSuchElementException();
Item item = items[index++];
return item;
}
}
private void resize(int size)
{
if(N>0 && N == size/4) {size=size/2;}
else if(N == size) {size=2*size;}
Item[] resized = (Item[]) new Object[size];
for(int i=0; i<size(); i++)
{
resized[i] = randeque[i];
}
randeque = resized;
}
@SuppressWarnings("unchecked")
public static void main(String[] args)// unit testing
{
RandomizedQueue<Integer> q = new RandomizedQueue<Integer>();
Integer[] s = new Integer[]{1,2,3,4,5,6,7,8,9};
int k = s.length;
for(int i=0; i<k; i++)
{
q.enqueue(s[i]);
}
for(int i=0; i<k; i++)
{
StdOut.println(q.dequeue());
}
}
}
<file_sep>import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation
{
private boolean [] [] neighbors;
private WeightedQuickUnionUF gridUf;
private int length;
private int cells;
private int openCount;
/**
*
* @param N , The number of cells in the grid
*/
// create N by N grid, with all sites blocked
public Percolation(int N)
{
neighbors = new boolean [N] [N];
//
cells = N*N+2;
length = N;
gridUf = new WeightedQuickUnionUF(cells);
for(boolean [] i : neighbors)
{ for(boolean j: i)
{
j = false;
}}
}
// open site (row i, column j) if it is not open already
public void open(int i, int j)
{
neighbors [i-1] [j-1] = true;
openCount++;
if(i == 1)
{
gridUf.union(0, qfCell(i,j));
//backwash.union(virtualTop, qfCell(i,j));
//The backwash problem can be solved by either using a parallel uf object or tracking
//the state of each cell in a 2d boolean array, but my attempts at both were off and aren't included here.
}
if(i == length)
{
gridUf.union(cells-1, qfCell(i,j));
}
if((boundsCheck(i-1,j)))
{ if(isOpen(i-1,j))
{
gridUf.union(qfCell(i-1 , j),qfCell(i , j));
}
}
if((boundsCheck(i+1,j))) if (isOpen(i+1,j)){gridUf.union(qfCell(i+1 , j),qfCell(i , j));}
if((boundsCheck(i,j+1))) if (isOpen(i,j+1)){gridUf.union(qfCell(i , j+1),qfCell(i , j));}
if((boundsCheck(i,j-1))) if (isOpen(i,j-1)){gridUf.union(qfCell(i , j-1),qfCell(i , j));}
}
private boolean boundsCheck(int i, int j)
{
return ((i <= length && i > 0)&&(j <= length && j > 0));
}
// is site (row i, column j) open?
boolean isOpen(int i, int j)
{
System.out.println(i+" "+j);
return neighbors [i-1][j-1];
}
// is site (row i, column j) full?
public boolean isFull(int i, int j)
{
return neighbors [i][j];
}
// does the system percolate?
public boolean percolates()
{
return gridUf.connected(0 , cells-1);
}
//convert the grid coordinate to something the union method can use.
private int qfCell(int i, int j)
{
return ((i-1)*length)+j;
}
public int numberOfOpenSites()
{
return openCount;
}
}
<file_sep>import java.util.Arrays;
import java.util.Comparator;
import edu.princeton.cs.algs4.MinPQ;
public class Board
{
private final int N;
private final int [][]blocks;
private int nn;
private int n ;
private MinPQ<Board> pq = new MinPQ();
private int[][] goal;
private Board previous=null;
private int zeroLoc;
// construct a board from an N-by-N array of blocks
// (where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks)
{
n = blocks.length;//rows
nn = blocks[0].length;//columns
N = n * nn;//total blocks
this.blocks = blocks;
findGoal();
isGoal();
pq.insert(this);
pq.delMin().findNeighbors();
}
// board size N
public int size()
{
return N;
}
// number of blocks out of place
public int hamming()
{
int d=0;
int index=1;
for (int i=0; i<n; i++)
{
for(int j=0; j<nn; j++)
{
if (blocks[i][j]==0)
{
continue;
}
if (!(blocks[i][j]==index))
{
d++;
}
index++;
}
}
return d;
}
// sum of Manhattan distances between blocks and goal
public int manhattan()
{
int d=0;
for (int i=0; i<n; i++)
{
for(int j=0; j<nn; j++)
{
if (blocks[i][j]==0)
{
continue;
}
if(goal[i][j]!=blocks[i][j])
d+= Math.abs(i - findGoal('r', blocks[i][j]))+Math.abs(j - findGoal('c', blocks[i][j]));
}
}
return d;
}
//comparator for MinPQ, this might be backwards.
public static Comparator<Board> byManhattan()
{
return new Comparator<Board>()
{
@Override
public int compare(Board b1, Board b2)
{
if (b1.compareTo(b2)< 0) return 1;
else if (b1.compareTo(b2)== 0)return 0;
else return -1;
}
};
}
//comparator for MinPQ, this might be backwards.
protected int compareTo(Board b2)
{
Integer b1b = manhattan();
Integer b2b = b2.manhattan();
return b1b.compareTo(b2b);
}
//This is supposed to create an 2d array with the solution.
private void findGoal()
{
int k=1;
for (int i=0; i<n; i++)
{
for(int j=0; j<nn; j++)
{
goal = new int[n][nn];
goal[i][j]=k;
k++;
}
}
goal[n-1][nn-1]=0;
}
//finds the row or column location of a value in blocks
private int findGoal(char c, int r)
{
int k = 0;
switch(c)
{
case'r':
for (int i=0; i<n; i++)
{
for(int j=0; j<nn; j++)
{
if(blocks[i][j]==r)
{
k=i;
}
}
}
case 'c':
for (int i=0; i<n; i++)
{
for(int j=0; j<nn; j++)
{
if(blocks[i][j]==r)
{
k=j;
}
}
}
}
return k;
}
// is this board the goal board?
public boolean isGoal()
{
if (hamming()==0)
{
return true;
}
else
return false;
}
// is this board solvable?//Check inversions
public boolean isSolvable()
{
int k=0;
for (int i=0; i<n; i++)
{
for(int j=0; j<nn; j++)
{
if (blocks[i][j]==0)
{
continue;
}
if (goal[i][j]<blocks[i][j])
{
k++;
}
}
};
if (N % 2 == 1)
{
return (k % 2 != 1);
}
else if(N % 2 == 0)
{
return ((k + zeroLoc) % 2 != 0);
}
else return false;
}
public boolean equals(Object y)
{
if (this == y)
return true;
if (y == null)
return false;
if (getClass() != y.getClass())
return false;
Board other = (Board) y;
if (!Arrays.deepEquals(this.blocks, other.blocks))
return false;
return true;
}
// all neighboring boards
public Iterable<Board> neighbors()
{
return pq;
}
//<NAME> 2420
private void makeNeighbors(int n, int nn)
{
for (int i=0;i<=3; i++)
{
int[][] b = blocks;
int zero = b[n][nn];
int r=0;
int c=0;
if(i==0){r=n+1; c=nn;}//up
if(i==1){r=n-1; c=nn;}//down
if(i==2){r=n; c=nn+1;}//right
if(i==3){r=n; c=nn-1;}//left
if(inBounds(n,nn))
{
b[n][nn] = b[r][c];
b[r][c] = zero;
Board brd = new Board(b);
brd.setPrevious(this);
pq.insert(brd);
}
}
}
private void findNeighbors()
{
for(int i=0;i<n;i++)
{
for(int j=0; j <nn; j++)
{
if (blocks[i][j]==0)
{
zeroLoc=i;
makeNeighbors(i,j);
}
}
}
}
public void setPrevious(Board previous)
{
this.previous = previous;
}
public Board getPrevious()
{
return this.previous;
}
private boolean inBounds(int n, int nn)
{
return n >= 0 && n < this.n && nn >= 0 && nn < this.nn;
}
// string representation of this board (in the output format specified below)
public String toString() {
StringBuilder s = new StringBuilder();
s.append(N + "\n");
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
s.append(String.format("%2d ", blocks[i][j]));
}
s.append("\n");
}
return s.toString();
}
public static void main(String[] args)
{
}
}
<file_sep>//<NAME> KDtrees 2420 Summer 2016
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.RedBlackBST;
public class PointST<Value>
{
private RedBlackBST table;
// construct an empty symbol table of points
public PointST()
{
table = new RedBlackBST<Point2D, Value>();
}
// is the symbol table empty?
public boolean isEmpty()
{
return table.isEmpty();
}
// number of points
public int size()
{
return table.size();
}
// associate the value val with point p
public void insert(Point2D p, Value v)
{
table.put(p,v);
}
// value associated with point p
public Value get(Point2D p)
{
return (Value) table.get(p);
}
// does the symbol table contain point p?
public boolean contains(Point2D p)
{
return table.contains(p);
}
// all points that are inside the rectangle
public Iterable<Point2D> range(RectHV rect)
{
Queue<Point2D> queue = new Queue<Point2D>();
for (Point2D p : points())
{
if (rect.contains(p))
{
queue.enqueue(p);
}
}
return queue;
}
// all points in the symbol table
public Iterable<Point2D> points()
{
return (Iterable<Point2D>) table;
}
// a nearest neighbor to point p; null if the symbol table is empty
public Point2D nearest(Point2D p)
{
double distance = Double.MAX_VALUE;
Point2D nearest = null;
for (Point2D point : points())
{
if (p.distanceTo(point) < distance)
{
distance = p.distanceTo(point);
nearest = point;
}
}
return nearest;
}
// public static void main(String[] args) {}
}
<file_sep>public class PercolationStats {
private double experiments[];
private int N;
// perform T independent computational experiments on an N-by-N grid
public PercolationStats(int N, int T)
{
experiments = new double[T];
this.N = N;
int t = 0;
if (N <= 0)
{
throw new IllegalArgumentException();
}
if (T <= 0)
{
throw new IllegalArgumentException();
}
while (t < T)
{
Percolation percolation = new Percolation(N);
boolean[][] grid = new boolean[N+1][N+1];
int i = 0;
while(true)
{
i++;
if(true)
{
int x = StdRandom.uniform(N) + 1;
int y = StdRandom.uniform(N) + 1;
if (grid[x][y]){
continue;
}
else
{
percolation.open(x, y);
grid[x][y] = true;
}
}
if (percolation.percolates())
{
experiments[t] = (double)i / ((double)N * (double)N);
break;
}
}
t++;
}
}
// sample mean of percolation threshold
public double mean()
{
return StdStats.mean(experiments);
}
// sample standard deviation of percolation threshold
public double stddev()
{
return StdStats.stddev(experiments);
}
// returns lower bound of the 95% confidence interval
public double confidenceLow()
{
return mean() - 1.96*stddev() / Math.sqrt(N);
}
// returns upper bound of the 95% confidence interval
public double confidenceHigh()
{
return mean() + 1.96*stddev()/ Math.sqrt(N);
}
// test client, described below
public static void main(String[] args)
{
System.out.println("Enter N:");
int N = StdIn.readInt();
System.out.println("Enter T:");
int T = StdIn.readInt();
PercolationStats percolationStats = new PercolationStats(N, T);
StdOut.println("mean = " + percolationStats.mean());
StdOut.println("stddev = " + percolationStats.stddev());
StdOut.println("95% confidence interval " + percolationStats.confidenceLow() + ", " + percolationStats.confidenceHigh());
}
}
<file_sep># CSIS-2420---Algorithms-Data-Structures
Summer2016
<file_sep>/*
* <NAME>
* CSIS 2420
*/
import java.util.Arrays;
import java.util.Comparator;
public class Term implements Comparable<Term> {
private String query;
private double weight;
// Initialize a term with the given query string and weight.
public Term(String query, double weight)
{
if (query == null) throw new java.lang.NullPointerException();
if (weight < 0) throw new java.lang.IllegalArgumentException();
this.query=query;
this.weight=weight;
}
@Override
public int compareTo(Term that)
{
return getQuery().compareTo(that.getQuery());
}
// Compare the terms in descending order by weight.
public static Comparator<Term> byReverseWeightOrder()
{
return new Comparator<Term>()
{
@Override
public int compare(Term arg0, Term arg1)
{
double a = arg0.getWeight();
double b = arg1.getWeight();
//Returns 1 when b is greater than a so the weights are evaluated in descending order.
if (a < b) return 1;
else if (a == b)return 0;
else return -1;
}
};
}
// Compare the terms in lexicographic order but using only the first r characters of each query.
public static Comparator<Term> byPrefixOrder(final int r)
{
if(r<0) throw new java.lang.IllegalArgumentException();
return new Comparator<Term>()
{
@Override
public int compare(Term arg0, Term arg1)
{
int prefix = arg0.query.length() > arg1.query.length() ?
arg1.query.length()
:arg0.query.length();
if (r < prefix) prefix = r;//If r is less the the shortest string, it's okay to use as the search prefix.
String a = arg0.query.substring(0, prefix);
String b = arg1.query.substring(0, prefix);
if (a.compareTo(b)< 0) return 1;
else if (a.compareTo(b)== 0)return 0;
else return -1;
}
};
}
public double getWeight()
{
return weight;
}
public String getQuery()
{
return query;
}
/* Testing
public static void main(String[] args)
{
Term term1 = new Term("lon",19);
Term term2 = new Term("lpn",20);
System.out.println(Term.byPrefixOrder(4).compare(term1, term2));
System.out.println(Term.byReverseWeightOrder().compare(term1, term2));
}*/
}
| f51eb3185a870faa426bce39debed80c7e57fbea | [
"Markdown",
"Java"
] | 7 | Java | sbenjam1n/CSIS-2420---Algorithms-Data-Structures- | c182c3351998f2409582384678b59676be750268 | cebf3bbd982edaeb7afe0d865f456e0e218f9fc6 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package goldenbug;
import java.awt.event.ActionEvent;
import java.util.Map;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* @author alex
*/
public class CustomTextfield extends JTextField {
private JTextField letra;
private Map<Character,Character> map;
public void setTraduccionText(String text){
this.letra.setText(text);
}
public CustomTextfield(JTextField traduccion, Map<Character,Character> map){
this.letra=traduccion;
this.map=map;
}
public void updateMap(){
char letra='*';
if(!this.getText().isEmpty()){
letra=this.getText().charAt(0);
}
this.map.put(this.letra.getText().charAt(0),letra);
}
}
<file_sep># Golden-Bug
Cryptanalysis tool used to break monoalphabetic substitution ciphers. It is based on "The gold bug" story by <NAME>.
| 754397e163aaa82373f3fa806fdca72881e84e54 | [
"Markdown",
"Java"
] | 2 | Java | amoyag00/Golden-Bug | 87b87539cbf5df9500634eb136c3aa006a9face3 | e964ce39b43f5907d876378c1f24ddad5af2f876 |
refs/heads/master | <repo_name>FoxAlex98/ToDoCT_Bot<file_sep>/settings.py
import yaml
with open('conf/settings.yaml') as yaml_conf:
config_map = yaml.safe_load(yaml_conf)
TOKEN = config_map["token"]
<file_sep>/main.py
import telepot
from settings import *
TelegramBot = telepot.Bot(TOKEN)
print (TelegramBot.getMe())
print ("\n")
print (TelegramBot.getUpdates())
def on_chat_message(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
name = msg["from"]["first_name"]
if content_type == 'text':
bot.sendMessage(chat_id, 'ciao ' + name)
bot = telepot.Bot(TOKEN)
bot.message_loop(on_chat_message)
print ("Listening ...")
import time
while 1:
time.sleep(10)
| cd87cee7a217da0f4f7a441a97c1325d73f9985a | [
"Python"
] | 2 | Python | FoxAlex98/ToDoCT_Bot | fff74abb72c16e0663464c1814e6512ebbe6a165 | 99c43670bcda30390b60f0701d88d02f84966127 |
refs/heads/master | <repo_name>EnnBi/Letter_Template<file_sep>/src/main/java/com/aaratech/letter/controller/LetterTemplateController.java
package com.aaratech.letter.controller;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.aaratech.letter.dao.AttributeRepo;
import com.aaratech.letter.dao.LetterTemplateRepo;
import com.aaratech.letter.model.Attribute;
import com.aaratech.letter.model.LetterTemplate;
import com.itextpdf.html2pdf.HtmlConverter;
@Controller
@RequestMapping("/letter")
public class LetterTemplateController {
@Autowired
LetterTemplateRepo letterTemplateRepo;
@Autowired
AttributeRepo attributeRepo;
final String ACTIVE="Active";
final String INACTIVE="Inactive";
final String APPROVED="Approved";
final String CREATED="Created";
final String WAITING="Waiting for Approval";
final String PATH = "D:\\reports_output\\";
@RequestMapping(value="/template",method=RequestMethod.POST)
public @ResponseBody ResponseEntity<?> saveTemplate(LetterTemplate letterTemplate,Model model){
if(letterTemplate.getId()>0){
LetterTemplate existingLT = letterTemplateRepo.findById(letterTemplate.getId()).orElse(null);
letterTemplate.setCreatedBy(existingLT.getCreatedBy());
letterTemplate.setCreatedOn(existingLT.getCreatedOn());
letterTemplate.setApprovalStatus(CREATED);
letterTemplate.setStatus(existingLT.getStatus());
letterTemplate.setUpdatedOn(new Date());
}
else{
letterTemplate.setCreatedOn(new Date());
letterTemplate.setStatus(ACTIVE);
letterTemplate.setApprovalStatus(CREATED);
}
letterTemplate = letterTemplateRepo.save(letterTemplate);
return ResponseEntity.ok(letterTemplate);
}
@GetMapping("/submitForApproval/{id}")
public @ResponseBody ResponseEntity<?> submitForApproval(@PathVariable("id") long id){
LetterTemplate letterTemplate = letterTemplateRepo.findById(id).orElse(null);
letterTemplate.setApprovalStatus(WAITING);
letterTemplate = letterTemplateRepo.save(letterTemplate);
return ResponseEntity.ok(letterTemplate);
}
@GetMapping("/approve/{id}")
public @ResponseBody ResponseEntity<?> approve(@PathVariable("id") long id){
LetterTemplate letterTemplate = letterTemplateRepo.findById(id).orElse(null);
letterTemplate.setApprovalStatus(APPROVED);
letterTemplate = letterTemplateRepo.save(letterTemplate);
return ResponseEntity.ok(letterTemplate);
}
@RequestMapping(value="/manage",method=RequestMethod.GET)
public String searchTemplate(Model model){
if(!model.asMap().containsKey("letterTemplate"))
model.addAttribute("letterTemplate", new LetterTemplate());
model.addAttribute("keys", attributeRepo.findAllKeys(ACTIVE));
model.addAttribute("templates", letterTemplateRepo.findByStatusAndApprovalStatusIn(ACTIVE,Arrays.asList(CREATED,APPROVED)));
return "search";
}
@RequestMapping(value="/authorize",method=RequestMethod.GET)
public String authorizeTemplate(Model model){
model.addAttribute("letterTemplate", new LetterTemplate());
model.addAttribute("templates", letterTemplateRepo.findByStatusAndApprovalStatusIn(ACTIVE,Arrays.asList(WAITING)));
return "authorize";
}
@RequestMapping(value="/edit/{id}",method=RequestMethod.GET)
public @ResponseBody ResponseEntity<?> edit(@PathVariable("id") long id,Model model){
LetterTemplate template = letterTemplateRepo.findById(id).orElse(null);
return ResponseEntity.ok(template);
}
@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)
public @ResponseBody ResponseEntity<?> delete(@PathVariable("id") long id){
letterTemplateRepo.deleteById(id);
return ResponseEntity.ok("");
}
@RequestMapping(value="/template/{name}",method=RequestMethod.GET)
public @ResponseBody ResponseEntity<?> generateTemplate(@PathVariable("name") String name){
LetterTemplate template= letterTemplateRepo.findByName(name);
List<String> keys = new ArrayList<String>(Arrays.asList(StringUtils.substringsBetween(template.getBody(),"${","}")));
String body = template.getBody();
List<Attribute> attributes = attributeRepo.findByKeyIn(keys);
for (Attribute attribute : attributes) {
if(attribute.getWidth()>0) {
String imgTag ="<img src="+attribute.getValue()+" width="+attribute.getWidth()+" height="+attribute.getHeight()+"/>";
body=body.replace(valueKey(attribute.getKey()), imgTag);
}
else
body = body.replace(valueKey(attribute.getKey()),attribute.getValue());
}
List<String> attachments = new ArrayList<>();
attachments.add(PATH+"img1.jpg");
attachments.add(PATH+"img2.jpg");
attachments.add(PATH+"img3.jpg");
body = body.concat("<br><br><br><br><br>");
body=body.concat("<div style='page-break-before:always'></div>");
for (String image : attachments) {
String imgTag ="<img src="+image+"/><br><br>";
body = body.concat(imgTag);
}
String fileName = PATH+template.getName()+".pdf";
generatePdf(body, fileName);
return ResponseEntity.ok("");
}
@GetMapping("/attributes")
public @ResponseBody String addAttributes(){
Attribute attribute = new Attribute("name",0, 0, "Ravi",ACTIVE);
attributeRepo.save(attribute);
Attribute attribute2 = new Attribute("date",0, 0, "07-2020",ACTIVE);
attributeRepo.save(attribute2);
Attribute attribute3 = new Attribute("cost",0, 0, "1857",ACTIVE);
attributeRepo.save(attribute3);
Attribute attribute4 = new Attribute("image",50, 20, PATH+"logo.png",ACTIVE);
attributeRepo.save(attribute4);
return "good";
}
public void generatePdf(String body,String fileName){
try {
HtmlConverter.convertToPdf(body, new FileOutputStream(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String valueKey(String key){
return "${"+key+"}";
}
}
| 1a6529fa70b58eb5017f8538de7fb1bbca423c5b | [
"Java"
] | 1 | Java | EnnBi/Letter_Template | 05f7b7ef474dfdb59561998ba6dfbd2fdfa6fc23 | 532c5f11cb6c57474efb35f38781b8e0a5c9e448 |
refs/heads/master | <repo_name>carlosfe2014/pruebagit<file_sep>/MovieDBAPI/app/src/main/java/pe/edu/cibertec/moviedbapi/PeliculaAdapter.java
package pe.edu.cibertec.moviedbapi;
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.bumptech.glide.Glide;
import java.util.ArrayList;
class PeliculaAdapter extends RecyclerView.Adapter<PeliculaAdapter.LayoutPelicula> {
ArrayList<Movie> peliculas;
public PeliculaAdapter(ArrayList<Movie> peliculas) {
this.peliculas = peliculas;
}
@NonNull
@Override
public LayoutPelicula onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater
.from(viewGroup.getContext())
.inflate(R.layout.pelicula_layout, viewGroup, false);
LayoutPelicula layoutPelicula = new LayoutPelicula(view);
return layoutPelicula;
}
@Override
public void onBindViewHolder(@NonNull LayoutPelicula layoutPelicula, int position) {
layoutPelicula.tvNombre.setText(peliculas.get(position).getTitle());
layoutPelicula.tvOverview.setText(peliculas.get(position).getOverview());
layoutPelicula.tvDate.setText(peliculas.get(position).getReleaseDate());
String url = "https://image.tmdb.org/t/p/w185/" + peliculas.get(position).getPosterPath();
Glide.with(layoutPelicula.itemView).load(url).into(layoutPelicula.ivMovie);
}
@Override
public int getItemCount() {
return peliculas.size();
}
public class LayoutPelicula extends RecyclerView.ViewHolder {
TextView tvNombre;
TextView tvOverview;
TextView tvDate;
ImageView ivMovie;
public LayoutPelicula(@NonNull View itemView) {
super(itemView);
tvNombre = itemView.findViewById(R.id.tvNombre);
tvOverview = itemView.findViewById(R.id.tvOverview);
tvDate = itemView.findViewById(R.id.tvDate);
ivMovie = itemView.findViewById(R.id.ivMovie);
}
}
}
<file_sep>/MovieDBAPI/app/src/main/java/pe/edu/cibertec/moviedbapi/MovieResponse.java
package pe.edu.cibertec.moviedbapi;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
class MovieResponse {
@SerializedName("results")
private ArrayList<Movie> peliculas;
public ArrayList<Movie> getPeliculas() {
return peliculas;
}
public void setPeliculas(ArrayList<Movie> peliculas) {
this.peliculas = peliculas;
}
}
| 943d6bb76cc583d6aef8fe909ad88ea387e68fa0 | [
"Java"
] | 2 | Java | carlosfe2014/pruebagit | 6d1851e0d63658bde0e22b3c1516cb595254c758 | 9ad7d400c3f3bc4ebfb8e1611c9ae29b4b3ebd6b |
refs/heads/master | <repo_name>sabhishek78/merge_linked_list<file_sep>/index.js
let listA = {
value : 2,
next: {
value : 3,
next : {
value : 7
}
}
};
let listB = {
value: 1,
next: {
value : 5,
next: {
value : 8,
next: {
value : 9
}
}
}
};
let listD = { value: 6 };
function mergeLinkedLists(listArray){
let listResult = { val : -1, next : null };
let pointerResult=listResult;
while(anyPointerIsNotUndefined(listArray)){
let [minimumValue,indexOfMinimumValue]=findMinimumValueNode(listArray);
if(listArray[indexOfMinimumValue].next){
listArray[indexOfMinimumValue]=listArray[indexOfMinimumValue].next ;
}
else{
console.log("hello");
listArray[indexOfMinimumValue]=undefined;
}
let newNode={value:minimumValue};
pointerResult.next=newNode;
pointerResult=pointerResult.next;
}
return JSON.stringify(listResult.next);
}
function anyPointerIsNotUndefined(listArray){
return listArray.some((e)=>e!==undefined);
}
function findMinimumValueNode(listArray){
console.log(listArray);
let valueArray=[];
for(let i=0;i<listArray.length;i++){
if(listArray[i]!==undefined){
valueArray.push(listArray[i].value);
}
else if(listArray[i]===undefined){
valueArray.push(undefined);
}
}
let minimumValue=findMinimumValue(valueArray);
let indexOfMinimumValue=valueArray.indexOf(minimumValue);
return [minimumValue,indexOfMinimumValue];
}
function findMinimumValue(valueArray){
let temp=[];
for(let i=0;i<valueArray.length;i++){
if(valueArray[i]!==undefined){
temp.push(valueArray[i]);
}
}
return Math.min(...temp);
}
console.log(mergeLinkedLists([listA, listB,listD])); | 3030fa8b162da1b391265da3aa16802a3a27c7a3 | [
"JavaScript"
] | 1 | JavaScript | sabhishek78/merge_linked_list | 5b6dabd07acde43b675a95629660c46173183a6d | 639c7e3361251f09f4f0fb5f92b8cb07bda12bb5 |
refs/heads/master | <file_sep>// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
'use strict';
var Caml_obj = require("bs-platform/lib/js/caml_obj.js");
var Belt_List = require("bs-platform/lib/js/belt_List.js");
var Pervasives = require("bs-platform/lib/js/pervasives.js");
var Input$MyNewProject = require("./Input.bs.js");
function digits(n) {
var _acc = /* [] */0;
var _n = n;
while(true) {
var n$1 = _n;
var acc = _acc;
if (n$1 <= 0) {
return acc;
} else {
var x = n$1 % 10;
_n = n$1 / 10 | 0;
_acc = /* :: */[
x,
acc
];
continue ;
}
};
}
function count(xs, y) {
return Belt_List.length(Belt_List.keep(xs, (function (x) {
return Caml_obj.caml_equal(x, y);
})));
}
function hasAdjecent(xs) {
return Belt_List.some(xs, (function (x) {
return count(xs, x) === 2;
}));
}
function isIncreasing(xs) {
var _last = Pervasives.min_int;
var _xs = xs;
while(true) {
var xs$1 = _xs;
var last = _last;
if (xs$1) {
var rest = xs$1[1];
var m = xs$1[0];
if (Caml_obj.caml_equal(last, m)) {
_xs = rest;
continue ;
} else if (Caml_obj.caml_greaterthan(m, last)) {
_xs = rest;
_last = m;
continue ;
} else {
return false;
}
} else {
return true;
}
};
}
function range(from, to_) {
var _acc = /* [] */0;
var from$1 = from;
var _to_ = to_ + 1 | 0;
while(true) {
var to_$1 = _to_;
var acc = _acc;
var n = to_$1 - 1 | 0;
if (n === from$1) {
return /* :: */[
n,
acc
];
} else {
_to_ = n;
_acc = /* :: */[
n,
acc
];
continue ;
}
};
}
function run(param) {
return Belt_List.length(Belt_List.keep(Belt_List.keep(Belt_List.keep(Belt_List.map(range(param[0], param[1]), digits), (function (xs) {
return Belt_List.length(xs) === 6;
})), hasAdjecent), isIncreasing));
}
console.log(run(Input$MyNewProject.input));
exports.digits = digits;
exports.count = count;
exports.hasAdjecent = hasAdjecent;
exports.isIncreasing = isIncreasing;
exports.range = range;
exports.run = run;
/* Not a pure module */
<file_sep>// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
'use strict';
var Belt_Id = require("bs-platform/lib/js/belt_Id.js");
var Belt_Map = require("bs-platform/lib/js/belt_Map.js");
var Belt_Set = require("bs-platform/lib/js/belt_Set.js");
var Caml_obj = require("bs-platform/lib/js/caml_obj.js");
var Belt_List = require("bs-platform/lib/js/belt_List.js");
var Pervasives = require("bs-platform/lib/js/pervasives.js");
var Belt_Option = require("bs-platform/lib/js/belt_Option.js");
var Caml_format = require("bs-platform/lib/js/caml_format.js");
var RList$Rationale = require("rationale/src/RList.js");
var Function$Rationale = require("rationale/src/Function.js");
var Input$MyNewProject = require("./Input.bs.js");
function cmp(param, param$1) {
var c = Caml_obj.caml_compare(param[0], param$1[0]);
if (c !== 0) {
return c;
} else {
return Caml_obj.caml_compare(param[1], param$1[1]);
}
}
var T = Belt_Id.MakeComparable({
cmp: cmp
});
function combine(xs) {
return Belt_List.reduceReverse(xs, /* [] */0, (function (acc, x) {
return Belt_Option.flatMap(acc, (function (xs) {
return Belt_Option.map(x, (function (x) {
return /* :: */[
x,
xs
];
}));
}));
}));
}
function split(param, param$1) {
return Function$Rationale.flip((function (prim, prim$1) {
return prim$1.split(prim);
}), param, param$1);
}
function parseSegment(str) {
var repeat = function (t, n) {
return RList$Rationale.repeat(t, Caml_format.caml_int_of_string(n));
};
var op = str.slice(0, 1);
var v = str.slice(1);
switch (op) {
case "D" :
return repeat(/* tuple */[
0,
-1
], v);
case "L" :
return repeat(/* tuple */[
-1,
0
], v);
case "R" :
return repeat(/* tuple */[
1,
0
], v);
case "U" :
return repeat(/* tuple */[
0,
1
], v);
default:
return ;
}
}
function parsePath(x) {
return Belt_List.flatten(Belt_Option.getWithDefault(combine(Belt_List.map(Belt_List.fromArray(split(x, ",")), parseSegment)), /* [] */0));
}
function step(a, b) {
var match = a > b;
if (match) {
return RList$Rationale.rangeInt(1)(b, a);
} else {
return RList$Rationale.rangeInt(1)(a, b);
}
}
function coordinates(segments) {
var map = Belt_Map.make(T);
return Belt_List.reduce(segments, /* tuple */[
/* tuple */[
0,
0
],
1,
map
], (function (param, param$1) {
var map = param[2];
var steps = param[1];
var match = param[0];
var next_000 = match[0] + param$1[0] | 0;
var next_001 = match[1] + param$1[1] | 0;
var next = /* tuple */[
next_000,
next_001
];
var match$1 = Belt_Map.has(map, next);
if (match$1) {
return /* tuple */[
next,
steps + 1 | 0,
map
];
} else {
return /* tuple */[
next,
steps + 1 | 0,
Belt_Map.set(map, next, steps)
];
}
}))[2];
}
function closest(m1, m2) {
var p1 = Belt_Set.fromArray(Belt_Map.keysToArray(m1), T);
var p2 = Belt_Set.fromArray(Belt_Map.keysToArray(m2), T);
var get = function (m, k) {
return Belt_Option.getWithDefault(Belt_Map.get(m, k), 0);
};
return Belt_List.reduce(Belt_List.map(Belt_Set.toList(Belt_Set.intersect(p1, p2)), (function (p) {
return get(m1, p) + get(m2, p) | 0;
})), Pervasives.max_int, (function (current, d) {
var match = d < current;
if (match) {
return d;
} else {
return current;
}
}));
}
function run(input) {
var paths = Belt_List.map(Belt_List.map(Belt_List.fromArray(split(input, "\n")), parsePath), coordinates);
if (paths) {
var match = paths[1];
if (match && !match[1]) {
return closest(paths[0], match[0]);
} else {
return 0;
}
} else {
return 0;
}
}
console.log(run(Input$MyNewProject.input));
exports.T = T;
exports.combine = combine;
exports.split = split;
exports.parseSegment = parseSegment;
exports.parsePath = parsePath;
exports.step = step;
exports.coordinates = coordinates;
exports.closest = closest;
exports.run = run;
/* T Not a pure module */
<file_sep>// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
'use strict';
var input = /* tuple */[
367479,
893698
];
exports.input = input;
/* No side effect */
<file_sep>// Generated by BUCKLESCRIPT, PLEASE EDIT WITH CARE
'use strict';
var List = require("bs-platform/lib/js/list.js");
var Block = require("bs-platform/lib/js/block.js");
var Curry = require("bs-platform/lib/js/curry.js");
var Caml_int32 = require("bs-platform/lib/js/caml_int32.js");
var RList$Rationale = require("rationale/src/RList.js");
var Option$Rationale = require("rationale/src/Option.js");
var Input$MyNewProject = require("./Input.bs.js");
function write(env, reg, v) {
return RList$Rationale.update(v, reg, env);
}
function add(a, b) {
return a + b | 0;
}
var multi = Caml_int32.imul;
function lookup(env, n) {
return RList$Rationale.nth(n, env);
}
function toOps(param) {
return RList$Rationale.splitEvery(4, param);
}
function parseLine(l) {
if (l) {
var switcher = l[0] - 1 | 0;
if (switcher === 0 || switcher === 1) {
if (switcher !== 0) {
var match = l[1];
if (match) {
var match$1 = match[1];
if (match$1) {
var match$2 = match$1[1];
if (match$2 && !match$2[1]) {
return /* Mult */Block.__(1, [
match[0],
match$1[0],
match$2[0]
]);
}
}
}
} else {
var match$3 = l[1];
if (match$3) {
var match$4 = match$3[1];
if (match$4) {
var match$5 = match$4[1];
if (match$5 && !match$5[1]) {
return /* Add */Block.__(0, [
match$3[0],
match$4[0],
match$5[0]
]);
}
}
}
}
} else if (switcher === 98) {
var match$6 = l[1];
if (match$6) {
var match$7 = match$6[1];
if (match$7) {
var match$8 = match$7[1];
if (!(match$8 && match$8[1])) {
return /* Return */1;
}
} else {
return /* Return */1;
}
} else {
return /* Return */1;
}
}
}
console.log("Parse error:", l);
return /* Error */0;
}
function apply(f, a, b, dst, env) {
var __x = Curry._2(Option$Rationale.Infix.$less$$great, Curry._2(Option$Rationale.Infix.$less$$great, Curry._2(Option$Rationale.Infix.$less$star$great, Curry._2(Option$Rationale.Infix.$less$star$great, Curry._1(Option$Rationale.pure, f), RList$Rationale.nth(a, env)), RList$Rationale.nth(b, env)), (function (__x) {
return RList$Rationale.update(__x, dst, env);
})), (function (x) {
return /* Continue */Block.__(0, [x]);
}));
return Option$Rationale.$$default(/* Error */0, __x);
}
function $$eval(op, env) {
if (typeof op === "number") {
if (op === /* Error */0) {
return /* Error */0;
} else {
return /* Result */Block.__(1, [env]);
}
} else if (op.tag) {
return apply(multi, op[0], op[1], op[2], env);
} else {
return apply(add, op[0], op[1], op[2], env);
}
}
function run(input) {
var _env = input;
var _pc = 0;
while(true) {
var pc = _pc;
var env = _env;
var __x = Curry._2(Option$Rationale.Infix.$less$$great, Curry._2(Option$Rationale.Infix.$less$$great, RList$Rationale.nth(pc, RList$Rationale.splitEvery(4, env)), parseLine), (function(env){
return function (__x) {
return $$eval(__x, env);
}
}(env)));
var result = Option$Rationale.$$default(/* Error */0, __x);
if (typeof result === "number") {
return ;
} else if (result.tag) {
return result[0];
} else {
_pc = pc + 1 | 0;
_env = result[0];
continue ;
}
};
}
function range(__x) {
return RList$Rationale.rangeInt(1)(1, __x);
}
var __x = List.flatten(List.map((function (i) {
return List.map((function (j) {
return /* tuple */[
i,
j
];
}), RList$Rationale.rangeInt(1)(1, 99));
}), RList$Rationale.rangeInt(1)(1, 99)));
var res = List.find((function (param) {
var env = RList$Rationale.update(param[0], 1, Input$MyNewProject.input);
var res = Curry._2(Option$Rationale.Infix.$great$great$eq, run(RList$Rationale.update(param[1], 2, env)), (function (param) {
return RList$Rationale.nth(0, param);
}));
if (res !== undefined) {
return res === 19690720;
} else {
return false;
}
}), __x);
console.log(res);
var nth = RList$Rationale.nth;
exports.write = write;
exports.add = add;
exports.multi = multi;
exports.lookup = lookup;
exports.toOps = toOps;
exports.nth = nth;
exports.parseLine = parseLine;
exports.apply = apply;
exports.$$eval = $$eval;
exports.run = run;
exports.range = range;
exports.res = res;
/* __x Not a pure module */
| aa2e2af9fb2acd817b7f9a39acd42c0fbc48bdd8 | [
"JavaScript"
] | 4 | JavaScript | frekw/advent-of-code | 66449cdd23bbde187ce20023982dd2acafc1b989 | b5052b7bf18056f2d9d5c0609c42b959a1e939b4 |
refs/heads/master | <repo_name>lukecyca/cycamatic<file_sep>/example.ini
[instagram]
username=cycamatic
password=lol
throttle=300
caption=Testing #meow
source_dir=/opt/photos/
dest_dir=/opt/photos-processed/
<file_sep>/uploader.py
import time
import os
import os.path
import configparser
import pynstagram
def upload_photo(filepath, c):
print "Converting {}".format(filepath)
status = os.system(
"convert -auto-orient -sample 1280x1280^ -gravity Center "
"-extent 1280x1280 {} /tmp/small.jpg".format(filepath)
)
if status & 0xff00:
raise ValueError("Failed to convert")
print "Uploading {}".format(filepath)
with pynstagram.client(c['username'], c['password']) as client:
client.upload("/tmp/small.jpg", c['caption'])
def main():
config = configparser.ConfigParser()
config.read('config.ini')
c = config['instagram']
source_dir = os.path.abspath(c['source_dir'])
dest_dir = os.path.abspath(c['dest_dir'])
throttle = int(c['throttle'])
if not os.access(source_dir, os.R_OK | os.W_OK | os.X_OK):
raise ValueError("Need permission to {}".format(source_dir))
while True:
time.sleep(1)
for fn in os.listdir(source_dir):
path = os.path.join(source_dir, fn)
upload_photo(path, c)
print "Moving {}".format(path)
os.rename(path, os.path.join(dest_dir, fn))
time.sleep(throttle)
if __name__ == "__main__":
main()
<file_sep>/resizer.py
import time
import os
# -resize is best
# -scale
# -sample is fastest
INPUT_DIR = "/opt/photos/"
OUTPUT_DIR = "/root/slideshow/"
PROCESSED_DIR = "/opt/photos-processed/"
def move_photo(filepath):
print "Converting {}".format(filepath)
status = os.system(
"convert -resize '2000x2000>' {} {}cycamatic-{}.jpg".format(filepath, OUTPUT_DIR, int(time.time()))
#"convert -sample '2000x2000>' {} {}cycamatic-{}.jpg".format(filepath, OUTPUT_DIR, int(time.time()))
)
if status & 0xff00:
print("Failed to convert")
return False
return True
def main():
if not os.access(OUTPUT_DIR, os.R_OK | os.W_OK | os.X_OK):
raise ValueError("Need permission to {}".format(INPUT_DIR))
while True:
time.sleep(1)
for fn in os.listdir(INPUT_DIR):
path = os.path.join(INPUT_DIR, fn)
if move_photo(path):
print "Moving {}".format(path)
os.rename(path, os.path.join(PROCESSED_DIR, fn))
else:
print "Failed"
if __name__ == "__main__":
main()
<file_sep>/README.markdown
cycamatic photobooth
====================
This is a collection of scripts that run the
[Cycamatic photobooth](https://lukecyca.com/2015/cycamatic-photobooth.html).
I use this repo as a backup and personal changelog. It isn't a polished project
ready for you to deploy, but it might be useful if you're building your own
photobooth. :)
Dependencies
------------
* [pynstagram](https://github.com/mr0re1/pynstagram) for posting to Instagram
* [RPi.GPIO](https://pypi.python.org/pypi/RPi.GPIO) for flashing LEDs and detecting button press
* [gphoto2-cffi](https://github.com/jbaiter/gphoto2-cffi) for interacting with a DSLR camera
<file_sep>/photobooth.py
import RPi.GPIO as GPIO
import time
import datetime
import gphoto2 as gp
from gphoto2.backend import lib as gplib
import logging
import signal
import sys
import thread
# Pins
BUTTON = 27
READY_LED = 18
POSE_LED = 22
WAIT_LED = 17
def flash(pin, delay, count):
for _ in range(count):
GPIO.output(pin, True)
time.sleep(delay)
GPIO.output(pin, False)
time.sleep(delay)
def main():
logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON, GPIO.IN)
GPIO.setup(READY_LED, GPIO.OUT)
GPIO.setup(POSE_LED, GPIO.OUT)
GPIO.setup(WAIT_LED, GPIO.OUT)
# Fancy startup sequence
for _ in range(3):
GPIO.output(READY_LED, True)
time.sleep(0.05)
GPIO.output(POSE_LED, True)
time.sleep(0.05)
GPIO.output(WAIT_LED, True)
time.sleep(0.2)
GPIO.output(READY_LED, False)
time.sleep(0.05)
GPIO.output(POSE_LED, False)
time.sleep(0.05)
GPIO.output(WAIT_LED, False)
time.sleep(0.1)
# Catch signals and turn off LEDs upon exit
def signal_handler(signal, frame):
GPIO.output(READY_LED, False)
GPIO.output(POSE_LED, False)
GPIO.output(WAIT_LED, False)
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)
signal.signal(signal.SIGHUP, signal_handler)
# Connect to camera
cam = gp.Camera()
GPIO.output(READY_LED, True)
GPIO.output(POSE_LED, False)
GPIO.output(WAIT_LED, False)
lock = thread.allocate_lock()
while True:
if not GPIO.input(BUTTON):
continue
GPIO.output(READY_LED, False)
# Trigger capture
def trig():
try:
err = gplib.gp_camera_trigger_capture(cam._cam, cam._ctx)
if err != 0:
raise ValueError("gp_camera_trigger_capture returned {}".format(err))
except:
thread.interrupt_main()
lock.release()
lock.acquire()
thread.start_new_thread(trig, ())
flash(POSE_LED, 0.5, 2)
while lock.locked():
flash(POSE_LED, 0.125, 1)
GPIO.output(WAIT_LED, True)
# Wait for camera to process the photo
fobj = cam._wait_for_event(event_type=gplib.GP_EVENT_FILE_ADDED)
data = fobj.get_data()
try:
fobj.remove()
except gp.errors.CameraIOError:
pass
filename = datetime.datetime.now().strftime('/opt/photos/%Y-%m-%d-%H-%M-%S.%f.jpg')
print("Saving " + filename)
with open(filename, "wb") as fh:
fh.write(data)
flash(WAIT_LED, 0.5, 10)
GPIO.output(WAIT_LED, False)
GPIO.output(READY_LED, True)
time.sleep(0.01)
if __name__ == "__main__":
main()
<file_sep>/slideshow/node.lua
-- at which intervals should the screen switch to the
-- next image?
local INTERVAL = 12
-- enough time to load next image
local SWITCH_DELAY = 8
-- transition time in seconds.
-- set it to 0 switching instantaneously
local SWITCH_TIME = 0.8
assert(SWITCH_TIME + SWITCH_DELAY < INTERVAL,
"INTERVAL must be longer than SWITCH_DELAY + SWITCHTIME")
gl.setup(NATIVE_WIDTH, NATIVE_HEIGHT)
math.randomseed( os.time() )
local font = resource.load_font("SADSLices-Regular.otf")
local function shuffle( a )
local c = #a
for i = 1, (c * 20) do
local ndx0 = math.random( 1, c )
local ndx1 = math.random( 1, c )
local temp = a[ ndx0 ]
a[ ndx0 ] = a[ ndx1 ]
a[ ndx1 ] = temp
end
return a
end
-- Load all picture files into table, shuffled
local pictures = {}
for name, _ in pairs(CONTENTS) do
if name:match(".*jpg") or name:match(".*JPG") then
table.insert(pictures, math.random(1, #pictures), name)
end
end
print("Loaded images: ")
for k, v in pairs(pictures) do
print(" " .. v)
end
node.event("content_remove", function(filename)
for k, v in pairs(pictures) do
if filename == v then
table.remove(pictures, k)
print("Removed " .. filename)
end
end
end)
local new_pictures = {}
node.event("content_update", function(filename)
print("Detected " .. filename)
for k, v in pairs(pictures) do
if filename == v then
print("Skipped " .. filename)
return
end
end
if filename:match(".*jpg") or filename:match(".*JPG") then
print("Added " .. filename)
table.insert(new_pictures, filename)
end
end)
local current_image, fade_start
local current_image_num = 1
local function next_image()
local next_image_name
if #new_pictures > 0 then
table.insert(pictures, current_image_num, table.remove(new_pictures, 1))
end
next_image_name = pictures[current_image_num]
print("now loading " .. current_image_num .. ":" .. next_image_name)
last_image = current_image
current_image = resource.load_image(next_image_name)
fade_start = sys.now()
current_image_num = current_image_num + 1
if current_image_num > #pictures then
shuffle(pictures)
current_image_num = 1
end
end
util.set_interval(INTERVAL, next_image)
function node.render()
gl.clear(0,0,0,1)
if current_image == nil then
return
end
local delta = sys.now() - fade_start - SWITCH_DELAY
if last_image and delta < 0 then
draw_full(last_image, 0, 0, WIDTH, HEIGHT)
elseif last_image and delta < SWITCH_TIME then
local progress = delta / SWITCH_TIME
draw_full(last_image, 0, 0, WIDTH, HEIGHT, 1 - progress)
draw_full(current_image, 0, 0, WIDTH, HEIGHT, progress)
else
if last_image then
last_image:dispose()
last_image = nil
end
draw_full(current_image, 0, 0, WIDTH, HEIGHT)
end
--font:write(98, 38, "See your photos on Instagram @JurkeAndBill", 80, 0, 0, 0, 1)
--font:write(100, 40, "See your photos on Instagram @JurkeAndBill", 80, 1, 1, 1, 1)
end
function draw_full(obj, x1, y1, x2, y2, alpha)
--assumes x1 = x2 = 0
local img_w, img_h = obj:size()
local img_aspect_ratio = img_w / img_h
local viewport_aspect_ratio = x2 / y2
if img_aspect_ratio < viewport_aspect_ratio then
-- constained by width, compensate height
local scale_by = x2 / img_w
local h_adj = (img_h * scale_by - y2) / 2
pcall(function()
obj:draw(0, -h_adj, img_w * scale_by, img_h * scale_by - h_adj, alpha)
end)
else
-- constrained by height, compensate width
local scale_by = y2 / img_h
local w_adj = (img_w * scale_by - x2) / 2
pcall(function()
obj:draw(-w_adj, 0, img_w * scale_by - w_adj, img_h * scale_by, alpha)
end)
end
end
| e2e97780405ffcf3a5c29ed023681231ccdc369e | [
"Markdown",
"Python",
"INI",
"Lua"
] | 6 | INI | lukecyca/cycamatic | a52ede7e5d6e754e71daa6a6f6cad5478f461bf5 | 6b727bc77a7474627275c2f643445494ad68283a |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Node : MonoBehaviour, IPointerClickHandler {
public Transform unit; // Current occupant.
public bool traversable = true;
public Vector3 worldPosition;
public int[] gridPosition;
private SpriteRenderer spriteRen;
private Color32 originalColour;
private void Awake()
{
worldPosition = transform.position;
spriteRen = GetComponent<SpriteRenderer>();
originalColour = spriteRen.color;
}
public void OnPointerClick(PointerEventData pointerEventData)
{
// TODO: Get unit's Range.
if(GameGrid.selectedNode != null)
{
GameGrid.selectedNode.ResetNeighbours();
}
GameGrid.selectedNode = this;
// Hard-coded value is range value.
Node[] neighbours = GameGrid.GetNeighbours(gridPosition, 1);
for (int i = 0; i < neighbours.Length; i++)
{
neighbours[i].SetColour(new Color32(0, 255, 0, 255));
}
}
public void ResetNeighbours()
{
Node[] neighbours = GameGrid.GetNeighbours(gridPosition, 1);
for (int i = 0; i < neighbours.Length; i++)
{
if(neighbours[i].traversable)
neighbours[i].SetColour(originalColour);
}
}
private void SetColour(Color32 newColour)
{
spriteRen.color = newColour;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
[RequireComponent(typeof(GameGridGenerator))]
public class GameGrid : MonoBehaviour {
public LayerMask untraversableMask;
public static Node selectedNode;
private static Node[,] grid;
private void Awake()
{
CalculateGrid();
}
public void CalculateGrid()
{
Transform generatedGrid = transform.GetChild(0);
GameGridGenerator generator = GetComponent<GameGridGenerator>();
int rowSize = (int)generator.gridWorldSize.x;
int colSize = (int)generator.gridWorldSize.y;
grid = new Node[colSize, rowSize];
if (generatedGrid != null && (rowSize * colSize == generatedGrid.childCount))
{
int index = 0;
for (int y = 0; y < colSize; y++)
{
for (int x = 0; x < rowSize; x++)
{
Node node = generatedGrid.GetChild(index).GetComponent<Node>();
grid[y, x] = node;
node.gridPosition = new int[]{y, x};
index++;
}
}
}
}
// TODO: Use Range parameter.
public static Node[] GetNeighbours(int[] gridPosition, int range)
{
int row = gridPosition[0];
int col = gridPosition[1];
List<Node> nodeList = new List<Node>();
// Left Neighbour.
if(row > 0)
{
nodeList.Add(grid[row - 1, col]);
}
// Right Neighbour.
if(row < grid.GetLength(0) - 1)
{
nodeList.Add(grid[row + 1, col]);
}
// Top Neighbour.
if(col > 0)
{
nodeList.Add(grid[row, col - 1]);
}
// Bottom Neighbour.
if(col < grid.GetLength(1) - 1)
{
nodeList.Add(grid[row, col + 1]);
}
return nodeList.ToArray();
}
}
| af2365e9b91b471a68c6079f56114ad35a7fc7a0 | [
"C#"
] | 2 | C# | ChrisDubeau/Game-Off-2018 | 95b77c310456f5e140c5226ed285f9f716fdacde | e1ad7b379845072c6b1efe6975678330d8aac165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.